[objective-c]在 URLSession 中完成任务后返回值

标签: ios Objective-C
发布时间: 2016/10/2 13:51:26
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我在新的 Objective-c 和我一直在挣扎与此。我要去上课,要从服务器下载文件︰

@interface DownloadManager ()
@property (nonatomic, strong) NSString *bytesWritten;

@end

@implementation DownloadManager

- (void)downloadTaskStart {
    NSURL  *url = [NSURL URLWithString:@"http://somehost.com/somefile.zip];
    NSMutableURLRequest *downloadRequest = [NSMutableURLRequest requestWithURL:url
                                                                   cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                               timeoutInterval:60];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *downloadSession = [NSURLSession sessionWithConfiguration:config
                                                                  delegate:self
                                                             delegateQueue:[NSOperationQueue mainQueue]];


    downloadTask = [downloadSession downloadTaskWithRequest:downloadRequest];
    startTime = [NSDate timeIntervalSinceReferenceDate];
    [downloadTask resume];

}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error) {
        NSLog(@"Error when download: %@", error);
    } 

    //do something?
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    //do something?
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {            
    self.bytesWritten = [@(totalBytesWritten) stringValue];
}

@end

想做什么时,我向其发送消息 -(void)downloadTaskStart 从另一个类,然后得到 bytesWritten 值 (我使用单例),任务完成后,它会返回值 (或者与错误或不),不是在第一次的毫秒值。由于任何帮助 !

解决方法 1:

您可以使用

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error 

方法 NSURLSession ,当任务完成时,它将被称为和出错的情况下,并将值传递使用委托NSNotification

官方微信
官方QQ群
31647020