首先,我创建了一个发送“GET”请求到Amazon AWS服务器的函数,并获取JSON响应,然后将这些数据放入表格中。当我第一次调用这些数据时,一切都很完美,但当我回到主屏幕并再次打开带有表格的视图时,同样的函数失败并返回不正确的标题错误,尽管它第一次成功了。下面是代码:
函数:
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发送请求,每次都能成功,但在这里只有第一次执行函数才有效。如果我关闭并重新打开应用程序,则再次仅能在第一次执行时有效。请问如何解决?