即使应用程序处于挂起状态,如何在ios中运行后台服务

时间:2014-03-26 07:04:41

标签: ios iphone ios7 cocos2d-iphone

我不知道如何实施后台服务。但在搜索互联网 时,我看到了一些关于ios 7中引入的背景提取Api的教程。我无法理解实施的过程.Plesae提供一些帮助。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.


    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];





    return YES;
}
- (void)                application:(UIApplication *)application
  performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{

    NSLog(@"hai");



    [NSTimer scheduledTimerWithTimeInterval:0.30
                                     target:self
                                   selector:@selector(sampleTest)
                                   userInfo:nil
                                    repeats:NO];
     completionHandler(UIBackgroundFetchResultNewData);
}

    -(void)sampleTest
{

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"hai" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alertView show];


}

仅在应用程序启动时调用,但在此之后30秒后我看不到任何警报

1 个答案:

答案 0 :(得分:0)

只需使用以下代码: -

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication  *app = [UIApplication sharedApplication];
    UIBackgroundTaskIdentifier bgTask = 0;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
    }];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
}