Alamofire in Swift 3 with iOS 8

I upgraded to the latest version of Xcode (8) and after updating the code to Swift 3, Alamofire suddenly stops working and throws a lot of errors.

After much research, I found that Alamofire for Swift 3 is compatible with iOS9 +, so now I need to find another one that works with iOS8 +.

Do you know how I can do the same functionality as Alamofire for iOS8?

+6
source share
2 answers

I did not find a “real” alternative to Alamofire for iOS 8, so I tried using URLRequest from Apple Swift itself.

So, here is an example that 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 } 

Hope this helps other developers. I will be very grateful if someone finds another possible solution to this problem.

Hi

+2
source

try this fork, https://github.com/tonyli508/AlamofireDomain

or pod directly:

pod 'AlamofireDomain', '~> 4.0'

+3
source

All Articles