我没有找到适用于 iOS 8 的 Alamofire 的“真正”替代品,因此我尝试使用 Apple Swift 本身的 URLRequest。
所以这是我经过多次尝试最终得到的例子(即使没有 SwiftyJSON):
func searchPosts() -> [Post] {
var request = URLRequest(url: URL(string: "https://www.mywebsite.com/searchPosts.php")!)
request.httpMethod = "POST"
let postString = ""
request.httpBody = postString.data(using: .utf8)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print(httpStatus.statusCode)
self.showError()
} else {
do {
self.listPosts = [Post]()
// Convert NSData to Dictionary where keys are of type String, and values are of any type
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
for field in json["posts"] as? [AnyObject] ?? [] {
// Create "Post" object
let post = Post(
id: (field["id"])! as! String,
title: (field["title"] as! String),
alias: (field["alias"] as! String),
catid: (field["catid"] as! String),
catname: (field["catname"] as! String),
date: (field["date"] as! String),
image: (field["image"] as! String),
introtext: (field["introtext"] as! String),
fulltext: (field["fulltext"] as! String)
)
self.listPosts.append(post)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
self.showError()
}
}
}
task.resume()
return listPosts
}
Run Code Online (Sandbox Code Playgroud)
我希望它可以帮助其他开发者。如果有人找到此问题的另一种可能的解决方案,我将不胜感激。
问候
| 归档时间: |
|
| 查看次数: |
2636 次 |
| 最近记录: |