如何在后台会话(iOS)中上传图像文件



我无法在后台会话中从设备的照片上传图像。当我调用[session uploadTaskWithRequest:req-fromFile:nsurl]时,系统立即通过发送进行投诉

Failed to issue sandbox extension for file file:///var/mobile/Media/DCIM/103APPLE/IMG_3984.JPG, errno = 1

到控制台。(此处存在类似的堆栈溢出问题)

然而,如果我使用[NSRLSessionConfiguration defaultSessionConfiguration](而不是我需要的[NSRLSsessionConfiguration backgroundSessionConfigurationWithIdentifier:id])创建我的NSURLSessionConfiguration如果我从NSURL构造了一个NSData对象并上传它,而不是直接从文件上传(这是后台会话所需的),那么上传成功。顺便说一句,我正在将文件上传到我们的Rackspace Cloud帐户中,并且能够通过一个简单的Postman PUT成功地做到这一点。

问题出现在我的uploadObject方法中,它看起来像:

-(void) uploadObject:(NSURL*)urlToBeUploadedIn
{
NSDictionary *headers = @{ @"x-auth-token": state.tokenID,
@"content-type": @"image/jpeg",
@"cache-control": @"no-cache" };
// create destination url for Rackspace cloud upload
NSString *sURL = [NSString stringWithFormat:@"%@/testing_folder/%@.jpg", state.publicURL, [state generateImageName]]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"PUT"];
[request setAllHTTPHeaderFields:headers];
self.sessionIdentifier = [NSString stringWithFormat:@"my-background-session"];    
//    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];  // when I use this instead of the line below the sandbox error goes away
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:self.sessionIdentifier];
self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:urlToBeUploadedIn];
[uploadTask resume];
}

我调用uploadObject:的调用看起来像:

PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:state.arrImagesToBeUploaded options:nil];
PHAsset *phAsset = [fetchResult objectAtIndex:0]; // yes the 0th item in array is guaranteed to exist, above.
[phAsset requestContentEditingInputWithOptions:nil
completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSURL *imageURL = contentEditingInput.fullSizeImageURL;                           
[self uploadObject:imageURL]; 
}];

顺便说一句,我首先通过调用fileExistsAtPath:来验证我发送到uploadObject:的NSURL,这样我就知道我对该文件的引用是好的。最后,我的代表打电话给

(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)dataIn
(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error does get invoked, although the data

确实被服务器调用了(尽管响应不会解析),所以,我从服务器那里得到了一些东西,但它从未正确接收到图像。

解决方案是首先将要上传的图像复制到应用程序的沙盒中。我用过:

NSError *err;
BOOL bVal = [myNSDataOb writeToURL:myDestinationURL options:0 error:&err];

并复制到我的应用程序的"文档"目录中,但也可以使用:

NSError *err;
BOOL bVal = [[NSFileManager defaultManager] copyItemAtURL:myImageURL toURL:myDestinationURL error:&err];

相关内容

  • 没有找到相关文章

最新更新