首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iPhone应用下载的NSURL连接未完成即终止

iPhone应用下载的NSURL连接未完成即终止
EN

Stack Overflow用户
提问于 2012-07-18 06:08:40
回答 1查看 762关注 0票数 1

我有这段代码可以从服务器上下载mp3。一切都是通过解析播客的表视图来设置的,mp3的链接是_entry.articleURL。几分钟后,iPhone终止了连接,我最终只下载了mp3的一小部分。你知道这是什么原因造成的吗?

代码语言:javascript
复制
-(void)didSelectRowAtIndexPath 
{     RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];

             self.nameit = entry.articleTitle;
             NSURL *url = [NSURL URLWithString:entry.articleUrl];    
             NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
             __block NSURLConnection *connection = [NSURLConnection connectionWithRequest:theRequest delegate:self];

             UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance

             __block UIBackgroundTaskIdentifier background_task; //Create a task object

             background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
                 // This code gets called when your app has been running in the background too long and the OS decides to kill it
                 // You might want to cancel your connection in this case, that way you won't receive delegate methods any longer.
                 [connection cancel];
                 [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
                 background_task = UIBackgroundTaskInvalid; //Set the task to be invalid

                 //System will be shutting down the app at any point in time now
             }];

             self.backgroundTaskIdentifier = background_task;
             if (connection) {
                 receivedData = [[NSMutableData data] retain];
                 self.thetable = tableView;
                 self.thepath = indexPath;
             }
             else {
                 UIAlertView *cancelled = [[UIAlertView alloc] initWithTitle:@"Download Failed" message:@"Please check your network settings, and then retry the download." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                 [cancelled show];
                 [cancelled release];
             }
}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
progress.hidden = NO;
downloadInProgress = YES;
RSSEntry *entry = [_allEntries objectAtIndex:thepath.row];

self.nameit = entry.articleTitle;
downloadlabel.text = [NSString stringWithFormat:@"%@", nameit];
[thebar addSubview:downloadlabel];
[receivedData setLength:0];
expectedBytes = [response expectedContentLength];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
float progressive = (float)[receivedData length] / (float)expectedBytes;
[progress setProgress:progressive];


}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
UIAlertView *connectionfailed = [[UIAlertView alloc] initWithTitle:@"Download Failed" message:@"Please check your network settings, and then retry the download." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[connectionfailed show];
[connectionfailed release];
progress.hidden = YES;
downloadInProgress = NO;
[downloadlabel removeFromSuperview];
[thetable deselectRowAtIndexPath:thepath animated:YES]; 
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
[connection release];



}

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[nameit stringByAppendingString:@".mp3"]];
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[receivedData writeToFile:pdfPath atomically:YES];
progress.hidden = YES;
downloadInProgress = NO;
[downloadlabel removeFromSuperview];

[thetable deselectRowAtIndexPath:thepath animated:YES]; 

[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}

问题是connectionDidFinishLoading似乎一直被调用,即使是不完整的。有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-18 06:19:21

我不确定你为什么要使用beginBackgroundTaskWithExpirationHandler来做这项工作--它的目的是为了一个完全不同的任务(在你的应用被移到后台之后做一些工作。您在前台使用它很可能是导致您的问题的原因。

我建议你去github等网站上寻找一个并发NSOperation示例项目,并用它们来做你的异步NSURLConnections。

此外,您还可以在回调中更新视图中的GUI元素。请记住,您必须在主线程上使用UIKit。如果您需要更新某些内容,只需使用一个块并将其分派到主队列进行更新。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11531577

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档