How to Integrate Alamofire in Your Swift App Development Project?

Alamofire is an HTTP networking library written in Swift.

Previously, we were using AFNetworking as HTTP networking library with Objective-C because AFNetworking is the Objective-C version of the library. However, now, we are using Alamofire Swift, as it is a Swift version of AFNetworking.

Let’s start integrate Alamofire Swift tutorial:

To integrate Alamofire, you need to install cocoapods. (Please refer this link for install cocoapods : https://guides.cocoapods.org/using/getting-started.html)

Now, follow these steps:

  1. Go to Terminal

  2. command “cd” and give the path of your project and then press “Enter” key

    Alamofire1

  3. Create a pod file in your project by terminal by command “touch Podfile” and press “Enter”

    Note: Name should be “Podfile”

    Alamofire2

  4. Then, open “Podfile” by terminal command “open Podfile” and press “Enter”

  5. Type following in “Podfile”
    source ‘https://github.com/CocoaPods/Specs.git’
    platform :ios, ‘8.0’
    use_frameworks!
    pod ‘Alamofire’, ‘~> 3.0.0’

    and close it with saving.

    Alamofire3

  6. Once you complete this process then come to the terminal again and type command “Pod install” and then press “Enter” Key.

    Alamofire4

    Once, you have entered this command, you will find below code in your terminal window.

    Alamofire5

    It will install Alamofire in your project. Now, you can use it easily.

    After that, you have to import Alamofire using

    import Alamofire
    

    Alamofire request

    example:
    Alamofire.request(.GET, strURL, parameters: nil, encoding: .URL, headers: nil)

    There are built-in Response Methods for Response Serialization, which we can use

    response()
    responseData()
    responseString(encoding: NSStringEncoding)
    responseJSON(options: NSJSONReadingOptions)
      responsePropertyList(options: NSPropertyListReadOptions)
    

    Example:

    Alamofire.request(.GET, strURL, parameters: ["user_id" : "1"], encoding: .URL, headers: nil).responseData { (response) in
     
    }
    

    In Alamofire request, we have to pass following data

    1. HTTP Method

      We have to pass Alamofire.Methods which is already defined as the public enum.

       
      public enum Method: String {
      	case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
      }
      

      We can use it like

      Alamofire.request(.GET, strURL, parameters: ["user_id" : "1"], encoding: .URL, headers: nil)
       
      Alamofire.request(.POST, strURL, parameters: [“name” : “jhon”], encoding: .URL, headers: nil)
       
      Alamofire.request(.DELETE, strURL, parameters: [“post_id” : “1”], encoding: .URL, headers: nil)
      
    2. Base Url

      Commonly, we define a BASEURL in the code and then add endpoint

      For ex:

      let BASEURL = http://www.callapi.com/

      When we go for call API we add endpoint to BASEURL
      for ex: strURL = BASEURL+”login”

    3. Parameters

      Parameters should be a dictionary of [String : AnyObject]?

      If you don’t pass parameters in API, it will be nil.

      For example:

      Alamofire.request(.GET, strURL, parameters: ["user_id" : "1"], encoding: .URL, headers: nil)
       
      Alamofire.request(. GET, strURL, parameters: nil, encoding: .URL, headers: nil)
      
    4. Parameter Encoding

      Parameters can also be encoded as JSON, URL or custom format. In Alamofire, we have enum (enumeration) for the same.

      public enum ParameterEncoding {
      	case URL
      	case URLEncodedInURL
      	case JSON
      	case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
      	case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
      }
      

      Most of them, we use .URL/.JSON parameter encoding

    5. HTTP Headers

      If you need to pass Headers in a request, then you can pass it in [String : String]? format
      This should be nil, in case we not have to pass Header in a request.

      for ex:

          	let headers = [
              	"Authorization": "Basic",
              	"Accept": "application/json"
          	]
       
          	Alamofire.request(. GET, strURL, parameters: nil, encoding: .URL, headers: headers)
       
       
          	Alamofire.request(.GET, strURL, parameters: nil, encoding: .URL, headers: nil)
      

      Uploading file by Alamofire
      By using Alamofire, we can upload any of file and Data. It also supports MultipartFormData, also shows the process of data uploaded.

      Uploading File

          	Alamofire.upload(.POST, strURL, file: fileURL).progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
              	print(totalBytesWritten)
          	}.responseJSON { (response) in
              	print(response)
          	}
      

      Uploading MultipartFormData

          	Alamofire.upload(.POST, strURL, multipartFormData: { (MultipartFormData) in
                  MultipartFormData.appendBodyPart(data: fileData, name: "myfile")
              	}) { (dataResult:Manager.MultipartFormDataEncodingResult) in
                  	switch dataResult {
                  	case .Success(let upload,_,_):
                          upload.responseJSON { response in
                              // success block
                              debugPrint(response)
                          }
                          upload.progress { _, totalBytesRead, totalBytesExpectedToRead in
                              // progress block
                          }
       
                  	case .Failure(let encodingError):
                          print(encodingError)
                  	}
          	}
       
      

      Do you have any queries about anything you have seen? If yes, then you are free to ask anything through comment. we’d also love to read your comments. You can also hire Swift developer to integrate Alamofire in swift 4 project.

    You may also like,

    This page was last edited on January 11th, 2021, at 6:03.

Author Bio

Hitesh Trivedi

Hitesh Trivedi

Designation: iOS Team Lead

Hitesh Trivedi is an iOS Team Lead at Space-O Technologies. He has over 9 years of experience in iOS app development. He has guided to develop over 100 iPhone apps with unique features and functionalities. He has special expertise in Swift and Objective-C.

 
 

Have an App Idea?

Get your free consultation now

Leave a Reply

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