コードスニペット(Push通知編 アプリ側)
Push通知のコードスニペット
実装手順
- Push通知の設定
- デバイストークンの送信
- Push通知を受け取る
1. Push通知の設定
iOS7以下とiOS8以上で仕様が違う
import UIKit class RemotePushManager { class func registerForRemoteNotifications(application: UIApplication) { if #available(iOS 8.0, *) { let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { application.registerForRemoteNotificationTypes([.Alert, .Badge, .Sound]) } } }
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { RemotePushManager.registerForRemoteNotifications(application) return true }
2. デバイストークンの送信
自前サーバーへデバイストークンを送信する
//MARK: - リモートプッシュ通知 func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let characterSet: NSCharacterSet = NSCharacterSet(charactersInString: "<>") let deviceTokenString: String = (deviceToken.description as NSString) .stringByTrimmingCharactersInSet(characterSet) .stringByReplacingOccurrencesOfString(" ", withString: "") as String print(deviceTokenString) //TODO : デバイストークンの送信 } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { }
3. Push通知を受け取る
import UIKit class RemotePushManager { class func received(application: UIApplication, launchOptions: [NSObject: AnyObject]?) { if let launchOptions = launchOptions { if let aps = launchOptions["aps"] as? [NSObject: AnyObject] { print(aps["alert"]) print(aps["sound"]) print(aps["badge"]) } } } }
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { RemotePushManager.registerForRemoteNotifications(application) if let launchOptions = launchOptions { if let option : NSDictionary = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary { self.application(application, didReceiveRemoteNotification: option as [NSObject : AnyObject]) } } return true } //Push通知受信時とPush通知をタッチして起動したとき func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { RemotePushManager.received(application, launchOptions: userInfo) switch application.applicationState { case .Inactive: break case .Active: break case .Background: break } } }
APNSから受信するデータは、下記のようなイメージ
{ "aps":{ "alert": "New Message", "badge": 3, "sound": "sound1.aiff", "content-available": 1 // -> サイレントプッシュ }, "name": "value" }
サーバー側
サーバーサイトは、下記のようなライブラリを使うと便利です。