1

AppDelegate에 내 Core Data에 가져 오기 요청을 수행하는 방법을 추가했으며 일부 경우 알림을 표시하고 있습니다 ...하지만 알 수 있습니다. 일부 사용되지 않는 메소드가 있음을 알립니다. 나는 몇 가지 변경을하려고했지만 : 내 응용 프로그램을 죽일 때 내 응용 프로그램이 포 그라운드에있는 경우배경 가져 오기 요청 및 알림이 모든 상황에서 작동하지 않습니다.

  • 는 백그라운드 모드가

  • 작동하지 않는 백그라운드 모드에서 작동하지만 통지는하지 않습니다

  • 나는 배경에서 내 응용 프로그램을 실행

    , 모든 것이 작동 표시 미세 여기

내 코드입니다 :

나는 모든 시간을 실행하려는 방법 (분당) :

func notification(){ 

    let appDel: AppDelegate = UIApplication.shared.delegate as! AppDelegate 
    let context: NSManagedObjectContext = appDel.managedObjectContext 
    var messageNotif:String? = nil 

    do { 

     let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Leads") 
     let predicate = NSPredicate(format: "statutSendLead=%@ OR statutSendSimulation=%@", "0", "0") 
     request.predicate = predicate 
     let results = try context.fetch(request) 

     if results.count > 0 { 
      if Reachability.isConnectedToNetwork() == false { 

       messageNotif = "Votre demande n'a pas été envoyée, merci de vous connecter à internet." 
      } else { 

       Reachability.checkUrl(urlString:Configuration.MyVariables.url, finished: { isSuccess in 


        if isSuccess == false { 
         messageNotif = "Notre service d'enregistrement des demandes est temporairement indisponible, un renvoi sera effectué ultérieurement." 
        } 
       }) 
      } 
      */ 


      if (messageNotif != nil) { 

       let identifier = self.stringWithUUID() 


       if #available(iOS 10.0, *) { 
        let center = UNUserNotificationCenter.current() 
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in 

         let content = UNMutableNotificationContent() 

         content.body = messageNotif! 
         content.sound = UNNotificationSound.default() 
         // Deliver the notification in five seconds. 
         let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false) 
         let request = UNNotificationRequest.init(identifier: "test", content: content, trigger: trigger) 

         // Schedule the notification. 
         let center = UNUserNotificationCenter.current() 

         UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 
         UNUserNotificationCenter.current().add(request) {(error) in 
          if let error = error { 
           print(error) 
          } 
         } 
        } 
       } else { 
        let notification = UILocalNotification() 
        notification.alertBody = messageNotif 
        notification.fireDate = NSDate() as Date 
        notification.soundName = UILocalNotificationDefaultSoundName 
        UIApplication.shared.scheduleLocalNotification(notification) 
       } 
      } 
     } 

     /* else { 
     timerNotification.invalidate() 
     } */ 

    } catch { 
     print(error) 
    } 
} 

다른 방법 :

var window: UIWindow? 
var timerUploadData:Timer! 
var timerNotification:Timer! 
var test:Timer! 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 

    UIApplication.shared.setMinimumBackgroundFetchInterval(
     UIApplicationBackgroundFetchIntervalMinimum) 

    let userDefaults = UserDefaults.standard 

    if userDefaults.object(forKey: "ApplicationUniqueIdentifier") == nil { 
     let UUID = Foundation.UUID().uuidString 
     userDefaults.set(UUID, forKey: "ApplicationUniqueIdentifier") 
     userDefaults.synchronize() 
    } 

    Thread.sleep(forTimeInterval: 3.0) 
    window = UIWindow(frame: UIScreen.main.bounds) 
    let containerViewController = ContainerViewController() 
    window!.rootViewController = containerViewController 
    window!.makeKeyAndVisible() 


    if #available(iOS 10.0, *){ 

     application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) 
     timerNotification = Timer.scheduledTimer(timeInterval: 60 * 1, target: self, selector: #selector(AppDelegate.notification), userInfo: nil, repeats: true) 

    } 
    else { //If user is not on iOS 10 use the old methods we've been using 
     let notificationSettings = UIUserNotificationSettings(
      types: [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound], categories: nil) 
     timerNotification = Timer.scheduledTimer(timeInterval: 60 * 1, target: self, selector: "notification", userInfo: nil, repeats: true) 
     application.registerUserNotificationSettings(notificationSettings) 
    } 

    registerPushNotifications() 

    return true 
} 

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { 
    notification() 
} 


func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { 
    if notificationSettings.types != UIUserNotificationType() { 
     application.registerForRemoteNotifications() 
    } 
} 

func registerPushNotifications() { 
    DispatchQueue.main.async { 
     let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil) 
     UIApplication.shared.registerUserNotificationSettings(settings) 
    } 
} 

func stringWithUUID() -> String { 
    let uuidObj = CFUUIDCreate(nil) 
    let uuidString = CFUUIDCreateString(nil, uuidObj)! 
    return uuidString as String 
} 
+0

이 https://stackoverflow.com/questions/17044373/local-notification-in-foreground에서 왜 알림이 표시되지 않는지 확인하십시오. 앱이 포 그라운드에 있습니다 (앱이 알림을 표시해야하기 때문에) –

+0

앱에 대한 모든 응답 종료 된 상황? – Ben

+0

읽어 보셨습니까? https://blog.newrelic.com/2016/01/13/ios9-background-execution/? –

답변

0

이 내가 지금 비슷한에 좋은 대답을 얻었다 오래된 질문이지만 문제가 발생했습니다. the answer from Rob

이 질문은 앱을 죽일 때 배경 모드가 작동하지 않는 이유와이를 테스트하는 방법에 대한 힌트까지 가능한 답변입니다.

다른 질문은 이미 의견에 대한 답변 : 알림 표시되지 않는 이유는 응용 프로그램이 있기 때문에 앱 (전경에있을 때

귀하의 질문이 stackoverflow.com/questions/17044373/... 참조 알림 자체를 표시) - 데이터 코스모스 1 월 13 일 10시 49 분