我的iOS应用程序遇到了麻烦。
我想每天运行一个函数,即使我的应用程序不在我的iPhone上。我尝试使用NSTimer
对象,但如果我的应用处于后台,它就不起作用。
我怎样才能做到这一点?
注意:我的功能会触发根据当天不同的通知。
答案 0 :(得分:4)
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
BackgroundFetch * fetch = [[BackgroundFetch alloc] init];
[fetch fetchNewDataWithCompletionHandler:^(UIBackgroundFetchResult result) {
completionHandler(result);
} successDictionary:^(NSDictionary *responseDict) {
// Schedule local notification, in this case it is 9am
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *notif = [[UILocalNotification alloc] init];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
[components setDay: day];
[components setMonth: month];
[components setYear: year];
[components setHour: 9];
[components setMinute: 0];
[components setSecond: 0];
[calendar setTimeZone: [NSTimeZone systemTimeZone]];
NSDate *dateToFire = [calendar dateFromComponents:components];
notif.fireDate = dateToFire;
notif.timeZone = [NSTimeZone systemTimeZone];
notif.alertBody = [NSString stringWithFormat:@"%@: %@", responseDict[@"city"], responseDict[@"temp"]];
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
答案 1 :(得分:0)
您无法执行此操作,因为您无法在后台运行,实际上您的应用甚至可能无法运行。所以重新考虑你的架构。例如,如果您的应用在此期间从未运行,请在接下来的30天内设置30个通知。这是通知的内容:系统代表您发送的消息, 始终在运行。