Swift4投掷函数类型'(_,_,_)抛出的无效转换 - > ()'到非投掷函数类型'(数据?,URLResponse?,错误?)

时间:2018-02-09 19:22:41

标签: json swift httprequest

func DoLogin(_ email:String, _ password:String)
{
    struct User: Decodable {
        let sfname: String
        let slname: String
        let email: String
        let sid: Int
    }

    let url = URL(string: "http://URL")!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let postString = "email=" + email + "&password=" + password + ""
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print(error!)
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print(response!)
        }

       if let responseString = String(data: data, encoding: .utf8){
        let myStruct = try JSONDecoder().decode(User.self, from: responseString)
        }
    }

    task.resume()
}

所以目的是解码HTTP响应responseString以便将信息保存到User的属性中,但是在按顺序插入代码行后,我仍然会弹出相同的错误解码HTTP响应(myStruct)。我觉得它与Do Try Catch错误处理有关,但无法解决这个问题。

提前感谢您的帮助:)

1 个答案:

答案 0 :(得分:6)

这是你的问题:

let myStruct = try JSONDecoder().decode(User.self, from: responseString)

的完成处理程序
URLSession.shared.dataTask(with: URLRequest, completionHandler: (Data?, URLResponse?, Error?) -> Void)

不允许抛出或重新抛出异常。如果有的话,签名将是这样的:

URLSession.shared.dataTask(with: URLRequest, completionHandler: (Data?, URLResponse?, Error?) throws -> Void)

(请注意方法签名中的throws

此外,您需要确保将responseString更改为datadecode方法需要Data个对象,而不是String。实际上根本不需要将data转换为String,因此您可以从代码中删除此if语句:

if let responseString = String(data: data, encoding: .utf8)

尝试做这样的事情:

do {
    let myStruct = try JSONDecoder().decode(User.self, from: data)
    //do something with myStruct
} catch let error as NSError {
    //do something with error
}

或者这个:

if let myStruct = try? JSONDecoder().decode(User.self, from: data) {
    //do something with myStruct
} else {
    //handle myStruct being nil
}