我在使用 NSURLSession
将照片从 Asset Library 上传到服务器时遇到了一些问题。
起初NSURLSession
不支持流式上传。我在尝试使用它时遇到异常:
@property (nonatomic, strong) NSURLSession *uploadSession;
...
_uploadSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration
backgroundSessionConfiguration:kUploadBackgroundURLSessionIdentifier] delegate:self delegateQueue:nil];
...
NSURLSessionUploadTask *task = [self.uploadSession uploadTaskWithStreamedRequest:URLRequest];
这是一个异常(exception):
Terminating app due to uncaught exception 'NSGenericException', reason: 'Upload tasks in background sessions must be from a file'
这真的很奇怪,因为 Apple 的手册不包含任何有关仅使用 uploadTaskWithRequest:fromFile:
进行后台 session 的信息。如果我想从 Assets 库上传非常大的视频文件怎么办?我应该先将它保存到我的 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];
关于ios - NSURLSession 和后台流上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19974673/