参考資料
環境
- Xcode: v7.1
- Nifty cloud mobile backend: v2.2.3
SDKインストール
この記事を書いた段階では、Podからインストールするとエラーが発生するため、SDKをダウンロードして利用する方法で、インストールします。
(追記: エラーはv2.2.5にて対応されたようです。)
実装
ドキュメントに、Swift版のサンプルコードがなかったので、自分で移植しました。
AppDelegate.swift
AppDelegate.swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// アプリが起動したとき
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NCMB.setApplicationKey(Const.NcmbApplicationKey, clientKey: Const.NcmbClientKey)
// プッシュ通知の設定
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications() // DeviceTokenを要求
// アプリ起動時のプッシュ通知
if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
print("Remote Notification \(remoteNotification)")
}
return true
}
// Push通知の登録が完了した場合、deviceTokenが返される
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData ) {
let installation = NCMBInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackgroundWithBlock { (error: NSError?) -> Void in
if let e = error {
// 端末情報の登録が失敗した場合の処理
print(e.description)
if (e.code == 409001){
// 失敗した原因がdeviceTokenの重複だった場合
self.updateExistInstallation(installation)
} else {
// deviceTokenの重複以外のエラーが返ってきた場合
}
}
}
}
// deviceTokenの重複で端末情報の登録に失敗した場合に上書き処理を行う
func updateExistInstallation(currentInstallation: NCMBInstallation) {
let installationQuery = NCMBInstallation.query()
installationQuery.whereKey("deviceToken", equalTo: currentInstallation.deviceToken)
do {
let searchDevice = try installationQuery.getFirstObject()
currentInstallation.objectId = searchDevice.objectId
currentInstallation.saveInBackgroundWithBlock { (error: NSError?) -> Void in
if error == nil {
// 端末情報更新に成功したときの処理
} else {
// 端末情報更新に失敗したときの処理
}
}
} catch let searchError as NSError {
// 端末情報の検索に失敗した場合の処理
print(searchError.description)
}
}
// Push通知が利用不可であればerrorが返ってくる
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
NSLog("#### didFailToRegisterForRemoteNotificationsWithError: " + "\(error.description)")
}
// 起動中に受け取ったプッシュ通知
func application(application: UIApplication, didReceiveRemoteNotification userInfo:[NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void){
print("#### didReceiveRemoteNotification")
print("User Info \(userInfo)")
}
}