如何 POST 在 swift ios 中向服务器发出整数请求?

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>

如何添加参数以将数字传递到服务器端。服务器端只有一个字段,我必须使用四个不同的文本字段传递 4 个整数。我怎样才能通过它?基本上我正在传递一个 OTP(四位一次性密码)

你检查过 属性 HTTPBody: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/#//apple_ref/occ/instp/NSMutableURLRequest/HTTPBody

不是我自己编译的,但会是这样的:

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

此代码的作用:

  • 连接您的文本值以构成一个字符串
  • 使用您的服务器期望的键创建字典(JSON 对象) 和连接字符串的值
  • 按照 HTTPBody 的预期将该字典转换为 NSData 属性
  • 在您的 NSMutableURLRequest
  • 上设置 HTTPBody 属性

也结账 https://github.com/AFNetworking/AFNetworking。使用 iOS.

处理 HTTP 请求变得超级简单

首先像这样制作OTP变量:-

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

然后形成参数:-

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