1

I have a project in swift 3 and want to make a GET request. However, Alamofire is not yet updated to swift 3. When will Alamofire support swift 3 and how do you hard code a GET request with parameters in swift 3?

Simon Narang
  • 69
  • 1
  • 1
  • 6
  • @EricAya In my case, I don't want use Alamofire with Swift 3, because it's only support iOS 9+. – AnLT Oct 19 '16 at 08:51
  • Please refer third-party API questions ("When will Alamofire support Swift 3") to their respective GIT pages, not SO. – Alec O Nov 05 '17 at 20:20

3 Answers3

27

Swift 3.0

    var request = URLRequest(url: URL(string: "http://example.com")!)
    request.httpMethod = "POST"
    let session = URLSession.shared

    session.dataTask(with: request) {data, response, err in
        print("Entered the completionHandler")
    }.resume()
karma
  • 1,282
  • 18
  • 23
  • 2
    Thanks! How can I add params? – AnLT Oct 19 '16 at 08:45
  • same question.. How to add parameters? – parilogic Nov 07 '16 at 09:56
  • 1
    var err: NSError? request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") – Haseeb Nov 16 '16 at 10:14
  • 1
    Check this link on how to use param in the request: https://stackoverflow.com/questions/27723912/swift-get-request-with-parameters – karma Sep 01 '19 at 10:07
18

Swift 3

let url = URL(string: "http://example.com/get")
    URLSession.shared.dataTask(with: url!, completionHandler: {
        (data, response, error) in
        if(error != nil){
            print("error")
        }else{
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]


                OperationQueue.main.addOperation({ 
                    self.tableView.reloadData()
                })

            }catch let error as NSError{
                print(error)
            }
        }
    }).resume()

REST API In Swift 3 And Xcode 8 Using URLSession And JSONSerialization

Sơn nguyễn
  • 189
  • 1
  • 5
2

Alamofire will be updated to Swift 3...whenever they get around to it, I guess. GET requests without Alamofire are pretty easy:

    let req = NSMutableURLRequest(URL: NSURL(string:"your-endpoint-url?parameter=value")!)
    req.HTTPMethod = "GET"
    req.HTTPBody = "key=\"value\"".dataUsingEncoding(NSUTF8StringEncoding) //This isn't for GET requests, but for POST requests so you would need to change `HTTPMethod` property
    NSURLSession.sharedSession().dataTaskWithRequest(req) { data, response, error in
        if error != nil {
            //Your HTTP request failed.
            print(error.localizedDescription)
        } else {
            //Your HTTP request succeeded
            print(String(data: data!, encoding: NSUTF8StringEncoding))
        }
    }.resume()
brimstone
  • 3,370
  • 3
  • 28
  • 49