我是iOS新手。我已经搜索了很多关于这个问题,尝试了很多方法,最后,我在这里。
在我的应用程序中,当在API响应中找到新记录时,我必须在后台发送通知。根据Apple文档,我已实现performFetchWithCompletionHandler
,如下所示:
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//User Login status from NSUserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL Is_User_Logged_in = [defaults boolForKey:IS_USER_LOGGED_IN];
if(Is_User_Logged_in){
NSLog(@"background fetch started");
//fetchDataFromAPIs method calls 3 API's here
// and if a new record found, inserts into the local sqlitedb
if([self fetchDataFromAPIs])
{
//getUpdatedInfo method checks the new record in the local sqlitedb
// and fires a notification
if([self getUpdatedInfo])
{
NSLog(@"Content Uploaded and pushed notification");
completionHandler(UIBackgroundFetchResultNewData);
[[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_HOME object:self];
NSLog(@"Time: %@", [Constants getCurrentTimeStamp]);
}
else{
completionHandler(UIBackgroundFetchResultNoData);
NSLog(@"Time: %@", [Constants getCurrentTimeStamp]);
}
}
}
}
当应用程序在后台时,上述方法会触发通知,但是当应用程序终止时,不会发生任何事情。获取时间间隔是不可预测的。
我已在应用程序委托方法中设置了执行后台提取的最小时间间隔,如下所示:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
[self registerForRemoteNotifications];
return YES;
}
如何使performFetchWithCompletionHandler
在后台运行一定时间间隔而不失败?
如果用户终止应用程序,如何运行performFetchWithCompletionHandler
?
另外,我在应用程序的前台运行NSTimer并定期显示时间间隔,以便将更新显示为徽章编号和通知,如下所示:
self.timer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(UpdatePages) userInfo:nil repeats:YES];
由于我已在应用程序委托中实现了performFetchWithCompletionHandler
,我是否应该在前台跳过此NSTimer
?
请帮助排序。非常感谢提前。