Ios 如何在swift 3中使用REST API

Ios 如何在swift 3中使用REST API,ios,xcode,swift3,backendless,Ios,Xcode,Swift3,Backendless,我正在尝试使用iOSSwift 3连接到RESTAPI。 我正在添加应用程序id和密钥,如下所示 request.addValue("0C896F8C-D3CE-BD08-FF1D-2B087CE77B00", forHTTPHeaderField: "application-id") request.addValue("9D9A2BCD-F272-16E8-FF01-CD5AFD8CC300", forHTTPHeaderField: "secret-key") 而且我也得到了 致命错误:在

我正在尝试使用iOSSwift 3连接到RESTAPI。 我正在添加应用程序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()
let request=NSMutableURLRequest(url:NSURL(字符串:“/v1/users/login”)as!url)
让session=URLSession.shared
request.httpMethod=“POST”
让params=[“name”:“mm”,“password”:“mm”]作为字典
request.httpBody=try?JSONSerialization.data(带jsonObject:params,选项:[]))
请求添加值(“0C896F8C-D3CE-BD08-FF1D-2B087CE77B00”,用于HttpHeaderField:“应用程序id”)
请求添加值(“9D9A2BCD-F272-16E8-FF01-CD5AFD8CC300”,用于HttpHeaderField:“密钥”)
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“REST”,forHTTPHeaderField:“应用程序类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
让task=session.dataTask(其中:request作为URLRequest,completionHandler:{data,response,error->Void in
打印(“响应:\(响应)”)
让strData=NSString(数据:data!,编码:String.encoding.utf8.rawValue)
打印(“正文:\(标准数据)”)
让json=try!JSONSerialization.jsonObject(带:data!,选项:.mutableLeaves)
打印(json)
//JSONObjectWithData(数据,选项:.MutableLeaves,错误:&err)作为NSDictionary
//JSONObjectWithData构造函数是否返回错误?如果是,请将错误记录到控制台
如果(错误!=nil){
//打印(错误!.localizedDescription)
让jsonStr=NSString(数据:data!,编码:String.encoding.utf8.rawValue)
打印(“错误无法分析JSON:'\(jsonStr)'”)
}
否则{
//JSONObjectWithData构造函数没有返回错误。但是,我们仍然应该
//使用可选绑定检查并确保json具有值。
如果让parseJSON=json作为?NSDictionary{//好的,parsedJSON在这里,让我们从中获取'uccess'的值
让success=parseJSON[“success”]作为?Int
打印(“成功:\(成功)”)
}
其他的
{
//哇,好吧,json对象为零,出现了问题。可能服务器没有运行?
让jsonStr=NSString(数据:data!,编码:String.encoding.utf8.rawValue)
打印(“错误无法解析JSON:\(jsonStr)”)
}
}
})
task.resume()

您需要先检查数据是否为零:

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

}

您从完成处理程序中的响应中得到了什么?在这种情况下,数据很容易为空,例如,如果请求失败或返回空响应,我建议使用bicycleDid而不是发明bicycleDid,在展开数据之前,将错误检查为零?。。似乎出现了一些错误,我得到的响应如下:响应:可选({URL:}{状态代码:400,标题{“访问控制允许标题”=“来源、应用程序id、应用程序类型、内容类型、密钥、请求、用户令牌”;@mlidal