2016-10-26 14 views
1

SwiftとiOS 10で連携するプッシュ通知を取得するのには苦労しています。登録は正常に完了しているようですが、notificaitonを作成すると何も起こりません。私は何が欠けているすべてのアイデア?Swift iOS 10のプッシュ通知

import Foundation 
import UIKit 
import UserNotifications 
class SPKPushNotifications 
{ 
    class func register(application:UIApplication){ 
     if #available(iOS 10.0, *) { 
      let center = UNUserNotificationCenter.current() 
      center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in 
       // Enable or disable features based on authorization. 
       application.registerForRemoteNotifications() 
      } 
     } else { 
      let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound] 
      let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil) 
      application.registerUserNotificationSettings(pushNotificationSettings) 
      application.registerForRemoteNotifications() 
     } 
    } 
    class func unregister(application:UIApplication){ 
     application.unregisterForRemoteNotifications() 
    } 
    class func create(title:String, body:String, delay:Double, repeats:Bool){ 
     if #available(iOS 10.0, *) { 
      let content = UNMutableNotificationContent() 
      content.title = title 
      content.body = body 
      content.sound = UNNotificationSound.default() //idk if we're gonna want something else 
      content.badge = NSNumber(value:UIApplication.shared.applicationIconBadgeNumber+1) 
      let trigger = UNTimeIntervalNotificationTrigger(timeInterval:delay, repeats:repeats) 
      let request = UNNotificationRequest(identifier:title, content:content, trigger:trigger) 
      let center = UNUserNotificationCenter.current() 
      center.add(request){ (error) in 
       print(error) 
      } 

     } else { 
      // Fallback on earlier versions 
     } 
    } 
    class func delete(){ 
     if #available(iOS 10.0, *) { 
      let center = UNUserNotificationCenter.current() 
      center.removeAllDeliveredNotifications() 
     } else { 
      // Fallback on earlier versions 
     } 
    } 
} 

答えて

0

アプリケーションがフォアグラウンドにある場合、通知は表示されません。アプリケーションがバックグラウンドにあるときに通知センターにリクエストを追加してみてください。

数秒間のスリープを追加してアプリケーションをバックグラウンドに移動することで(このテストのみ)行うことができます。または、アプリケーションがフォアグラウンドで実行されていないときに通知をスケジュールする。

+0

10秒間遅延させると機能しません。コードを使ってアプリをバックグラウンドに移動する方法はありますか? – Dominic

+0

私は 'UIApplication.shared.perform(#selector(URLSessionTask.suspend))'でアプリをバックグラウンドに移動でき、通知が表示されます。しかし、私はバックグラウンドにアプリを移動したくない。私は通知が追加されている間、それを開いたままにしておきたい。 – Dominic

+0

ホームボタンをクリックすることで、アプリケーションをバックグラウンドに移動できます。シミュレータでは、ハードウェア - >ホームを使用できます。 通知は、アプリケーションがフォアグラウンドにない場合にユーザーに表示されるようになっています。アプリケーションがフォアグラウンドにある場合、なぜ通知する必要があるのですか?アプリケーションでUIを使用できます。おそらく、あなたのユースケースについて詳しく説明することができます。しかし、あなたのプッシュ通知が現在機能しているので、それはもう一つの疑問であるようです。 – little

関連する問題