Jordi Jordi - 1 year ago 237
Swift Question

Alamofire in Swift 3 with iOS 8

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?

Answer Source

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: "")!)
    request.httpMethod = "POST"
    let postString = ""
    request.httpBody = .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 {
        } 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)

                DispatchQueue.main.async {
            } catch {


    return listPosts

I hope it could help other developers. I will be much appreciated if someone found another possible solution to this problem.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download