我的应用程序从互联网下载视频并将其保存在iPhone中。
my app downloads a video from internet and saves it in the iPhone.
我正在使用此代码
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setHTTPMethod:@"GET"]; NSError *error; NSURLResponse *response; NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *videosFolderPath = [documentFolderPath stringByAppendingPathComponent:@"videos"]; //Check if the videos folder already exists, if not, create it!!! BOOL isDir; if (([fileManager fileExistsAtPath:videosFolderPath isDirectory:&isDir] && isDir) == FALSE) { [[NSFileManager defaultManager] createDirectoryAtPath:videosFolderPath withIntermediateDirectories:YES attributes:nil error:nil]; } NSString *filePath = [videosFolderPath stringByAppendingPathComponent:@"name.mp4"]; if ([fileManager fileExistsAtPath:filePath ] == YES) { NSLog (@"File exists"); } else { NSLog (@"File not found"); NSData *urlData; NSString *downloadPath = @"www.mywebsite/name.mp4"; [request setURL:[NSURL URLWithString:downloadPath]]; urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; BOOL written = [urlData writeToFile:filePath atomically:NO]; if (written) NSLog(@"Saved to file: %@", filePath); else {NSLog(@"problem");} }全部工作正常,但我想添加一个进度视图,以指示下载的状态。
All works fine, but I want to add a progress View, to indicate the status of the download.
问题(我想,但我不知道)是我的NSURLConnection本身不作为委托,所以方法如
The problem (I think but I'm not sure) is that my NSURLConnection hasn't itself as delegate, so methods like
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data或
-(void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{从未被调用。
我尝试使用
urlData = [[NSURLConnection alloc] initWithRequest:request delegate:self];但是当我尝试写入文件时,应用程序崩溃
but the app crashes when I try to write the file
[urlData writeToFile:filePath atomically:NO];我该怎么办? 谢谢
What can I do? Thanks
推荐答案您正在做的是发送同步请求,这意味着正在下载HTTP响应将挂起,直到所有数据都被提取。即使您不希望显示下载进度的任何指标,在UI线程上执行此操作也不会太好。我建议使用NSURLConnection类,设置它的委托和响应委托方法。可以在 snippets.aktagon/snippets/350-How-to-make-asynchronous-HTTP-requests-with-NSURLConnection 。
What you are doing is sending a "synchronous" request, meaning that the thread that is downloading the HTTP response will hang until all data has been fetched. It is never good to do this on a UI thread, even when you do not want display any indicator of the download's progress. I suggest using the NSURLConnection class, setting it's delegate, and responding to delegate methods. A small tutorial for this can be found at snippets.aktagon/snippets/350-How-to-make-asynchronous-HTTP-requests-with-NSURLConnection.
一次你是一个连接的代表,你可以在连接收到响应时获得内容长度:
Once you are a connection's delegate, you can get the content length when the connection receives a response:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response; contentSize = [httpResponse expectedContentLength]; }然后,计算新数据到达时下载的总体进度,做这样做:
Then, to calculate the total progress of the download whenever new data arrives, do something like this:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // download data is our global NSMutableData object that contains the // fetched HTTP data. [downloadData appendData:data]; float progress = (float)[downloadData length] / (float)contentSize; [progressView setValue:progress]; }更新:
另一个关于如何使用Foundation进行异步HTTP的示例: http: //codewithchris/tutorial-how-to-use-ios-nsurlconnection-by-example/
Another example on how to do async HTTP with Foundation: codewithchris/tutorial-how-to-use-ios-nsurlconnection-by-example/
更多推荐
了解更新UIprogressView的下载进度
发布评论