Corrupted image when uploading in background

2019-08-27 03:56发布

问题:

I'm developping a little image sharing app for my company. Everything works pretty fine except for one thing : when I upload an image to the server, and switch the app to background, a part of the image is corrupted (all gray).

It seems that the image data is sent correctly as long as the app is live. As soon as I switch to background, it sends nothing as it seems.

For the record, I use ASIHttpRequest, the shouldContinueWhenAppEntersBackground is set to YES and I'm running the app from iOS 4.3 to iOS 6.0. I'm using ARC.

I tried to "retain" (through a strong reference) both the image and the data, nothing there too.

Here are parts of the code :

The Webservice that sends the image

- (void)sendImage:(UIImage*)image forEmail:(NSString*)email
{
     NSString* uploadImage = [NSString stringWithFormat:[self completeUrlForService:SEND_PHOTO], email];
     NSURL* url = [NSURL URLWithString:[uploadImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
     NSLog(@"uploadImage %@", uploadImage);
     // setting that we will send a JSON object
     [self setRequestType:WebServiceWrapperTypePOSTRequest];
    // when posting a picture, it could take more time...
    self.request.timeOutSeconds = 4*60;
    [self.request setShouldContinueWhenAppEntersBackground:YES];
     // setting up the POST data
     [self addPostData:image forKey:@"fileContents"];
     // start the request
     [self startRequestForUrl:url userInfo:[NSDictionary dictionaryWithObject:SEND_PHOTO forKey:URL_KEY]];
}

the actual part of ASIHttpRequest class

self.request = [ASIHTTPRequest requestWithURL:url];
[self.request setShouldContinueWhenAppEntersBackground:YES];
NSString* key = [[self.postDictionnary allKeys] objectAtIndex:0];
UIImage* value = [self.postDictionnary valueForKey:key];
__strong NSData* data = UIImageJPEGRepresentation(value, 1.0);
if (!data) data = UIImagePNGRepresentation(value);
[self.request appendPostData:data];
[self.request setPostLength:data.length];    
[self.request setUserInfo:userInfo];
[self.request setDelegate:self];
[self.request startAsynchronous];

If any of you guys has the tinyest idea, I'll take it! Thanks.

回答1:

Finally I decided to use a different library (MKNetworkKit) and instead of sending an UIImage, I save the image on disk to the tmp folder and send the file instead. When the download is complete, I just delete the image on disk. It worked liked a charm :)