大家好,提前感谢在理解如何将一些NSURLConnection代码转换为更新的NSURLSession方面提供的任何帮助。我想做的是向服务器发出POST请求,并为密钥"photo"发送一张64码的照片。
下面我有一个用NSURLConnection写的工作示例,我想把它转换成NSURLSession。
根据我的理解,我应该使用数据任务,因为在我的情况下,它是一个图像,如果它是一个更大的传输,如视频,我应该使用上传任务。
关于上传任务,我已经找到了下一个教程,但问题是,在我的情况下,我也设置了一个标题,也我的内容类型应该是多部分/表单数据。
NSURL *url = [NSURL URLWithString:myLink];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:parameter1 forHTTPHeaderField:header1];
[request addValue:parameter2 forHTTPHeaderField:header2];
[request addValue:parameter3 forHTTPHeaderField:header3];
[request addValue:parameter4 forHTTPHeaderField:header4];
[request addValue:parameter5 forHTTPHeaderField:header5];
[request setHTTPBody:[UIImageJPEGRepresentation(avatarImage, 1.0) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
NSError *jsonError;
if(httpResp.statusCode == 200){
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
if (!jsonError) {
[[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"photo_url"] forKey:@"avatarLink"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else {
NSString *errorCode = [NSString stringWithFormat:@"An error has occured while uploading the avatar: %ld", (long)httpResp.statusCode];
[GeneralUse showAlertViewWithMessage:errorCode andTitle:@"Error"];
}
}];
我想提到的是,我试图使用Ray Wenderlich教程构建一个工作示例,但我得到了一个错误,关于我设置标题的方式
提前感谢您提供的任何帮助!
我正在使用我编写的一个简单的HTTPClient类,但不幸的是它目前不支持上传任务。但是下面我提出了一个创建这样一个上传任务的方法。我的客户端维护一个对NSURLSession的引用和一个运行任务的字典(键是任务本身,值是收到的NSData),作为异步处理接收响应数据(可能不止一个)会话任务的一种方式。为了工作,我的客户端实现了以下协议:我将按如下方式创建上传任务:
- (NSURLSessionTask *) startUploadTaskForURL: (NSURL *) url withData: (NSData *) data {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
NSURLSessionUploadTask uploadTask = [self.session uploadTaskWithRequest:request fromData:data];
[self scheduleTask:task];
return task;
}
- (void) scheduleTask: (NSURLSessionTask *) task {
[self.runningTasks setObject:[NSMutableData data] forKey:task];
[task resume];
}
- (NSMutableData *) dataForTask: (NSURLSessionTask *) task {
return [self.runningTasks objectForKey:task];
}
- (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTTPClient: Data task received data: %@", dataString);
NSMutableData *runningData = [self dataForTask:dataTask];
if (!runningData) {
NSLog(@"No data found for task");
}
[runningData appendData: data];
}
- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"HTTPClient: Task completed with error: %@", error);
// my client also works with a delegate, so as to make it reusable
[self.delegate sessionTask:task completedWithError:error data:[self dataForTask:task]];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
NSLog(@"HTTPClient: did send body data: %lld of %lld bytes ", totalBytesSent, totalBytesExpectedToSend);
}