gpt4 book ai didi

ios - 从 NSURLConnection 迁移到 NSURLSession

转载 作者:行者123 更新时间:2023-11-28 22:14:11 26 4
gpt4 key购买 nike

我正在尝试迁移到 NSURLSession,这样我就可以将多个图像发送到我的服务器并在收到所需响应时停止。但是我的完成 block 永远不会被调用。如果您能告诉我我是否正确地进行了迁移,我们将不胜感激。

这是我的旧代码,运行良好-

-(void) sendImgWithText:(UIImage*)img
{
NSURL *requestURL = [NSURL URLWithString:@"Some URL"];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"*****";
NSString *lineEnd = @"\r\n";
NSString *twoHyphens = @"--";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
// UIImage *imgColor = [UIImage imageNamed:@"9.jpg"];

UIImage * imageToPost = [[UIImage alloc] init];
UIImageWriteToSavedPhotosAlbum(imageToPost, nil, nil, nil);
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);

if (imageData) {
[body appendData:[[NSString stringWithFormat:@"%@%@%@", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"%@%@%@%@", twoHyphens,boundary, twoHyphens,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

NSLog(@"%@",requestURL);
NSLog(@"%f,%f",imageToPost.size.height,imageToPost.size.height);

// set URL
[request setURL:requestURL];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

这是版本(我从其他堆栈溢出文章中得到大部分)

- (void) serverRequestWithImage:(UIImage *)img completion:(void (^)(id responseObject, NSError *error))completion
{
NSURL *requestURL = [NSURL URLWithString:@"Some URL"];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"*****";
NSString *lineEnd = @"\r\n";
NSString *twoHyphens = @"--";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

UIImage * imageToPost = [[UIImage alloc] init];
imageToPost = img;

NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:@"%@%@%@", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"%@",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"%@%@%@%@", twoHyphens,boundary, twoHyphens,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

NSLog(@"%@",requestURL);
NSLog(@"%f,%f",imageToPost.size.height,imageToPost.size.height);

// set URL
[request setURL:requestURL];

NSURLSessionTask *task =
[session
dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
// report any network-related errors
NSLog(@"Got Response 1");

if (!data) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, error);
});
}
return;
}

// report any errors parsing the JSON
NSError *parseError = nil;
_responseData = [NSMutableData dataWithData:data];

if (_responseData) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, parseError);
});
}
return;
}

// if everything is ok, then just return the JSON object
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(_returnedData, nil);
});
}
}];

[task resume];
}

这是我在其他类(class)的调用方法

- (IBAction)GetData:(id)sender
{
[_imageView setImage:[UIImage imageNamed:@"9.jpg"]];

msg = [[Message alloc] init];
[msg initData];
msg.delegate=self;
[msg serverRequestWithImage:_imageView.image completion:^(id responseObject, NSError *error)
{
if (responseObject) {
// do what you want with the response object here
NSLog(@"Got Data");
} else {
NSLog(@"%s: serverRequest error: %@", __FUNCTION__, error);
}
}];

}

最佳答案

项目:

  • 我没有看到 NSURLSession 的初始化。这是你应该在你的问题中展示的东西。您还可以检查 session 是否为非零的“发送图像”方法。

  • 看起来您是从一个文件 (@"9.jpg") 开始的。如果是这样,-[NSURLSession uploadTaskWithRequest:fromFile:completionHandler:] 可能会为您省去很多麻烦。

未经请求的建议,包含所有内容::)

  • 在我看来,-serverRequestWithImage:completion: 是该方法的糟糕名称。它暗示它返回一个请求对象,并没有告诉你它实际上发送了请求。一些活跃的东西,比如 -uploadImage:completionHandler: 可能会更好。

  • 按照惯例,所有方法名称都应以小写字母开头,即 -getData:

关于ios - 从 NSURLConnection 迁移到 NSURLSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22148209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com