我有一个iOS应用程序,我从服务器获取我的信息,问题是我使用的任何请求都没有工作,因为代码执行退出代码,然后从服务器返回响应,或者可能它失败了,无论如何这是我迄今为止所尝试的:
let manager = AFHTTPSessionManager()
manager.post("www.myapps.com/api/Files/getFiles?folderId=6", parameters: nil, progress: nil, success: { (task: URLSessionTask, responseObject) in
if let response = responseObject as? [String:Any],
let medias = response["medias"] as? [String:Any] {
locked = false
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let url = NSURL(fileURLWithPath: documentsPath)
let contentFile = url.appendingPathComponent("Content.json")
if let data = try? JSONSerialization.data(withJSONObject: medias) {
try? data.write(to: contentFile!, options: .atomic)
}
let data = try! Data(contentsOf: contentFile!)
self.jsonData = JSON(data:data)
self.categoriesCount = self.jsonData["categories"].count
print(self.categoriesCount)
}
},failure: { (operation: URLSessionTask!, NSError) in
print(NSError.localizedDescription)
})
while locked {
wait()
}
}
func wait()
{
DispatchQueue.main.async {
RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: NSDate(timeIntervalSinceNow: 1) as Date)
}
}
请记住,如果我直接在浏览器中使用我的网址,我会得到一个回复,这意味着它正在运行,但在我的应用程序中,任何想法都会出错?
答案 0 :(得分:-1)
我通过使用Alamofire同步方法解决了以下问题:
let response = Alamofire.request("http://www.appsandgamesinc.com/api/Files/getFiles", method: .post, parameters: ["folderId": "6"]).responseJSON(options: .allowFragments)
if let json = response.result.value {
print(json)
}