Rakesh Mohan February 2016

How to POST integer request to server in swift ios?

    let theRequest = NSMutableURLRequest(URL: url!)
    theRequest.HTTPMethod = "POST"

    let parameters = ["otp":firstDigit.text!,"otp":secondDigit.text!,"otp":thirdDigit.text!,"otp":fourthDigit.text!] as Dictionary<String,String>

How to add parameters to pass numbers in to the server side. There is only one field in the server side and I have to pass 4 integers using four different text fields. How can I pass it? Basically I am passing an OTP(One time password with four digits)

Answers


Daniel Bruce February 2016

Have you checked out the property HTTPBody: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/#//apple_ref/occ/instp/NSMutableURLRequest/HTTPBody

Not compiled myself, but would be something like:

let otp = firstDigit.text + secondDigit.text+thirdDigit.text+fourthDigit.text
let json = [ "OTP" : otp ]
let jsonData = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.allZeros, error: nil)
theRequest.HTTPBody = jsonData

What this code does:

  • Concatenate your text values to make a string
  • Create a dictionary (JSON object) with the key your server expected and the value of the concatenated string
  • Convert that dictionary to NSData as expected by the HTTPBody property
  • Set the HTTPBody property on your NSMutableURLRequest

Also checkout out https://github.com/AFNetworking/AFNetworking. It makes it super simple to handle HTTP requests using iOS.


Vizllx February 2016

First make the OTP variable like this:-

 var otpText:String= firstDigit.text + secondDigit.text +thirdDigit.text+fourthDigit.text

then form the parameter:-

let parameters : NSDictionary =["otp":otpText]

Post Status

Asked in February 2016
Viewed 2,967 times
Voted 10
Answered 2 times

Search




Leave an answer