2015-11-26 51 views
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值(我使用單),它會返回任務完成後的值(無論是否有錯誤),而不是第一個毫秒的值。感謝任何幫助!

+1

也許使用[代表](HTTPS ://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html)? – Vin

+0

謝謝,它的工作 – PotatoMeme

回答

0

您可以使用

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

NSURLSession方法,當任務完成後它會被稱爲在錯誤的情況下,並傳遞值使用Delegates

+0

非常感謝,我得到它的工作,並學習如何基於你們的建議與自定義代表和NSNotification工作。 – PotatoMeme