Simple API Call for Swift

For the past year and a half I’ve been immersed in learning Swift to make iOS applications. What I learned was that all sorts of applications use APIs. API stands for Application Programming Interface. An API are data sets of routines, protocols, information and tools for building applications. These data sets are saved in remote servers and are accessed through a URL (a link). To be able to use the data in these URLs you need a code to add to your application and then distribute this information throughout your app.

Whats great about APIs is the ease of getting data into an application. You don’t need to be constantly updating your app because this is done remotely whenever the API is updated, also making apps with less code in them. Less code means a lighter app for users to download on their phones.

I have to say it took me a very long time to get the hang of APIs. Whenever I looked online there was always a different way of calling them, and code setups I found where very long and complicated. But finally I got to make my own code. I found a way to make a “set” code that I can use for any kind of API that I need no matter where or what it is about.

OK, now that you know what an API is, we need to call this information from our app. First we need to create an ‘API Manager’.

Its just a function where  the only thing you need to add is your API URL. I made it simple to write and understand. You don’t need to change anything. Just copy+paste to your Swift view controller file. Note: I’m using Swift 3.0.

// API Manager
    
    func ApiManager() {
        
        // API url goes here
        let myUrl = "YOUR URL HERE"
        let dataURL = NSURL(string: myUrl)!
        
        // Prepares session
        let session = NSURLSession.sharedSession()
        
        // Calls url
        let task = session.dataTaskWithURL(dataURL) { (data, response, error) in
            
            // Checks for errors
            if let error = error {
                print(error)
            } else {
                
                // Checks for url response
                if let http = response as? NSHTTPURLResponse {
                    if http.statusCode == 200 {
                        
                        // Gets data
                        if let data = data {
                            
                            do {
                                // Parses Data
                                let userData = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
                                
                                // Gets API data
                                if let dictionary = userData as? [NSObject: AnyObject] {
                                    
                                    // Sends Api data to another function where JSON objects are called
                                    self.jsonData(dictionary)
                                }
                            }
                            catch let error as NSError {
                                print(error)
                            }
                        }
                    }
                }
            }
        }
        task.resume()
    }// end ApiManager

This is the easy part, calling you API, now we need to call the JSON objects from the API and make them show on your app. As you saw on the API Manager, there’s a “sendData” function that is been set. This is where the API sends its data. Now this part is very tricky because you can’t just simply call the data to a variable and present it. Each JSON has different set ups and each has a different way of been called. You can’t call an array of names the same way you would call a set of images.

Here is our new function to call our JSON objects.

 // JSON Data Function
    
    func jsonData(object: [NSObject: AnyObject]) {}

Now, inside this function we need to call our data. JSON objects have different types. They are Dictionaries, Arrays, Strings, Numbers, and Bools. But, because JSONs have different types of structures and values, it can be can be challenging to call objects correctly.

Later on I will make a post on how to work with JSON objects on swift and implementing it in your API code. That’s it. That’s the quick way to call a REST API from Swift. Hope this post has helped you in anyway on your Swift project.

Here is the GitHub link to this code: GitHub

 

‘Calling JSON Objects In Swift’ coming soon