【问题标题】:How to work with Backendless REST API in swift 3如何在 swift 3 中使用 Backendless REST API
【发布时间】:2016-12-22 07:53:22
【问题描述】:

我正在尝试使用 IOS swift 3 连接回无尽的休息 api。 我正在添加应用程序 ID,如下所示的密钥

request.addValue("0C896F8C-D3CE-BD08-FF1D-2B087CE77B00", forHTTPHeaderField: "application-id")
request.addValue("9D9A2BCD-F272-16E8-FF01-CD5AFD8CC300", forHTTPHeaderField: "secret-key")

我也得到了

致命错误:在展开可选值时意外发现 nil

在这行代码中

 let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("Body: \(strData)")

谁能告诉我发生了什么事...

let request = NSMutableURLRequest(url: NSURL(string:"/v1/users/login") as! URL)
        let session = URLSession.shared
        request.httpMethod = "POST"
        let params = ["name":"mm", "password":"mm"] as Dictionary<String, String>

        request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
        request.addValue("0C896F8C-D3CE-BD08-FF1D-2B087CE77B00", forHTTPHeaderField: "application-id")
        request.addValue("9D9A2BCD-F272-16E8-FF01-CD5AFD8CC300", forHTTPHeaderField: "secret-key")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("REST", forHTTPHeaderField: "application-type")

        request.addValue("application/json", forHTTPHeaderField: "Accept")

       let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
            print("Response: \(response)")
            let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("Body: \(strData)")

        let json = try! JSONSerialization.jsonObject(with: data!, options: .mutableLeaves)
        print(json)
        //JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

            // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(error != nil) {
               // print(err!.localizedDescription)
                let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
            else {
                // The JSONObjectWithData constructor didn't return an error. But, we should still
                // check and make sure that json has a value using optional binding.
                if let parseJSON = json as? NSDictionary   {                   // Okay, the parsedJSON is here, let's get the value for 'uccess' out of it
                    let success = parseJSON["success"] as? Int
                    print("Succes: \(success)")
                }
                else
                {
                    // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                    let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                    print("Error could not parse JSON: \(jsonStr)")
                }
            }
        })

        task.resume()

【问题讨论】:

  • 你从完成处理程序的响应中得到什么?在这种情况下,数据很容易为空,例如如果请求失败或返回空响应
  • 我建议使用github.com/Alamofire/Alamofire 而不是发明自行车
  • 在解包数据之前,您是否将错误检查为零?...似乎可能出现了一些错误
  • 我得到如下响应:响应:可选( { URL:api.backendless.com/v1/users/login } {状态代码:400,标题 {“Access-Control-Allow-Headers”=“ Origin、application-id、application-type、Content-Type、secret-key、request、user-token";@mlidal

标签: ios xcode swift3 backendless


【解决方案1】:

你需要先检查数据不为零:

if let d = data {
    let strData = NSString(data: d, encoding: String.Encoding.utf8.rawValue)
    print("Body: \(strData)")
} else {
    print(error)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    相关资源
    最近更新 更多