ios - NSURLSession 和后台流上传

标签 ios background alassetslibrary uploading nsurlsession

我在使用 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/

相关文章:

css - 多个 CSS 3 背景图像 - 为顶部图像添加不透明度

android - 在 android 中,线性布局的背景颜色不起作用

iphone - NSBlockOperation 或带有 ALAsset Block 的 NSOperation 使用 ALAsset URL 显示照片库图像

ios - ALAssetsLibrary 图像扭曲

ios - 在 Storyboard 中调整弹出窗口 Controller 的大小

ios - 如何实现一个单选按钮在选择时处于事件状态?

iphone - 将 post 变量发送到 iOS 表单

android - 应用程序支持后台播放视频、cordova 问题、google play 拒绝应用程序

ios - 处理 DPad 和 Shooting Swift 的多次触摸