I've updated to the latest version of Xcode (8) and after upgrading the code to Swift 3, Alamofire suddenly stops working and throwing a lot of errors.
After a lot of research, I find that Alamofire for Swift 3 is compatible with iOS9+, so now I have to find another one that works with iOS8+.
Do you know how can I make the same functionality as Alamofire for iOS8?
try this fork, https://github.com/tonyli508/AlamofireDomain
or pod directly:
pod 'AlamofireDomain', '~> 4.0'
I didn't find a "real" alternative to Alamofire for iOS 8, so I tried using the URLRequest from Apple's Swift itself.
So here is the example I finally got after trying and trying (even without 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
}
I hope it could help other developers. I will be much appreciated if someone found another possible solution to this problem.
Regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With