Rakesh Mohan
Rakesh Mohan

Reputation: 609

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)

Upvotes: 0

Views: 1120

Answers (2)

Daniel Bruce
Daniel Bruce

Reputation: 11

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.

Upvotes: 1

Vizllx
Vizllx

Reputation: 9246

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]

Upvotes: 1

Related Questions