0
votes

I am requesting some data by json , I am new to SWIFT for iOS so I don't get whats the problem in my code :

var URL="http://X.X.X.X.X/Api/UserManagement/getMobileUser";
    var UserId=uname.text;
    var pword=passwd.text;
    var PostData: NSString = "{\"data\":{},\"action\":\"System\",\"method\":\"getMobileUser\",\"username\":\" mpc01\",\"password\":\"mpc01\",\"type\":\"rpc\",\"tid\":\"144\"}"
    let request = NSMutableURLRequest(URL: NSURL(string: URL)!)
    request.HTTPMethod = "POST"

    let postString = PostData
    //var st:NSData = PostData.dataUsingEncoding(NSUTF8StringEncoding)!
   // request.HTTPBody = PostData.dataUsingEncoding(NSUTF8StringEncoding)

    request.HTTPBody = (postString as NSString).dataUsingEncoding(NSUTF8StringEncoding)


   //let data = (postString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

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

        println("response = \(response)")


        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString)")

    }
    task.resume()

THE response I get is :

response = { URL: http://X.X.X.X/Api/UserManagement/getMobileUser } { status code: 500, headers { "Cache-Control" = "no-cache"; "Content-Length" = 36; "Content-Type" = "application/json; charset=utf-8"; Date = "Sat, 03 Jan 2015 06:11:51 GMT"; Expires = "-1"; Pragma = "no-cache"; Server = "Microsoft-IIS/7.5"; "X-AspNet-Version" = "4.0.30319"; "X-Powered-By" = "ASP.NET"; } } responseString = Optional({"Message":"An error has occurred."})

1
I assume you have tested the service API before (using some other client) and it works. Then the HTTP request you create isn't correct. I propose you try to set at least another two HTTP headers: Content-Type to application/json and Content-Length to the length of the UTF-8 encoded data. - Codo
ok I am going to try it - Ziad Tareq

1 Answers

-1
votes

I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.

I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.

// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?

if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
    keys = NSDictionary(contentsOfFile: path)
}

if let dict = keys {
    // variablize our https path with API key, recipient and message text
    let mailgunAPIPath = dict["mailgunAPIPath"] as? String
    let emailRecipient = "[email protected]"
    let emailMessage = "Testing%20email%20sender%20variables"

    // Create a session and fill it with our request
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)

    // POST and report back with any errors and response codes
    request.HTTPMethod = "POST"
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let response = response {
            print("url = \(response.URL!)")
            print("response = \(response)")
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:

https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?

Hope this helps!