ios后台运行程序

来源:互联网 发布:桌面工作计划软件 编辑:程序博客网 时间:2024/05/16 07:24

http://blog.csdn.net/csharpjasp/article/details/6833343

1.运行逻辑代码:

-(void)execBackrgoundMethod

{
    /*
     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.
     */
 UIApplication* app = [UIApplication sharedApplication];  
 bgTask = [app beginBackgroundTaskWithExpirationHandler:^{  
     [app endBackgroundTask:bgTask];  
     bgTask = UIBackgroundTaskInvalid;  
     }];  
 // Start the long-running task and return immediately.  
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,  
     0), ^{  
//在这里写你要在后运行行的代码
         
     [app endBackgroundTask:bgTask];  
     bgTask = UIBackgroundTaskInvalid;  
     }); 
}

2.后台弹出UILocalNotification:

 - (void)scheduleAlarmForDate:(NSDate*)theDate  
 {  
//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] autorelease];  
     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];  
     }  
 } 


原创粉丝点击