【问题标题】:How to store push notification token into external database - iOS 10, Swift 3如何将推送通知令牌存储到外部数据库 - iOS 10,Swift 3
【发布时间】:2016-10-12 01:28:52
【问题描述】:

我已经实现了 FCM,我想从我自己的应用服务器(用 PHP 编写)发送推送通知。因此,我需要将 fcm 的设备令牌存储在我的 Phpmyadmin 数据库中。有没有办法将令牌从 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)

}

数据库表结构:

【问题讨论】:

  • 你的代码很好,你的 web 服务代码用于发送服务器令牌
  • 嗨 Anbu Karithik,我刚刚在 iOS 上创建了将 POST 请求发送到服务器,这是将令牌传递到我的 phpmyAdmin 数据库的正确方法吗?感谢您的评论
  • 100% 正确,你需要这个支持吗
  • 是的,非常感谢您的努力!

标签: ios swift xcode swift3


【解决方案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()
   }

第二步

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

第三步

在两个地方调用方法

 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.
    
}

【讨论】:

  • 非常感谢 Anbu,它在 iOS 10 中就像一个魅力 :) 祝你有美好的一天
  • 您好 Anbu,我意识到存储在我的数据库表中的令牌字符串始终为空,希望您也可以协助调查此问题,我已将其作为另一个问题发布,您可以参考 @ 987654322@
猜你喜欢
  • 2017-01-26
  • 1970-01-01
  • 2016-10-16
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多