我想在我的自定义网站上使用捐款。
我应该连接一个URL,并传递名为“sku”&的2值。 “DEVICE_ID”。
因为网络给了我一个名为“status”的值和一个价值如此“726287618769179”的付费代码。
如果“status”等于“READY_TOPAY”,我应该转到下一个url + paycode和 然后用户可以填写卡号和密码等。
我使用此代码连接并与网络通信:
let DID = UIDevice.currentDevice().identifierForVendor!.UUIDString
print("Device ID is : \(DID)")
let url = NSURL (string: "https://qqqq.com/rest-api/pay-request");
let requestObj = NSURLRequest(URL: url!);
webView.loadRequest(requestObj);
let request = NSMutableURLRequest(URL: NSURL(string: "https://qqqq.com/rest-api/pay-request")!)
request.HTTPMethod = "POST"
let postString = "mypayid&device_id=\(DID)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
if (responseString?.UTF8String.) {
print("YESsssss")
}
}
task.resume()
问题是我得到了第一个JSON答案:
responseString = Optional({"error":false,"status":"READY_TO_PAY","pay_code":"4443697552108","prd_status":1})
我不知道该怎么做!
如何判断“状态”是否等于“READY_TO_PAY”转到下一个网址+付费代码?
答案 0 :(得分:2)
不是使用NSString(data: data!, encoding: NSUTF8StringEncoding)
从JSON数据创建String,而是将JSON数据解码为字典,并通过安全下标访问其内容:
if let json = try? NSJSONSerialization.JSONObjectWithData(data!, options: []) {
if let content = json as? [String:AnyObject],
status = content["status"] as? String,
payCode = content["pay_code"] as? String {
print(status)
print(payCode)
}
}
现在,您可以轻松地将status
与“READY_TO_PAY”进行比较并采取必要的措施。