gpt4 book ai didi

ios - 使用 NSURLSession 的异步上传将不起作用,但同步 NSURLConnection 可以

转载 作者:可可西里 更新时间:2023-11-01 03:24:13 31 4
gpt4 key购买 nike

编辑:我需要将文件从 iPhone 异步上传到 Python 服务器端进程。我想异步执行请求,以便在它工作时显示忙碌的动画。

请求需要包含用户名、密码和文件作为“multipart/form-data”。

我可以使用 NSURLConnection 让它同步工作,代码如下所示::

-(void) uploadDatabase{

Database *databasePath = [[Database alloc] init];
NSString *targetPath = [databasePath getPathToDatabaseInDirectory];

NSData *dbData = [NSData dataWithContentsOfFile:targetPath];
NSString *url = @"http://mydomain.com/api/upload/";
//NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
NSString *username = @"user";
NSString *password = @"pass";
NSMutableURLRequest *request = [self createRequestForUrl:url withUsername:username andPassword:password andData:dbData];

NSURLResponse *response;
NSError *error;

NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *stringResult = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];

NSLog(@"**server info %@", stringResult);}

//请求构造

    -(NSMutableURLRequest*) createRequestForUrl: (NSString*)urlString withUsername:(NSString*)username andPassword:(NSString*)password andData:(NSData*)dbData
{NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"BOUNDARY_STRING";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

NSMutableData *body = [NSMutableData data];

if(dbData != NULL)
{
//only send these methods when transferring data as well as username and password
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"dbfile\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:dbData]];
}

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\"\r\n\r\n%@", username] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"password\"\r\n\r\n%@", password] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

return request;}

但是,当我尝试使用 NSURLSession 异步执行此操作时,它似乎无法正常工作。带有 NSURLSession 的代码如下所示:

    -(void)uploadDatabase{
Database *databasePath = [[Database alloc] init];
NSString *targetPath = [databasePath getPathToDatabaseInDirectory];
NSURL *phonedbURL = [NSURL URLWithString:targetPath];

NSString *url = @"http://mydomain.com/api/upload/";
NSString *username = @"user";
NSString *password = @"pass";
NSMutableURLRequest *request = [self createRequestForUrl:url withUsername:username andPassword:password andData:NULL];

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

self.uploadSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:Nil];
NSLog(@"the url = %@",url);
NSURLSessionUploadTask *uploadTask = [self.uploadSession uploadTaskWithRequest:request fromFile:phonedbURL];

[uploadTask resume];}

我正在努力了解我所做的不同之处,尽管这似乎应该可行。

使用 NSURLSession 是进行异步请求的正确方法吗?我是 NSURLSession 的新手,所以我是否必须为 NSURLSession 请求而不是 NSURLConnection 更改我的 NSURLMutableRequest?

在此先感谢您的帮助!

最佳答案

你是对的,如果你只是想让你的请求异步,你应该退出 sendSynchronousRequest。虽然我们曾经会推荐 sendAsynchronousRequest,但在 iOS 9 中有效,NSURLConnection 已正式弃用,人们应该更喜欢 NSURLSession

一旦开始使用 NSURLSession,您可能会发现自己被它吸引了。例如,可以使用 [NSURLSessionConfiguration backgroundSessionConfiguration:],然后即使在应用程序进入后台后也有上传进度。 (您必须编写一些委托(delegate)方法,因此为了简单起见,我在下面保留了一个简单的前台上传。)这只是您的业务需求的问题,抵消了新的 NSURLSession 功能与它带来的 iOS 7+ 限制。

顺便说一句,如果不引用 AFNetworking,任何有关 iOS/MacOS 网络请求的讨论都可能是不完整的.它极大地简化了这些多部分请求的创建,绝对值得研究。他们也有 NSURLSession 支持(但我没有使用他们的 session 包装器,所以不能说)。但是AFNetworking无疑是值得你考虑的。您可以享受基于委托(delegate)的 API 的一些丰富功能(例如进度更新、可取消请求、操作之间的依赖关系等),提供比便捷方法(如 sendSynchronousRequest)可用的更大的控制,但不会拖着你穿过委托(delegate)方法本身的杂草。

无论如何,如果您真的对如何使用 NSURLSession 进行上传感兴趣,请参阅下文。


如果想通过NSURLSession上传,就是稍微转变一下思路,即将NSMutableURLRequest中请求(及其headers)的配置从创建请求的主体(您现在在 NSURLSessionUploadTask 的实例化期间指定)。您现在指定为上传任务一部分的请求正文可以是 NSData、文件或流(我在下面使用 NSData,因为我们'正在构建一个多部分请求):

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *boundary = [self boundaryString];
[request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

NSData *fileData = [NSData dataWithContentsOfFile:path];
NSData *data = [self createBodyWithBoundary:boundary username:@"rob" password:@"password" data:fileData filename:[path lastPathComponent]];

NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSAssert(!error, @"%s: uploadTaskWithRequest error: %@", __FUNCTION__, error);

// parse and interpret the response `NSData` however is appropriate for your app
}];
[task resume];

创建正在发送的 NSData 与您现有的代码非常相似:

- (NSData *) createBodyWithBoundary:(NSString *)boundary username:(NSString*)username password:(NSString*)password data:(NSData*)data filename:(NSString *)filename
{
NSMutableData *body = [NSMutableData data];

if (data) {
//only send these methods when transferring data as well as username and password
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", [self mimeTypeForPath:filename]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\"\r\n\r\n%@\r\n", username] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"password\"\r\n\r\n%@\r\n", password] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

return body;
}

您硬编码了边界和 mime 类型,这很好,但上面恰好使用了以下方法:

- (NSString *)boundaryString
{
NSString *uuidStr = [[NSUUID UUID] UUIDString];

// If you need to support iOS versions prior to 6, you can use
// Core Foundation UUID functions to generate boundary string
//
// adapted from http://developer.apple.com/library/ios/#samplecode/SimpleURLConnections
//
// NSString *uuidStr;
//
// CFUUIDRef uuid = CFUUIDCreate(NULL);
// assert(uuid != NULL);
//
// NSString *uuidStr = CFBridgingRelease(CFUUIDCreateString(NULL, uuid));
// assert(uuidStr != NULL);
//
// CFRelease(uuid);

return [NSString stringWithFormat:@"Boundary-%@", uuidStr];
}

- (NSString *)mimeTypeForPath:(NSString *)path
{
// get a mime type for an extension using MobileCoreServices.framework

CFStringRef extension = (__bridge CFStringRef)[path pathExtension];
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
assert(UTI != NULL);

NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType));
assert(mimetype != NULL);

CFRelease(UTI);

return mimetype;
}

关于ios - 使用 NSURLSession 的异步上传将不起作用,但同步 NSURLConnection 可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20893171/

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