Abdalla AlHaj Hasan Abdalla AlHaj Hasan - 2 months ago 90
JSON Question

Parsing JSON object to NSArray in Swift 3

After i convert my project to swift 3 i had run time error when i try to parsing JSON object to NSArray this my code

let receipt: Data! = try? Data(contentsOf: receiptURL)
if receipt == nil {//NSData(contentsOfURL: receiptURL, options: nil, error: nil)!
// validateReceipt(false)
return
}
let base64Data: String = receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) as String

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last?.path//
do{
let payload: Dictionary = ["receipt-data" : base64Data as String, "password": sharedSecret as String ]
let receiptData = try JSONSerialization.data(withJSONObject: payload, options: JSONSerialization.WritingOptions.prettyPrinted)

let request = NSMutableURLRequest(url: URL(string: serverURL)!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 10) // ur website

request.httpMethod = "POST"

request.httpBody = receiptData as! Data?
var response: URLResponse?
let resultData = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning: &response)

do{
let json = try JSONSerialization.jsonObject(with: resultData, options: .mutableLeaves) as? NSDictionary
let statusCode = (json?.object(forKey: "status") as! NSNumber).intValue

switch(statusCode){
case 21000, 21002, 21003, 21004, 21006:
return
// break
case 21005:
//Server is not available: Save recipt data and try again later
return
case 21007:
validateReceipt(true)
return

case 21008:
validateReceipt(false)
return

default:
break
}
//print("**********************************")
//print("json :: ", json )
//print("**********************************")
if let parseJSON = json {

let latest_receipt_info:NSArray = (parseJSON.object(forKey: "receipt") as AnyObject).object(forKey: "in_app") as! NSArray
//var ms = 0

//parse the json reponse and add the objects into array
for i in 0 ..< latest_receipt_info.count {
let object:[String: String] = latest_receipt_info.object(at: i) as! [String : String]
let strMS = object["expires_date_ms"]
let prodId = object["product_id"]
if(prodId == iAPItems["LifeTime"] || prodId == iAPItems["Remove_Ads"]){
latestObjectsForEachProduct[prodId!] = object
}else{
if let oldTransaction = latestObjectsForEachProduct[prodId!] {
let strOldMS = oldTransaction["expires_date_ms"]

print("oldTransaction :: ",prodId, " :: ",strOldMS)
if( strMS!.toDouble() > strOldMS!.toDouble() ){
//latestObject = object
latestObjectsForEachProduct[prodId!] = object
//ms = str!.toInt()
}
}else{
latestObjectsForEachProduct[prodId!] = object
}

}
}


the errors appears on this line

let latest_receipt_info:NSArray = (parseJSON.object(forKey: "receipt") as AnyObject).object(forKey: "in_app") as! NSArray


i dont know what should i do , if any one can help

Note that on swift 2 its work

Answer

Try this code

let json = try JSONSerialization.jsonObject(with: resultData, options: .mutableLeaves) as? NSDictionary let statusCode = (json?.object(forKey: "status") as! NSNumber).intValue

to replace this code

let json = try JSONSerialization.jsonObject(with: resultData, options: .mutableLeaves) as? [String:AnyObject]
            let statusCode = (json?["status"] as! NSNumber).intValue

let latest_receipt_info:NSArray = (parseJSON.object(forKey: "receipt") as AnyObject).object(forKey: "in_app") as! NSArray

To replace this code

let latest_receipt_info:NSArray = parseJSON["receipt"]!["in_app"] as! NSArray