我想知道爲什麼我的委託方法-(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多少字節了)。
您是否在類中聲明瞭委託,例如'UIViewController'? –
wigging
@GavinWiggins聲明是:interface ViewController:UIViewController –