mesopotamia
mesopotamia

Reputation: 393

How to HTTP Request in Swift 2.0 (Xcode 7.2)

I am trying make a http request to a web service. It returns JSON data. And I am also want to parse this data. I am new at swift I try many ways but get nothing. Here is my service address:

http://xxx.xxx.xxx.xxx/mobileservice/login/firmcode/mailaddress/password/ip

I am try to call service on this uri template. How can I do can anybody help ?

Upvotes: 2

Views: 437

Answers (3)

Marco Castano
Marco Castano

Reputation: 150

A nice way for sending http request is alamofire. Although you can also send http without external library. Look at this code

func sendHttpRequests(data : Dictionary<String, AnyObject>)
{
 let url = NSURL ( string : "http://xxx.xxx.xxx.xxx/mobileservice/login/firmcode/mailaddress/password/ip")!
    let request:NSMutableURLRequest = NSMutableURLRequest(URL : url)

    //Data that you want to send
    let payload = "{r: typeRequest, e: object, p: anotherObject}"
    //js_object is the key that is configured in your server
    let bodyData = "{js_object:\(payload)}"
    //Setting httpMethod
    request.HTTPMethod = "POST"

    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);


    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
        {
            (response, data, error) in

            //If response code is 200 you send the request successfully         
            if let httpResponse = response as? NSHTTPURLResponse {
                let responseCode = httpResponse.statusCode
                print(responseCode)
            }
            do
            {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)


                print("Json sent by server\(json)")

                if let value = json["myKey"] as? String
                {

                    print(value)
                }
            }
            catch
            {
                print(error)
            }


    }
}

Pay attention if json sent by server is a valid json Here is an example in php

<?php
$arr = array('myKey' => "ciao", 'b' => 2, 'c' => 3, 'd' => 4);

echo json_encode($arr);
?>

Upvotes: 2

Duncan C
Duncan C

Reputation: 131491

You can use a third party framework like Alamofire, as Benobab says. It's also quite easy to use NSURLSession and an NSURLSessionTask to do this. NSURLSession has a method sharedSession that gives you a session that's already configured. Then you want to create an NSURLSessionDataTask. Take a look at the Xcode docs for more info.

Upvotes: 0

Benobab
Benobab

Reputation: 428

https://github.com/Alamofire/Alamofire

+

https://github.com/SwiftyJSON/SwiftyJSON

EX :

Alamofire.request(.GET, "http://xxx.xxx.xxx.xxx/mobileservice/login/firmcode/mailaddress/password/ip", parameters: nil)
     .responseJSON { response in
         print(response.request)  // original URL request
         print(response.response) // URL response
         print(response.data)     // server data
         print(response.result)   // result of response serialization

         if let res= response.result.value {
             print("JSON: \(JSON)")
             //Here you can parse the json with swiftyJSON
             let json = JSON(res)
             let name = json["name"].string
         }
     }

Upvotes: 1

Related Questions