gpt4 book ai didi

ios - Swift 3 NSMutableURLRequest 第二次调用失败

转载 作者:搜寻专家 更新时间:2023-10-31 23:09:13 24 4
gpt4 key购买 nike

总而言之,我创建了一个向亚马逊 aws 服务器发送“GET”请求的函数,并获得 JSON 格式的响应,然后将这些数据放在一个表中。当我第一次调用此数据时,一切正常,但当我返回主屏幕并再次打开带有表格的 View 时,相同的功能失败,返回不正确的标题错误,即使它是第一次工作,我附上代码:

功能:

func getData(url:String, complete: @escaping ([Int:Any]) -> Void) {
var array: [Int:Any] = [:]
let headers = [
"authorization": "Bearer codeBearer",
"cache-control": "no-cache"
]
print(headers)
print(url)
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error!) // errore
} else {
let input = String(data: data!, encoding: .utf8)?.data(using: .utf8) // json
let json = try! JSON(data: input!)
print(json)
for (_,subJson):(String, JSON) in json {
let num = subJson["index"].int
if( num != nil ){
array[num!] = subJson
}
}
session.invalidateAndCancel()
complete(array)
}
})
dataTask.resume()
}

查看:

@IBOutlet weak var table: UITableView!

func reload(){
DispatchQueue.main.async{
self.table.reloadData()
}
}

override func viewDidLoad() {
super.viewDidLoad()
if( idCell == "cell" ){
fun.getData(url: fun.request("/v1/media", test: true), complete: { success in
self.array = success
self.reload()
})
}else{
fun.getData(url: fun.request("/v1/banner", test: true), complete: { success in
self.array = success
self.reload()
})
}
}

错误:

    {
"message" : "'codeBearer' not a valid key=value pair (missing equal-sign) in Authorization header: 'Bearer codeBearer'."
}

如果我尝试通过 curl 发送请求,它每次都有效,而这里仅在我第一次执行该功能时有效,但如果我关闭并重新打开应用程序,它会在第一次再次有效,提示如何修复它?

最佳答案

要清理您的 session ,请在下面调用。

session.invalidateAndCancel()

关于ios - Swift 3 NSMutableURLRequest 第二次调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45527331/

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