How to make iOS app connected to backend? Alamofire

alamofire

Almost every iOS app uses backend API. In this post we will use one of the most famous libraries for iOS developing – Alamofire.

Alamofire is library that helps us to send request and receive response from server. I thought, that it will be good to use public API and show example, that can repeat everybody. Let’s practice on loading current weather in Hamburg. We will use OpenWeatherMap API.

You can find source code of this project in my GitHub account.

Step 1

Create Xcode project. Please select “Single View Application” template. We will write all our code in ViewController.swift for simplicity. You project tree should look like this:

Screen Shot 2017-02-07 at 10.11.24

Step 2

Create account in OpenWeatherMap and generate API key. This API key will be used in your app. OpenWeatherMap identify you by API key and do not let you make too many requests. In Free plan we are limited to 60 requests per minute.

Step 3

Build interface. Interface will be very simple. I prefer to build view only by code (without using storyboard).

    var activityIndicatorView:UIActivityIndicatorView!
    var whiteLoadingView:UIView!
    var responseLabel:UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        buildView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func buildView() {
        let mainView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        self.view.addSubview(mainView)
        
        let titleLabel:UILabel = UILabel(frame: CGRect(x: 30, y: 30, width: mainView.frame.width - 60, height: 25))
        titleLabel.font = UIFont(name: "Helvetica-Bold", size: 18.0)
        titleLabel.text = "Current Hamburg weather:"
        mainView.addSubview(titleLabel)
        
        responseLabel = UILabel(frame: CGRect(x: titleLabel.frame.origin.x, y: 55, width: mainView.frame.width - 60, height: 20))
        responseLabel.font = UIFont(name: "Helvetica", size: 16.0)
        responseLabel.text = "-°C, -"
        mainView.addSubview(responseLabel)
        
        whiteLoadingView = UIView(frame: mainView.frame)
        whiteLoadingView.backgroundColor = UIColor.white
        whiteLoadingView.alpha = 0.7
        whiteLoadingView.isHidden = true
        mainView.addSubview(whiteLoadingView)
        
        activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        activityIndicatorView.center = CGPoint(x: mainView.frame.width/2, y: mainView.frame.height/2)
        activityIndicatorView.hidesWhenStopped = true
        mainView.addSubview(activityIndicatorView)
    }
    
    func loadingAnimation(isLoading:Bool) {
        if (isLoading) {
            self.whiteLoadingView.isHidden = false
            self.activityIndicatorView.startAnimating()
        } else {
            self.whiteLoadingView.isHidden = true
            self.activityIndicatorView.stopAnimating()
        }
    }

In responseLabel I wrote example data. This label’s text will be dynamic. activityIndicatorView is for showing loading process. whiteLoadingView prevent blocks user taps during loading and makes activityIndicatorView more visible. Run this project and you will need to see this page:

Screen Shot 2017-02-06 at 18.25.43

Step 4

Install Alamofire Pod. Example

Step 5

We are going to connect to not secured (not https) web site, so to avoid error “The resource could not be loaded because the App Transport Security policy requires the use of a secure connection” we need to edit info.plist. Add “App Transport Security Settings” with element “Allow Arbitrary Loads” => “YES“:

Screen Shot 2017-02-07 at 16.27.12

Step 6

Load data. We will use this API method.

    func loadData() {
        let API_URL:String = "http://api.openweathermap.org/data/2.5/weather"
        let API_KEY:String = "----------------------------"
        let parameters:[String:String] = [
            "q": "Hamburg",
            "units": "metric",
            "APPID": API_KEY
        ]
        let headerParameters:[String:String] = [
            "Authorization": "just example of header parameter"
        ]
        print(parameters)
        self.loadingAnimation(isLoading: true)
        Alamofire.request(API_URL, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headerParameters)
            .responseJSON { response in

                self.loadingAnimation(isLoading: false)

                if let JSON:[String:Any] = response.result.value as? [String:Any] {
                    let mainObject:[String:Any] = JSON["main"] as! [String:Any]
                    let temperatureInt:Int = mainObject["temp"] as! Int
                    
                    let weatherObjects:[Any] = JSON["weather"] as! [Any]
                    let weatherObject:[String:Any] = weatherObjects[0] as! [String:Any]
                    let descString:String = weatherObject["description"] as! String
                    
                    self.responseLabel.text = String(temperatureInt) + "°C, " + descString
                }
        }
    }

Please use your own API_KEY. Run loadData at viewDidLoad after buildView.

Step 7

Build and check.

Screen Shot 2017-02-08 at 15.45.19

If you have found a spelling error, please, notify us by selecting that text and pressing Ctrl+Enter.

Profile photo of Doszhan Kalibek

Doszhan Kalibek