gpt4 book ai didi

swift - 无法将类型 'NSURL' 的值转换为预期参数类型 'NSURLRequest'

转载 作者:行者123 更新时间:2023-11-30 10:05:54 25 4
gpt4 key购买 nike

对于 POST 请求,我使用以下代码:

private func post(url: String, params: [String: AnyObject], headers: [String: AnyObject]) {

let url = NSURL(string: apiUrl)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Application")

do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
} catch {
print("error")

//POST with completionHandler
var task = session.dataTaskWithRequest(url, completionHandler: { (data, response, error) -> Void in
print(data)
})
}
}

在以 var task = ... 开头的行中,我收到此错误:无法将类型“NSURL”的值转换为预期参数类型“NSURLRequest”

最佳答案

更改此行:

var task = session.dataTaskWithRequest(url, completionHandler: { (data, response, error) -> Void in

并传入请求...而不是 url:

var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in

始终读取您正在调用的方法名称,这是专门创建带有 REQUEST 的 dataTask,xcode 也应该突出显示这一点。

NSURLSession Documentation

关于swift - 无法将类型 'NSURL' 的值转换为预期参数类型 'NSURLRequest',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35988002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com