HTTP GET Request Example in Swift

In this short blog post I am going to share with you how to create and send HTTP GET Request with one request parameter. I will also show you how to add Basic Authorization header or how to add custom Token Auth header value to your HTTP request.

For this particular example I have created a Single View Application with one ViewController only. My UI is also very basic. I have one UITextField which will accept userName value and a button which user needs to tap to send HTTP Request.

HTTP GET Example in Swift

 

When user taps on Send button we will trigger following function:

  

@IBAction func sendButtonTapped(sender: AnyObject) { } 

The above function is not ready to be used with our project as is of course and we need to add some business login to it. And the first step for us will be to get the value from UITextFiled and check if this value is not empty. To do that we will first create an outlet for UITextField. Place the IBOutlet right under the class declaration like so:

  

class ViewController: UIViewController {
@IBOutlet weak var userNameTextField: UITextField!
...

Now lets modify our function “sendButtonTapped” and make it look like so:

  

@IBAction func sendButtonTapped(sender: AnyObject) {        

// Read textValue user inputs into userNameValue variable
let userNameValue = userNameTextField.text
        
// Check of userNameValue is not empty
if isStringEmpty(userNameValue!) == true
{
     return
}

// If we reach here then we can send http request

}

The isStringEmpty is custom function which we need to implement. Let’s create a new function which will check the value provided for empty string and will return true if it is so.

  

func isStringEmpty(var stringValue:String) -> Bool
    {
        var returnValue = false
    
        if stringValue.isEmpty  == true
        {
            returnValue = true
            return returnValue
        }
        
       // Make sure user did not submit number of empty spaces
        stringValue = stringValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        
        if(stringValue.isEmpty == true)
        {
            returnValue = true
            return returnValue
 
        }
    
          return returnValue
        
    }

Now we can continue with our sendButtonTapped function and add code that sends HTTP GET Request. I will write below a compete implementation of the function and in the comments to my code explain its business logic line by line.

  

@IBAction func sendButtonTapped(sender: AnyObject) {
        let userNameValue = userNameTextField.text
        
        if isStringEmpty(userNameValue!) == true
        {
            return
        }
        
        // Send HTTP GET Request 
  
        // Define server side script URL 
        let scriptUrl = "http://swiftdeveloperblog.com/my-http-get-example-script/"

        // Add one parameter
        let urlWithParams = scriptUrl + "?userName=\(userNameValue!)"

        // Create NSURL Ibject
        let myUrl = NSURL(string: urlWithParams);
        
        // Creaste URL Request
        let request = NSMutableURLRequest(URL:myUrl!);
      
        // Set request HTTP method to GET. It could be POST as well
        request.HTTPMethod = "GET"
        
        // If needed you could add Authorization header value
        // Add Basic Authorization
        /*
        let username = "myUserName"
        let password = "myPassword"
        let loginString = NSString(format: "%@:%@", username, password)
        let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
        let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
        request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
        */
        
        // Or it could be a single Authorization Token value
        //request.addValue("Token token=884288bae150b9f2f68d8dc3a932071d", forHTTPHeaderField: "Authorization")
        
        // Excute HTTP Request
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            
            // Check for error
            if error != nil
            {
                print("error=\(error)")
                return
            }
            
            // Print out response string
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
            
            
            // Convert server json response to NSDictionary
            do {
                if let convertedJsonIntoDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                    
                    // Print out dictionary
                    print(convertedJsonIntoDict)
                    
                    // Get value by key
                    let firstNameValue = convertedJsonIntoDict["userName"] as? String
                    print(firstNameValue!)
                    
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
            
        }
        
        task.resume()

        
    }

And this it! Pretty simple. Using this example you should be able to send HTTP GET requests to your web service end points. If you would like to see how this project works and be able to debug it here is URL to download it from GitHub. You can also download ZIP archive of this project.

Add Basic Authorization HTTP Request Header

Please note that in the function above some of the code is commented out. The commented out code is for adding HTTP Request Header with Authorization value. The server side endpoint that I use does not require Auth token or Basic Authorization to be used. However if your web service endpoint requires Basic Authorization to be used, you can add this code:

  

        let username = "myUserName"
        let password = "myPassword"
        let loginString = NSString(format: "%@:%@", username, password)
        let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
        let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
        request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")

Add Auth Token to HTTP Request Header

or if your RESTful web service requires Auth Token to be provided with HTTP Request Header you can uncomment the following code and add Authorization header with the Auth token value:

  

request.addValue("Token token=884288bae150b9f2f68d8dc3a932071d", forHTTPHeaderField: "Authorization")

 

I hope this was helpful!

Happy learning :)! ah, and yes, by the way, below are three videos courses that will help you in your learning process and will provide you with a lot of value if you are learning app development for iOS platform.


Learn iOS Development with these Video Courses


How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon


iOS 10 & Swift 3: From Beginner to Paid Professional
icon


The Complete iOS 10 Developer Course - Build 21 Apps
icon


Swift 3 - Learn to Code with Apple's New Language
icon icon


Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus: https://plus.google.com/+SergeyKargopolov/posts
Facebook: Swift Developer Blog on Facebook



  • AndrewLL94

    Hi! I found your code really complete and helpful and I tried with different web services before trying with the one I need and I found no problem, but when I did with the one I need for my code there´s a format error with the response I get, instead of “” I receive “>”, any idea of how I can solve this situation? I was trying to make an own parse method but it didn´t work at all. Thanks in advance.

    • Andrew, did you paste some kind of special character which did not appear properly in your comment? I do not see the difference between “>” and “>”…

      • AndrewLL94

        wow, I didn´t know that would happen, well, I receive “& l t ;” and “& g t ;” without the spaces between the characters, I’m a little bit confused with it.

        • It is difficult to say why it is returning these characters. It could be an error in your server side script for example…

  • adam

    can you do a tutorial on a get request for the login system you have created. i am new to swift so i dont understand much. thanks

  • adam

    can you do a tutorial on a get request for the login system you have created. i am new to swift so i dont understand much. thanks

  • Nikolay Kudryavtsev

    Hi! I don’t code on Swift and was just interested in this post. Doesn’t isStringEmpty method need to be a bit refactored?

  • Nikolay Kudryavtsev

    Hi! I don’t code on Swift and was just interested in this post. Doesn’t isStringEmpty method need to be a bit refactored?

  • Ange Olivier Batienan

    Can you please update for Swift 3 ?

    • @angeolivierbatienan:disqus you can find this and many more Swift 3 code examples on swiftdeveloperblog.com/code-examples page. Please have a look.