Ios background update and download, ios background update download
Ios background update and download by Wu xueying
-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {
[Application setMinimumBackgroundFetchInterval: UIApplicationBackgroundFetchIntervalMinimum];
NSLog (@ "Launched in background % d", UIApplicationStateBackground = application. applicationState );
ReturnYES;
}
// 1. Use Background Fetch
-(Void) application :( UIApplication *) application performFetchWithCompletionHandler :( void (^) (UIBackgroundFetchResult) completionHandler {
NSURLSessionConfiguration * sessionConfiguration = [nsurlsessionconfigurationdefasessessionconfiguration];
NSURLSession * session = [NSURLSessionsessionWithConfiguration: sessionConfiguration];
NSURL * url = [[NSURLalloc] initWithString: @ "http: // 127.0.0.1/data. json"];
NSURLSessionDataTask * task = [session dataTaskWithURL: url
CompletionHandler: ^ (NSData * data, NSURLResponse * response, NSError * error ){
If (error ){
CompletionHandler (UIBackgroundFetchResultFailed );
Return;
}
CompletionHandler (UIBackgroundFetchResultNewData );
}];
[Task resume];
}
// 2. Use Remote Notification
/*
Pushed content
{
"Aps ":{
"Content-available": 1
},
"Content-id": 42
}
*/
-(Void) application :( UIApplication *) application
DidReceiveRemoteNotification :( NSDictionary *) userInfo
FetchCompletionHandler :( void (^) (UIBackgroundFetchResult) completionHandler
{
NSLog (@ "Received remote notification with userInfo % @", userInfo );
NSNumber * contentID = userInfo [@ "content-id"];
NSString * downloadURLString = [NSStringstringWithFormat: @ "http://yourserver.com/downloads/%d.mp3", [contentID intValue];
NSURL * downloadURL = [NSURLURLWithString: downloadURLString];
NSURLRequest * request = [NSURLRequestrequestWithURL: downloadURL];
NSURLSessionDownloadTask * task = [[selfbackgroundURLSession] downloadTaskWithRequest: request];
Task. taskDescription = [NSStringstringWithFormat: @ "Podcast Episode % d", [contentID intValue];
[Task resume];
CompletionHandler (UIBackgroundFetchResultNewData );
}
-(NSURLSession *) backgroundURLSession
{
StaticNSURLSession * session = nil;
Staticdispatch_once_t onceToken;
Dispatch_once (& onceToken, ^ {
NSString * identifier = @ "io. objc. backgroundTransferExample ";
NSURLSessionConfiguration * sessionConfig = [NSURLSessionConfigurationbackgroundSessionConfiguration: identifier];
Session = [NSURLSessionsessionWithConfiguration: sessionConfig
Delegate: self
DelegateQueue: [NSOperationQueuemainQueue];
});
Return session ;}