尝试使用 NSURLSession 委托方法获取数据时遇到问题。我想出了这个错误:
"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'"
我不明白的是
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
CGFloat percentDone = (double)totalBytesWritten/(double)totalBytesExpectedToWrite;
NSLog(@"Pourcentage: %f", percentDone);
}
正在返回 1.000000,并调用以下委托方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
// Parse the JSON that came in
NSLog(@"DidComplete"); --> I can see this message
if (error) {
NSLog(@"Error in finishLoading: %@", error.localizedDescription); --> but this message is not displayed. There is no error, only data returning nil resulting in a crash...
}
else {
....
}
但是没有调用以下方法
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *) response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
NSLog(@"DidReceiveResponse"); --> not displayed
completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSLog(@"DidReceiveData. Data: %@", data); --> not displayed
_downloadedData = [[NSMutableData alloc] init];
[_downloadedData appendData:data];
}
但是它应该在 didCompleteWithError 之前调用不是吗?我假设无法调用其他处理附加数据的方法,然后数据为零。
我确信我可以在服务器端获取数据,因为当我使用块方法(而不是委托方法)时,NSData 对应于我正在寻找的内容。
奇怪的是,这个错误是在我像这样更改配置会话之后出现的:
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession2 = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@"http://localhost:8888/download_list.php"];
NSURLSessionDownloadTask *dataTask = [defaultSession2 downloadTaskWithURL:url];
当它是这样的时候,我可以看到从服务器检索到的 NSData
NSURLSessionDataTask *dataTask = [defaultSession2 dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil) {
NSString * text = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text); -> text corresponds to the data I am looking for
}
}];
然而,不可能用块来调用委托。
知道“数据”是如何消失的吗?或者我应该在不使用块时更改某些内容?
感谢您的帮助!