Help us understand the problem. What is going on with this article?

Nifty cloud mobile backend + Swift

More than 3 years have passed since last update.

参考資料

環境

  • 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)")
  }
}

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした