将 NSURLConnection 转换为 NSURLSessionUploadTask 示例
Convert NSURLConnection to NSURLSessionUploadTask example
大家好,在此先感谢您在理解如何将一些 NSURLConnection 代码转换为更新的 NSURLSession 方面提供的帮助。
我想要做的是向服务器发出 POST 请求,并发送为密钥 "photo".
编码的照片 base 64
下面我有一个用 NSURLConnection 编写的工作示例,我想将它转换成 NSURLSession。
正如我在苹果文档中所读到的那样,我应该使用数据任务,因为在我的情况下它是一个图像,如果它是像视频这样的更大的传输,我应该使用上传任务。
关于上传任务,我找到了下一个 tutorial,但问题是,在我的情况下,我还设置了 headers,而且我的内容类型应该是 multipart/form-data。
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 教程构建一个工作示例,但我在设置 headers
的方式方面遇到了错误
提前感谢您提供的帮助!
我用的是我写的一个简单的HTTPClient class,可惜目前不支持上传任务。但下面我提出了一种创建此类上传任务的方法。我的客户端维护对 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);
}
大家好,在此先感谢您在理解如何将一些 NSURLConnection 代码转换为更新的 NSURLSession 方面提供的帮助。 我想要做的是向服务器发出 POST 请求,并发送为密钥 "photo".
编码的照片 base 64下面我有一个用 NSURLConnection 编写的工作示例,我想将它转换成 NSURLSession。
正如我在苹果文档中所读到的那样,我应该使用数据任务,因为在我的情况下它是一个图像,如果它是像视频这样的更大的传输,我应该使用上传任务。
关于上传任务,我找到了下一个 tutorial,但问题是,在我的情况下,我还设置了 headers,而且我的内容类型应该是 multipart/form-data。
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 教程构建一个工作示例,但我在设置 headers
的方式方面遇到了错误提前感谢您提供的帮助!
我用的是我写的一个简单的HTTPClient class,可惜目前不支持上传任务。但下面我提出了一种创建此类上传任务的方法。我的客户端维护对 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);
}