当前位置:主页 > IT技术分享 >

iOS后台网络任务

作者:AG88发表时间:2019-01-16

在iOS系统,App的前台运行和后台运行,行为是不同的,iOS操作系统对后台运行做了诸多限制,为了能够让系统运行更流程和更省电。

App的状态如下图:

UIDevice* device = [UIDevice currentDevice]; BOOL backgroundSupported = NO; if ([device respondsToSelector:@selector(isMultitaskingSupported)]) backgroundSupported = device.multitaskingSupported;

第一种,使用beginBackgroundTaskWithExpirationHandler:在applicationDidEnterBackground里调用

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you
        // stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    
    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        // Do the work associated with the task, preferably in chunks.
        // your code
        NSLog(@" %f",application.backgroundTimeRemaining);
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });

}
第二种,使用本地系统通知

- (void)scheduleAlarmForDate:(NSDate*)theDate
    {
        UIApplication* app = [UIApplication sharedApplication];
        NSArray*    oldNotifications = [app scheduledLocalNotifications];
        // Clear out the old notification before scheduling a new one.
        if ([oldNotifications count] > 0)
            [app cancelAllLocalNotifications];
        // Create a new notification.
        UILocalNotification* alarm = [[UILocalNotification alloc] init];
        if (alarm)
        {
            alarm.fireDate = theDate;
            alarm.timeZone = [NSTimeZone defaultTimeZone];
            alarm.repeatInterval = 0;
            alarm.soundName = @"alarmsound.caf";
            alarm.alertBody = @"Time to wake up!";
            
            [app scheduleLocalNotification:alarm];
        }
    }

第三种调用系统指定的后台运行任务,有一下这些,例如GPS 音乐等

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
    NSError *error;
    NSURLResponse *response;
    NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
可正常收到response,暂时解决了个问题。但对于有数个请求,执行效率是一个问题。

http://www.bkjia.com/Androidjc/437228.htmlwww.bkjia.comtruehttp://www.bkjia.com/Androidjc/437228.htmlTechArticle在iOS系统,App的前台运行和后台运行,行为是不同的,iOS操作系统对后台运行做了诸多限制,为了能够让系统运行更流程和更省电。 App的状...

本文源自: 环亚娱乐

下一篇:没有了 上一篇:Angular-指令,angular
IT技术分享
联系我们