2015-11-19 133 views
0

我想知道爲什麼我的委託方法-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location沒有調用。這裏是我的代碼:NSURLSession委託不叫

- (void)viewDidLoad { 
    [self createSessionWithDelegate]; 
    [super viewDidLoad]; 
} 

- (void)createSessionWithDelegate { 
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; 
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://example.com/my-expected-image.jpg"]]; 
    [task resume]; 
} 

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { 
    UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]]; 
    if (downloadedImage){ 
     NSLog(@"Got image!"); 
    } 

    // Perform UI changes in main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     self.myImageView.image = downloadedImage; 
    }); 
} 

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { 
    NSLog(@"%f/%f", (double)totalBytesWritten, (double)totalBytesExpectedToWrite);  
} 

另外我想補充,我的方法:-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite工作正常(它顯示輸出I多少字節了)。

+0

您是否在類中聲明瞭委託,例如'UIViewController '? – wigging

+0

@GavinWiggins聲明是:interface ViewController:UIViewController

回答

2

你嘗試實施

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

,看看如果返回某些錯誤?

+0

Im sorry。問題是在不好的鏈接(事實上,鏈接工作幾分鐘前,我試圖實現委託調用後停止工作:) –

+2

僅供參考,如果您使用**完成處理程序**創建會話,委託方法將不會被調用。 –