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



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

- (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秒后我看不到任何警报

只需使用以下代码:-

- (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];
}

最新更新