swift - 在数据库中存储 token 的 Http post 请求

标签 swift push-notification apple-push-notifications

我在 wordpress 中实现推送通知,除了将 token 存储在数据库中外,一切都对我有用。

我在 AppDelegate.swift 中有以下功能

// send token

func SendToken(_ token: String)
{
    //info device

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


    // create the request

    let stringUrl = "http://example.com/wp/wp-json/apnwp/register?os_type=ios&user_email_id=pushx@40test.com&device_token=\(token)"

    let stringUrlEncoded = stringUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
    let myUrl = URL(string: stringUrlEncoded!)



    var request = URLRequest(url: myUrl!)


    // 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("There was error during datatask session")
            print(error!)
        } else {
            do {
                guard let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else { return }
                //print(json as Any)

                guard let errors = json?["errors"] as? [[String: Any]] else { return }


                if errors.count > 0 {
                    // show error
                    print("There is an error during parse JSON datatask")
                    return
                } else {
                    // show confirmation
                    print("datatask with JSON format performed successfully")
                }
            }
        }
        print(request)
    }).resume()
}
//end send token

我使用的插件文档说明如下:

URL structure:

http://yourwordpresssite/wp-json/apnwp/register

Method:  GET

Parameters:
device_token (string): token given by APNs or FCM identifying the device, often called device ID.
os_type (string): operating system. It must be ios or android (case sensitive).
user_email_id (string, optional): the user email address which is login from your mobile app.

Examples:

http://yourwordpresssite/wp-json/apnwp/register?os_type=android&user_email_id=androidmobile@40test.com&device_token=1234567890

在 AppDelegate.swift 中我调用函数:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""
    for i in 0..<deviceToken.count {

        token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])

    }
    print("New token is: \(token)")

    SendToken(token)

}

但是将数据保存在数据库中不起作用,但是如果我输入 URL (//yourwordpresssite/wp-json/apnwp/register?os_type=android&user_email_id=iosdmobile@40test.com&device_token=1234567890) 在浏览器中,如果它存储在数据库中。

如果有任何帮助,我将不胜感激。

最佳答案

查看插件文档,我在您的代码中发现了一些问题:

<强>1。方法:GET

你的http方法是GET,不是POST

<强>2。 httpBody 为 ["token": token]

您已经在 urlRequest 的末尾附加 token 作为 ?os_type=ios&user_email_id=pushx@40test.com&device_token=\(token)

即使是使用 request.httpBody = nil 调用 GET 请求,您的所有参数都应附加在 urlRequest 中。

<强>3。使用 [ ] 而不是 .allowFragments

解码 JSON 对象

我不确定这一点,但如果您无法解析数据,您应该使用 [] 而不是 .allowFragments

guard let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any] else { return }

Try updating your code as:

func SendToken(_ token: String) {
    // Create reuest
    let stringUrl = "http://example.com/wp/wp-json/apnwp/register?os_type=ios&user_email_id=pushx@40test.com&device_token=\(token)"
    let stringUrlEncoded = stringUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
    let myUrl = URL(string: stringUrlEncoded!)
    var request = URLRequest(url: myUrl!)

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

    // append the paramter to body
    request.httpBody = nil

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

                guard let errors = json?["errors"] as? [[String: Any]] else { return }

                if errors.count > 0 {
                    // show error
                    print("There is an error during parse JSON datatask")
                    return
                } else {
                    // show confirmation
                    print("datatask with JSON format performed successfully")
                }
            }
        }
        print(request)
    }).resume()
}

关于swift - 在数据库中存储 token 的 Http post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49871374/

相关文章:

ios - 属性 'self.*' 未在 super.init 调用时初始化

ios - Swift:实例化 View Controller 以在当前导航堆栈中进行自定义转换

php - Apple 推送通知服务 APNS - 通知未到达

ios - 如何在 iphone 中点击应用程序图标时清除角标(Badge)计数器?

iphone - 如何从我们的服务器中找到是否已发送给用户的 Apple Push Notification?

ios - UITextField 子类,下方有栏 : bar not going all the way

ios - 将上下文传递给多个 InterfaceControllers?

laravel - 使用 Laravel FCM 向设备和 Web 浏览器发送推送通知

c# - 如何添加时间以使用 .Net(C#) 发送 API 推送消息 (parse.com)

ios - Swift 中的推送通知和 token 设备