【发布时间】:2015-07-24 18:48:38
【问题描述】:
当应用程序在后台时,我正在尝试上传超过 200 张图像(根据我的需要)。我正在使用 NSUrlSession (上传任务)。它正在上传大约。 20 张图像很容易,但在此过程之后没有响应。我正在使用单个请求(不使用数组在服务器上上传图像以满足客户端要求)。请用一些示例代码向我提出任何想法,因为我已经尝试过大约。 10-15 种不同的方法。
先谢谢了
【问题讨论】:
标签: ios objective-c swift
当应用程序在后台时,我正在尝试上传超过 200 张图像(根据我的需要)。我正在使用 NSUrlSession (上传任务)。它正在上传大约。 20 张图像很容易,但在此过程之后没有响应。我正在使用单个请求(不使用数组在服务器上上传图像以满足客户端要求)。请用一些示例代码向我提出任何想法,因为我已经尝试过大约。 10-15 种不同的方法。
先谢谢了
【问题讨论】:
标签: ios objective-c swift
应用程序在特定时间后进入挂起状态(后台)。所以所有正在进行的任务都保持暂停。
可能的方法是,应用程序可以使用beginBackgroundTaskWithExpirationHandler 请求操作系统额外的时间来完成未完成的任务。
示例代码如下:
__block UIBackgroundTaskIdentifier backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Background Time:%f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
backgroundTaskIdentifier = backgroundTaskIdentifier;
}];
注意:对于您提到的 200 张图像,应用程序处于活动状态将是一项艰巨的任务。尝试不同的方法,例如支持后台模式的应用程序。
【讨论】:
试试这个
我正在使用 AFNetworking 来执行此操作
第 1 步:创建您的请求
NSMutableURLRequest *request1 = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
URLString:[NSString stringWithFormat:@"%@%@", API_MAIN_URL, IMAGE_UPLOAD]
parameters:param constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:strImagePath]
name:@"sendimage"
fileName:[strImagePath lastPathComponent]
mimeType:@"image/png"
error:nil];
} error:nil];
第 2 步:我在给定位置创建流
[[AFHTTPRequestSerializer serializer] requestWithMultipartFormRequest:request1
writingStreamContentsToFile:[NSURL fileURLWithPath:[strImagePath stringByDeletingPathExtension]]
completionHandler:^(NSError *error){
第 3 步:这里我正在创建上传任务。
///here is file
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [self.manager uploadTaskWithRequest:request1
fromFile:[NSURL fileURLWithPath:strImagePath]
progress:&progress
completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
NSLog(@"response : %@\n\n responseObject : %@\n\n error : %@", response, responseObject, error);
}];
[uploadTask resume];
}
}];
}
使用后台任务上传此代码
【讨论】: