我目前正在开发一个使用异步下载的iPad iOS 6应用程序。为了接收进度信息,我使用了委托NSURLConnectionDownloadDelegate
。下载和收到的进度
– connection:didWriteData:totalBytesWritten:expectedTotalBytes:
工作得很好。
但是一旦下载完成,我不知道如何从委托方法提供的NSURL
destinationURL
中提取数据
– connectionDidFinishDownloading:destinationURL:
字符串中接收的目标网址如下所示"/private/var/mobile/Applications/7CB3B194-9E79-4F0B-ACFD-7B87AA8C7BAF/tmp/filename.mp4
"
然后我尝试从给定的NSURL中提取数据:
NSData *data = [[NSData alloc] initWithContentsOfURL:destinationURL];
但是数据是空的...
NSLog(@"data Size: %@", data.length); //prints out 0
有人使用NSURLConnectionDownloadDelegate
有同样的问题吗?有什么想法如何解决吗?
编辑:我尝试先复制文件,然后按照建议使用[NSData initWithContentsOFFile]
,但数据大小仍然是0。
- (void) connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
[[NSFileManager defaultManager] copyItemAtPath:destinationURL.path toPath:DEST_PATH error:nil];
NSData *data = [[NSData alloc] initWithContentsOfFile:DEST_PATH];
NSLog(@"data Size: %i", data.length); //still returns 0..
}
编辑2:我可以在使用sendAsynchronousRequest
NSURLConnection
方法时提取NSData
。但是像这样,我无法确定下载进度...
[NSURLConnection sendAsynchronousRequest:theRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (data){
NSLog(@"Size of the data: %i Bytes(s)", data.length); //works fine
[data writeToFile:DEST_PATH atomically:YES];
//From this point i can use the file at DEST_PATH
NSLog(@"Succeeded!");
}
else if (error)
NSLog(@"%@",error);
}];
检查文件是否存在。我有同样的问题,我必须使用NSURLConnectionDataDelegate并手动保存数据,这就是为什么:NSURLConnectionDownloadDelegate 存在与某些文件扩展名相关的错误。
您也可以在此处看到相同问题的答案:NSURLConnectionDownloadDelegate file issue
/private/var/mobile/Applications/7CB3B194-9E79-4F0B-ACFD-7B87AA8C7BAF/tmp/filename.mp4
是路径,而不是 URL。试试 initWithContentOfFile: 代替。