Reputation: 21
I have iOS app that is main functionality is to upload images. My question is there any case that app can continue uploading images and communicate with server when app is dismissed?
Thanks
Upvotes: 1
Views: 998
Reputation: 7410
If you use NSURLConnection
, you can use a UIBackgroundTaskIdentifier
to keep your connection alive even when the app is sent to background :
Declare your background task identifier so you can access it anywhere within your class implementation, for example at the top of your .m file :
@implementation MyClass {
UIBackgroundTaskIdentifier backgroundTaskID;
}
Create your connection :
NSURLRequest *request = [NSURLRequest requestWithURL: aURL];
NSURLConnection *uploadConnection = [NSURLConnection connectionWithRequest:request delegate:self];
backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// Cancel the connection in case of expiration
[uploadConnection cancel];
}];
End your background task in both of these NSURLConnectionDelegate
methods after the connection completed / failed :
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Handle a fail
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Handle a success
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
}
Upvotes: 2