NSURLSession和后台上传流

使用NSURLSession将照片从资源库上传到服务器时遇到一些问题。

起初NSURLSession不支持流式上传。 我试图使用它时遇到exception:

 @property (nonatomic, strong) NSURLSession *uploadSession; ... _uploadSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration backgroundSessionConfiguration:kUploadBackgroundURLSessionIdentifier] delegate:self delegateQueue:nil]; ... NSURLSessionUploadTask *task = [self.uploadSession uploadTaskWithStreamedRequest:URLRequest]; 

这是一个例外:

 Terminating app due to uncaught exception 'NSGenericException', reason: 'Upload tasks in background sessions must be from a file' 

这真的很奇怪,因为Apple的手册不包含任何有关仅使用uploadTaskWithRequest:fromFile:用于后台会话。 如果我想从资源库上传真正庞大的video文件怎么办? 我应该先将它保存到我的tmp目录吗?

看起来唯一的原因是使用uploadTaskWithRequest:fromFile:无论如何,对吧? 但是我有一个问题,如果上传过程中断并开始在后台上传下一部分,服务器如何知道该文件的哪一部分正在上传?

我应该为此管理一些事情吗? 以前我在URL请求中使用Content-Range,如果我想继续上传之前启动的文件的一部分。 现在我不能这样做 – 我必须在创建上传任务之前创建一个URL请求,看起来像NSURLSession必须自动为我做这样的事情?

有没有人做过这样的事情? 谢谢

转换为NSData并在app文件夹中进行复制和写入

 ALAsset *asset = [cameraRollUploadImages objectAtIndex:startCount]; ALAssetRepresentation *representation = [asset defaultRepresentation]; // create a buffer to hold the data for the asset's image uint8_t *buffer = (Byte *)malloc(representation.size);// copy the data from the asset into the buffer NSUInteger length = [representation getBytes:buffer fromOffset:0 length:representation.size error:nil]; // convert the buffer into a NSData object, free the buffer after NSData *image = [[NSData alloc] initWithBytesNoCopy:buffer length:representation.size freeWhenDone:YES]; 

现在,除了将图片保存到本地文件系统或临时目录之外别无他法。

以下代码确保您的数据不会丢失exif标记。 (ALAsset => NSData)

 ALAssetRepresentation *assetRepresentation = [(ALAsset *)assetBeingUploaded defaultRepresentation]; uint8_t *buffer = (uint8_t *)malloc(sizeof(uint8_t)*[assetRepresentation size]); NSUInteger buffered = 0; if (buffer != NULL) buffered = [assetRepresentation getBytes:buffer fromOffset:0.0 length:assetRepresentation.size error:nil]; self.imageBeingUploaded = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES]; 

后台会话中的上载任务不支持完成处理程序。 我们应该去。,

 - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL; 

我怀疑如果我们使用后台会话和uploadtask与请求使用文件,我们如何得到响应标题或正文?

一个干净的解决方法是创建一个NSOperation,它将使用NSStream将文件从资产库复制到临时文件夹,这样你就不会在有大文件的情况下崩溃,当操作完成时你会安排上传临时文件,上传完成后删除它。

在我的情况下,我需要以多部分格式发送文件,因此创建临时文件是必要的,但我在上传大文件时遇到问题,超过2 Gb,示例电影超过20分钟。

您无法在后台上传NSData,您需要上传文件格式。 您可以按目录路径创建它