Ahmadreza
Ahmadreza

Reputation: 7212

How to use this JSON response?

I want to use donation payment with my custom website.

There is a URL I should connect to and pass 2 value with the name "sku" & "device_id".

As asnwer the web gives me a value with name of "status" and a paycode with a value like this "726287618769179".

If "status" equals "READY_TOPAY" I should go to next url+paycode and then user can fill card number and password and etc.

I use this code to connect and communicate with the web:

  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()

The problem is I get the first JSON answer like this:

responseString = Optional({"error":false,"status":"READY_TO_PAY","pay_code":"4443697552108","prd_status":1})

I don't know what to do with this!

How should I tell if "status" equals "READY_TO_PAY" go to next url+paycode?

Upvotes: 1

Views: 95

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

Instead of making a String from your JSON data with NSString(data: data!, encoding: NSUTF8StringEncoding), decode the JSON data to a dictionary, and access its contents by safely subscripting:

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)
    }
}

Now you can easily compare status with "READY_TO_PAY" and take necessary actions.

Upvotes: 2

Related Questions