Menggunakan Alamofire Untuk Networking Di Swift

Supaya aplikasi bisa terhubung dengan server untuk transaksi database, maka dibutuhkan networking / koneksi ke server. Untuk mengkoneksikan ke server kita akan belajar menggunakan library Alamofire yang dikembangkan oleh Alamofire Software Foundation.

Buat new project seperti berikut :

Klik kanan New File…

Pilih Source Cocoa Touch Class, klik Next

Input Class : ViewLogin, Subclass of : UIViewController, klik Next

Klik Create

Tampilan ViewLogin

Selanjutnya klik Main.storyboard -> Klik ViewController -> pada pojok kanan atas Klik Show the Identity Inspector, pada Cutom Class -> Class ganti dengan ViewLogin yang sudah kita buat.

Klik Show the Asistant editor pojok kanan atas, pilih All Editor Stacked Horizontally

Selanjutnya kita menghubungkan desain dengan Source Code pada setiap komponen. Dengan cara menekan tombol keyboard Control + Drag ke Source Code. Lakukan untuk semua label dan Button.

Maka hasil pada source code :


//  ViewLogin.swift
//  Sewa Mobil
//
//  Created by Handoyo on 3/28/18.
//  Copyright © 2018 Handoyo. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class ViewLogin: UIViewController {

    @IBOutlet weak var labelEmail: UITextField!
    @IBOutlet weak var labelPassword: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func goLogin(_ sender: Any) {
        
    }

}

Membuat networking menggunakan Library Alamofire.

  • Install Cocoapod terlebih dahulu.
    Buka terminal, ketikkan code :
    # Xcode 8 + 9
    $ sudo gem install cocoapods
  • Masih di Terminal (pod sudah terinstall), ketikkan code :
    $ pod init
  • Masih di Terminal, ketikkan code :
    $ open -a xcode Podfile, ketikkan add pada Podfile, “pod ‘Alamofire'” dan “pod ‘SwiftyJSON'”

  • Masih di Terminal, ketikkan code :
    $ pod install

Buka info.plist (untuk koneksi) tambahkan code seperti berikut :

Ketikkan code pada Action Button Login :


@IBAction func goLogin(_ sender: Any) {

     DispatchQueue.main.async(execute: {
          let parameters = [
               "email": self.labelEmail.text!,
               "password": self.labelPassword.text!
          ]

          let url:String = "http://localhost/sewamobil/api/login.php"

          Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in
               if let value = response.result.value {
                    let json = JSON(value)
                    for item in json["login"].arrayValue {
                        if (item["info"].stringValue == "Success, You are now login!") {
                            let alertController = UIAlertController(title: "Login Success!", message: item["info"].stringValue, preferredStyle: .alert)

                            let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in

                            }

                            alertController.addAction(OKAction)
                            self.present(alertController, animated: true, completion:nil)
                        } else {
                            let alertController = UIAlertController(title: "Login Failed!", message: item["info"].stringValue, preferredStyle: .alert)

                            let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in

                            }

                            alertController.addAction(OKAction)
                            self.present(alertController, animated: true, completion:nil)
                        }
                    }
               }
          }
     })

}

Build / Run Project
Hasil di simulator iPhone X

NB : ( Untuk Rest API yang menggunakan Content-Type : multipart/form-data )
Contoh penggunaan seperti berikut :

let headers = [
    "Content-Type": "multipart/form-data"
]

let catalog_nama: String = "Buku Saku Pramuka"
let catalog_harga: String = "7500"
let catalog_deskripsi: String = "Edisi Terbaru 2021"
let catalog_image: String = "http://127.0.0.1:8000"

DispatchQueue.main.async(execute: {
    let url:String = "http://127.0.0.1:8000/create_product"
    Alamofire.upload(multipartFormData: { multipart in
        multipart.append(catalog_nama.data(using: .utf8)!, withName: "catalog_nama")
        multipart.append(catalog_harga.data(using: .utf8)!, withName: "catalog_harga")
        multipart.append(catalog_deskripsi.data(using: .utf8)!, withName: "catalog_deskripsi")
        multipart.append(catalog_image.data(using: .utf8)!, withName: "catalog_image")
    }, to: url, method: .post, headers: headers) { [self] encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload
                .validate(statusCode: 200 ..< 300)
                .responseJSON { [self] response in
                    switch response.result {
                    case .success:
                        if let value = response.result.value {
                            let json = JSON(value)
                            let alertController = UIAlertController(title: "Success", message: json["message"].stringValue, preferredStyle: .alert)
                            let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in }
                            alertController.addAction(OKAction)
                            self.present(alertController, animated: true, completion:nil)
                        }
                    case .failure(let error):
                        handleError(error: error)
                    }
            }
        case .failure(let error):
            handleError(error: error)
        }
    }
})

func handleError(error: Error) {
    let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
    let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in }
    alertController.addAction(OKAction)
    self.present(alertController, animated: true, completion:nil)
}

Sekian dulu tutorialnya, selamat mencoba.
Happy coding 🙂

Leave a Reply

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