共享扩展不上传全尺寸图像

Posted

技术标签:

【中文标题】共享扩展不上传全尺寸图像【英文标题】:Share Extension not uploading full size images 【发布时间】:2014-09-04 06:33:11 【问题描述】:

我正在为我的 ios 应用程序开发共享扩展。我真的做了所有的事情,但问题是我的代码只适用于小图像,但是当我上传从设备相机拍摄的图像时,上传失败,只有文本被上传。

- (void)performUploadWith:(NSDictionary *)parameters imageFile:(UIImage *)image

NSString *boundary = @"SportuondoFormBoundary";


//    NSURLSessionConfiguration *configuration= [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationName];

//    NSURLSession *session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
//    NSMutableURLRequest *request;//[NSURLRequest pho]

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = @
                                        @"api-key"       : @"55e76dc4bbae25b066cb",
                                        @"Accept"        : @"application/json",
                                        @"Content-Type"  : [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
                                        ;

NSURLSession *session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];


NSMutableData *body = [NSMutableData data];


for (NSString *key in parameters)

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];



NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
NSLog(@"imageDATE, %@", imageData);
if (imageData)

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"file"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];




// Data uploading task. We could use NSURLSessionUploadTask instead of NSURLSessionDataTask if we needed to support uploads in the background
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kURLBase,kURLAddPostDL]];
NSLog(@"url %@",url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10000];
request.HTTPMethod = @"POST";
request.HTTPBody = body;



NSURLSessionUploadTask *upload=[session uploadTaskWithRequest:request fromData:request.HTTPBody];
[upload resume];


我将我的代码更新为此,并在服务器上检查我的请求从未到达服务器。我正在使用此代码

        NSInteger randomNumber = arc4random() % 1000000;
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:[NSString stringWithFormat:@"testSession.foo.%d", randomNumber]];
    config.sharedContainerIdentifier=kGroupNameToShareData;
  session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
  NSURLSessionUploadTask  *uploadTask = [session uploadTaskWithRequest:request fromFile:[NSURL        URLWithString:[NSString stringWithFormat:@"file://%@", dataSrcImagePath]]];

   [uploadTask resume];

【问题讨论】:

您是否获得了解决方案,然后您在容器应用或共享扩展应用中处理会话委托? 您是如何在扩展程序中将图像数据保存到文件中的?? 【参考方案1】:

扩展程序不允许有自己的缓存磁盘空间。需要与应用分享

上传大图需要缓存磁盘空间,所以上传失败。

您需要使用以下代码创建 url 会话:

let configName = "com.shinobicontrols.ShareAlike.BackgroundSessionConfig"
let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(configName)
// Extensions aren't allowed their own cache disk space. Need to share with application
sessionConfig.sharedContainerIdentifier = "group.ShareAlike"
let session = NSURLSession(configuration: sessionConfig)

然后将应用组设置为扩展目标和包含应用。

以及更多信息,您可以参考以下链接: http://www.shinobicontrols.com/blog/posts/2014/07/21/ios8-day-by-day-day-2-sharing-extension

【讨论】:

【参考方案2】:

您应该使用后台 NSURLSession,因为您应该通过在您的 NSExtensionContext 实例上调用 completeRequestByReturningItems 来尽快关闭共享 UI。

【讨论】:

【参考方案3】:

问题是我没有使用后台会话

  NSURLSessionConfiguration *configuration= [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationName];

- (void)performUploadWith3:(NSDictionary *)parameters imageFile:(UIImage *)image

NSString *fileName = @"image.file";
NSString *boundary= @"Boundary+2EB36F87257DBBD4";

NSURL *storeURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:kGroupNameToShareData];


storeURL=[storeURL URLByAppendingPathComponent:fileName];
NSLog(@"sotre url %@",storeURL);

NSData *imageData =  UIImageJPEGRepresentation(image, 0.8);

imageData =[self appendParams:parameters andImage:image bondary:boundary];


if (!([imageData writeToFile:[storeURL path] atomically:YES]))

    NSLog(@"Failed to save file.");



NSString *string=@"URL here";


NSURL *url = [NSURL URLWithString:string];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];


NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];

for (NSString *key in parameters)

    [request setValue:[parameters objectForKey:key] forHTTPHeaderField:key];




if (session == nil)

    //If this is the first upload in this batch, set up a new session

    //Each background session needs a unique ID, so get a random number
    NSInteger randomNumber = arc4random() % 1000000;


    sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:[NSString stringWithFormat:@"and unique name"]];
    sessionConfiguration.sharedContainerIdentifier=kGroupNameToShareData;
    // config.HTTPMaximumConnectionsPerHost = 1;


    session = [NSURLSession  sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

    //Set the session ID in the sending message structure so we can retrieve it from the
    //delegate methods later
    //            [sendingMessage setValue:session.configuration.identifier forKey:@"sessionId"];
    NSLog(@"config %@",sessionConfiguration.sharedContainerIdentifier);





if([[NSFileManager defaultManager]fileExistsAtPath:[storeURL path]])


    NSURLSessionUploadTask  *uploadTask = [session uploadTaskWithRequest:request fromFile:storeURL];
    [uploadTask resume];

else
    NSLog(@"file does not exsit");

    NSLog(@"desc %@",[session sessionDescription]);



    //   NSLog(@"state %ld", [uploadTask state]);

    

【讨论】:

您好,我已经使用了这条线,但仍然有问题。你能在共享扩展类中分享你的代码吗.. 我的问题是它正在上传图片,但我以不同的格式发送它,所以我使用runscope.com 站点来查找问题 您好,您是在此方法应用程序中处理 appdelegate 中的后台会话吗? 在共享扩展中没有代理类,您是在共享扩展中导入应用代理类吗? 后台会话确实在应用程序中工作,您只需创建请求,然后 iOS 处理它,即使您的应用程序崩溃,它也会运行。我已经添加了我的代码。希望对你有帮助

以上是关于共享扩展不上传全尺寸图像的主要内容,如果未能解决你的问题,请参考以下文章

无法通过共享扩展打开/读取图像

在共享扩展中上传图片导致 NSURLErrorDomain Code=-997

Firebase 图像大小调整扩展。引用调整大小的图像

上传图片的三个版本,全尺寸、缩略图和调整大小

使用 JavaScript 在后台共享扩展上传

减小 jqDock 中的扩展图像大小