How do I make an HTTP request in Swift?

前端 未结 20 1096
不知归路
不知归路 2020-11-22 05:10

I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes

20条回答
  •  遇见更好的自我
    2020-11-22 05:47

    I am calling the json on login button click

    @IBAction func loginClicked(sender : AnyObject) {
    
        var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.
    
        var session = NSURLSession.sharedSession()
    
        request.HTTPMethod = "POST"
    
        var err: NSError?
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
    
        var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
            var err1: NSError?
            var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
    
            println("json2 :\(json2)")
    
            if(err) {
                println(err!.localizedDescription)
            }
            else {
                var success = json2["success"] as? Int
                println("Success: \(success)")
            }
        })
    
        task.resume()
    }
    

    Here, I have made a seperate dictionary for the parameters.

    var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
        return params
    }
    
    // You can add your own sets of parameter here.
    

提交回复
热议问题