Alamofire – HTTP networking library written in Swift

alamofire-swift

In a recent tutorial, I have shown you how to handle network calls in Objective-C using AFNetworking. Well the same guys that created that library, have done a dedicated one for Swift as well called Alamofire.

If you need detailed info on how to install it in your project please visit their GitHub repository, I will be focusing here on explaining how I use this library for creating calls.

 

Here we go: 

  
func requestWithEnd(endUrl: String,method:String,params:[String : AnyObject]?,success: ServiceResponse) -> Void{
        let url = getUrl(endUrl)
        if method == "GET"{
            Alamofire.request(.GET, url, parameters: params, encoding: ParameterEncoding.URL,headers: ["Cookie": getToken()]).responseJSON {
                response in
                if response.response?.statusCode == 200 {
                    let data = response.result.value
                    if let tmpData = data{
                        let json = JSON(tmpData)
                        success (json,nil)
                    }
                }
                else{
                    var e: NSError?
                    if let errorMessage = response.result.value?["error"]{
                        e = self.createError(errorMessage,code: response.response?.statusCode,url: url)
                    }
                    success (nil,e)
                }
            }
        }
        else if method == "POST"{
            Alamofire.request(.POST, url, parameters: params, encoding: ParameterEncoding.URL,headers: ["Cookie": getToken()]).responseJSON {
                response in
                                
                if response.response?.statusCode == 200 {
                    let s = "{}"
                    var json = JSON(s)

                    if let data = response.result.value{
                         json = JSON(data)
                    }
                    success (json,nil)

                }
                else{
                    var e: NSError?
                    if let errorMessage = response.result.value?["error"]{
                        e = self.createError(errorMessage,code: response.response?.statusCode,url: url)
                    }
                    success (nil,e)

                }
            }
        }
        else if method == "DELETE"{
            Alamofire.request(.DELETE, url, parameters: params, encoding: ParameterEncoding.URL,headers: ["Cookie": getToken()]).responseJSON {
                response in
                
                if response.response?.statusCode == 200 {
                    let data = response.result.value
                    let json = JSON(data!)
                    success (json,nil)
                }
                else{
                    var e: NSError?
                    if let errorMessage = response.result.value?["error"]{
                        e = self.createError(errorMessage,code: response.response?.statusCode,url: url)
                    }
                    success (nil,e)
                }
            }
        }
        else if method == "PUT"{
            Alamofire.request(.PUT, url, parameters: params, encoding: ParameterEncoding.URL,headers: ["Cookie": getToken()]).responseJSON {
                response in
                if response.response?.statusCode == 200 {
                    let data = response.result.value
                    let json = JSON(data!)
                    success (json,nil)
                }
                else{
                    var e: NSError?
                    if let errorMessage = response.result.value?["error"]{
                        e = self.createError(errorMessage,code: response.response?.statusCode,url: url)
                    }
                    success (nil,e)
                }
            }
        }
    }
    
    func getUrl(urlEnd: String) -> String {
        return "http://www.example.com/api/\(urlEnd)"
    }
    
    //MARK: Error Handler
    func createError(value: AnyObject?, code: Int!, url: String)-> NSError?{
        var errorMessage = ""
        let er = value as? NSArray
        var tmpCode = code

        if tmpCode == nil{
            tmpCode = 0
        }
        
        let error = NSError(domain: url, code: tmpCode, userInfo: ["message":errorMessage])
        return error
    }

 

Assuming that your response will be in JSON format, we are using one more library that you can see in the snippet (let json = JSON(data!)) which is called SwiftyJSON and helps us parse the response pretty easy.

This tutorial showed you everything you need to start creating/intercepting calls. I suggest you create one Singleton class and put this snippet there and you are good to go.

 

Leave a Reply

Your email address will not be published. Required fields are marked *