Post Method with NSDictionary Values using Swift

I'm completely new toSwift. I need to hit a Post Method webservice with NSDictionary parameters & get the JSON response. I tried usingAlamofire & also NSMutableUrlRequest. Nothing seems to workout for me. I either get 'JSON text did not start with array or object and option to allow fragments not set' error or 'Undefined Variable' response from the server. The same service works fine when I try using Objective-C. As I said earlier, I am completely new toSwift & need your assistance.

My base url: http://myofficeit.in/bizfeed/webservices/client.php

Parameter I wanna Pass:

Parameter =

{
    UserName = xyz;
    deviceModel = iPhone;
    deviceToken = "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e";
    emailid = "[email protected]";
    location = Asia;
    userMobileNo = 1234567890;
};
functionName = register;

The code I used for hitting the service is: http://pastebin.com/aaT4uhS7

Thanks

Upvotes: 0

Views: 1045

Answers (2)

CouchDeveloper
CouchDeveloper

Reputation: 19116

As broad as your question is, the broad will be my answer:

The first thing to do, is to get a clear idea about the web service API, which also requires a basic knowledge of the HTTP protocol. So, what you need to understand is, what the server expects in HTTP terminology.

You eventually will find out, how the server will expect its "parameters". Note, that there is no term like "parameters" in the HTTP protocol. So, you need to map them into something the HTTP protocol provides.

Most likely, in a POST request, "parameters" are transferred as the body of the HTTP message, as a content-type which is application/x-www-form-urlencoded, multipart/form-data or application/json.

According to the needs of the server, and with your basic knowledge of HTTP and NSURLSession, NSURLComponents etc., you compose the URL and the body of the request, set Content-Type header and possibly other headers and you are ready to go.

How this eventually looks like is given in the answer of @AnbyKarthik, which used Alamofire, and a command that composes a POST request whose parameters are send in the body whose content-type is x-www-form-urlencoded.

Upvotes: 0

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

you can use like

let param: [String:AnyObject] = [
    "UserName": iPhone,
    "deviceToken": "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e",
    "emailid": "[email protected]",
    "location": Asia,
    "userMobileNo": 1234567890
]

Alamofire.request(.POST, "http://myofficeit.in/bizfeed/webservices/client.php/register", parameters: param).responseJSON { (req, res, json, error) in
    print(req)
    print(res)
    print(json)
    print(error)
}

for sample request in Alamofire

Upvotes: 1

Related Questions