2016-10-06 3 views
0

私のiOSアプリに問題があります。 自分のアプリケーションが自分のIPhone上でフォアグラウンドにない場合でも、毎日機能を実行したいと思います。 NSTimerオブジェクトを使用しようとしましたが、アプリがバックグラウンドの場合は機能しません。Swift 3 - アプリがバックグラウンドであっても機能を実行する

どうすればこの問題を解決できますか?

注:私の機能は、現在の日付に基づいて異なる通知をトリガーします。

+0

バックグラウンドリフレッシュを使用できますが、実行時間を設定することはできません。必要な時間のローカル通知をスケジュールするロジックと組み合わせることができます。それ以外の場合は、プッシュ通知を使用することができます – Paulw11

+2

なぜアプリケーションが実行されていない場合でも、1日に1回何かを実行する必要がありますか? *本当にその必要性は非常にまれです。 – rmaddy

答えて

0

バックグラウンドでは実行できないため、実際にはアプリが実行されていない可能性があるため、実行できません。だからあなたのアーキテクチャを再考してください。たとえば、その期間中にアプリが実行されない場合は、30日間の通知を30回設定します。それは通知です。システムによってあなたの代わりに配信されるメッセージで、は常にです。

4

Paulw11が正しい。バックグラウンド更新とローカル通知を使用できます。バックグラウンドフェッチはランダムに呼び出されます。呼び出されるたびにローカル通知がリセットされます。このコードはObj Cですが、少し古いですが、コンセプトは同じです。

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

@ThBM:StackOverflowへようこそ。これは正しい答えのように見えます。それがあなたの問題を解決するなら、それを受け入れられた答えとしてマークしてください。 – mttdbrd

関連する問題