我是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
值(我使用单身)时,它将在任务完成后返回值(或者错误与否),而不是在第一个毫秒时的值。感谢您的帮助!
答案 0 :(得分:0)
您可以使用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
NSURLSession
的方法,因为它将在任务完成时调用,如果出现错误并传递值,请使用Delegates或NSNotification