softdownfeathers softdownfeathers - 3 months ago 56
Swift Question

AlamoFire 4.0 + SwiftyJSON Unwrapping deeply nested JSON

I'm having issues parsing the JSON I'm getting back from the Wiki API.


platform :ios, ’10.0’


target 'GemFinder' do

pod 'Alamofire', '~> 4.0’
pod 'SwiftyJSON', :git => '', :branch => 'swift3'


Swift Code:

import UIKit
import Alamofire
import SwiftyJSON

class WikiAPI: NSObject {

func MineralRequest(minID: (String)) {

Alamofire.request("\(minID)&exintro=1&prop=pageimages%7Cextracts&format=json&pithumbsize=300", parameters: ["query": "pages"]).responseJSON { response in

if let values = response.result.value as? [String: AnyObject] {

let json = JSON(values)

// Returns null
print("otherJSON: \(json["query"]["pages"][0]["extract"])")

let JSONvalues = values as NSDictionary
print("JSONvalues: \(JSONvalues)")

// This is also working to retrieve everything from below "query"
let parse = JSONvalues.object(forKey: "query")
print("Parse: \(parse)")

let queryValues = values["query"]

// Returns nested "pages" object, but I need to go deeper.
print("queryvalues: \(queryValues?["pages"])")


I'm able to get a response, of course, and trying to go deeper, but I keep getting null values when trying to unwrap.

What am I missing? Here's an image of the tree. I'm trying to pull title, images and the extract out.

JSON response preview

Following this format, as seen here, still yields null values. Parameters didn't seem to benefit either: How do I access a nested JSON value using Alamofire and SwiftyJSON?


"pages" value is a dictionary so using [0] on it won't work, you need to use the key instead:

print("otherJSON: \(json["query"]["pages"]["1895477"]["extract"])")

Or if there are many items in pages and you want them all you can iterate through it like:

let pages = json["query"]["pages"]
for page in pages.values {