0
我是Objective-c中的新成員,我一直在爲此付出努力。我有一類從服務器下載文件:在URLSession中完成任務後的返回值
@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
值(我使用單),它會返回任務完成後的值(無論是否有錯誤),而不是第一個毫秒的值。感謝任何幫助!
也許使用[代表](HTTPS ://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html)? – Vin
謝謝,它的工作 – PotatoMeme