如何通过POST方法登录或如何通过POST方法访问数据

时间:2016-08-17 05:26:10

标签: ios swift nsurlsession

我正在尝试使用多个参数从API获取数据并使用标头。 我尝试了很多,但没有成功,问题是我可以使用Alamofire做到这一点。但我想通过NSURLSession来做。

func apiCalling(){
        let myUrl = NSURL(string: "http://203.XXXXXXXXX.php");
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";// Compose a query string
        request.addValue("KAISAPAISA", forHTTPHeaderField: "APIXXXXX")
        let postString = "uname=demo&password=demo123";

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil
            {
                print("error=\(error)")
                return
            }

            // You can print out response object
            print("response = \(response)")

            // Print out response body
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")

            //Let's convert response sent from a server side script to a NSDictionary object:
            do {
                let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                if let parseJSON = myJSON {

                    // Now we can access value of First Name by its key
                    let firstNameValue = parseJSON["firstName"] as? String
                    print("firstNameValue: \(firstNameValue)")
                }
            } catch {
                print(error)
            }
        }
        task.resume()
}

0 个答案:

没有答案