iosswiftrequestbackend

Need to know common ways to communicate with backend in Swift


I'm new to the iOS world, but I have been working as a Software Developer and worked on many Web Applications with Laravel and PHP.

My Question is now if PHP is a good server-side language for Swift, then what is the common way to communicate with a Server in Swift.

I'm thinking to make a REST API call to a Laravel or PHP Application to get and store all Datas I need for my Project.

Thanks for your Tips


Solution

  • Here is your way for beginners (Swift, iOS developer)

    Using cocoa framework in Swift

    URLSession

    Initialize a URL object and a URLSessionDataTask from URLSession. Then run the task with resume().

    let url = URL(string: "http://www.stackoverflow.com")
    
    let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
        print(NSString(data: data!, encoding: String.Encoding.utf8))
    }
    
    task.resume()
    

    NSURLConnection

    First, initialize a URL and a URLRequest:

    let url = URL(string: "http://www.stackoverflow.com")
    let request = URLRequest(URL: url!)
    

    Then, you can load the request asynchronously with:

    NSURLConnection.sendAsynchronousRequest(request, queue: 
    NSOperationQueue.mainQueue()) {(response, data, error) in
        print(NSString(data: data!, encoding: NSUTF8StringEncoding))
    }
    

    Using Alamofire - Awesome framework

    https://github.com/Alamofire/Alamofire

    Making a Request

    import Alamofire
    
    Alamofire.request(.GET, "http://httpbin.org/get")
    

    Response Handling

    Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
             .response { request, response, data, error in
                  print(request)
                  print(response)
                  print(error)
              }