如何将推送通知令牌存储到外部数据库 - iOS 10,Swift 3

时间:2016-10-12 01:28:53

标签: ios swift xcode swift3

我实现了FCM,我想从我自己的应用服务器发送推送通知(用PHP编写)。因此,我需要在我的Phpmyadmin数据库中存储fcm的设备令牌。有没有办法将令牌从iOS swift存储到我的数据库中?如果有人会就此问题给我一些提示,我将不胜感激,谢谢!

AppDelegate.swift

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""

    for i in 0..<deviceToken.count {
        token += String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }

    print("Registration succeeded!")
    print("Token: ", token)

}

数据库表格结构:

enter image description here

1 个答案:

答案 0 :(得分:2)

<强>步骤1

  

在两个地方创建访问的常用方法

  func Callquery(_ token: String)   
 {

  // append parameter to oneDictionary
  let tokenString = ["keyName": token] as [String: Any]

   // create the request
  var request = URLRequest(url: URL(string:"yourServer URL")!)

  // set the method as POST
  request.httpMethod = "POST"

  // append the paramter to body
  request.httpBody = try! JSONSerialization.data(withJSONObject: tokenString, options: [])

// create the session
URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
    if error != nil {
        print(error)
    } else {
        do {
            guard let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else { return }

            guard let errors = json?["errors"] as? [[String: Any]] else { return }
                if errors.count > 0 {
                    // show error
                    return
                } else {
                    // show confirmation
                }
            }
        }
    }).resume()
   }

<强>步骤-2

iOS9 之后我们需要在 .plist 中加入传输安全性,请参阅example

<强>步骤-3

在两个地方调用方法

 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
  print("Registration failed!")

    Callquery("") // pass the empty paramter if user deny the permission.

   }

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""

    for i in 0..<deviceToken.count {
        token += String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }

    print("Registration succeeded!")
    print("Token: ", token)

      Callquery(token) // pass the token paramter if user accept the permission.

}