aamck
aamck

Reputation: 100

JSON unwrap not running

I have a JSON fetch happening and then I do stuff with the data. My JSONObject is created and then I go about working with the data. A sample can be seen here: https://openlibrary.org/api/books?bibkeys=1593243987&f&jscmd=data&format=json

My first block to extract the author name is working perfectly, however the second to extract the cover url as a string isn't even running and I have no idea why.

If I set a breakpoint at if let thumbs = bookDictionary["cover"] as? NSArray {it stops, but then when I 'step through' the code, it jumps to the end and moves on, not even running anything inside the block.

I would appreciate any help anyone can offer. I'm using Swift 2.0 / Xcode 7b6.

let requestURL = ("https://openlibrary.org/api/books?bibkeys=" + lookUpID + "&f&jscmd=data&format=json")
        let url = NSURL(string: requestURL)
        let req = NSURLRequest(URL: url!)
        let dataTask = session.dataTaskWithRequest(req) {
            (data, response, error) in
            do {
                let jsonObject = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary


    if let bookDictionary: AnyObject = jsonObject!["\(self.lookUpID)"] {

                // Retrieve the author name
                    var names = [String]()
                    if let authors = bookDictionary["authors"] as? NSArray {
                        for author in authors {
                            if let author = author as? NSDictionary,
                                let name = author["name"] as? String {
                                    names.append(name)
                            }
                        }
                    }

                // Retrieve cover url
                    var coverThumbURL: String = ""
                    if let thumbs = bookDictionary["cover"] as? NSArray {
                        // This code isn't running at all.
                        for thumb in thumbs {
                            if let thumb = thumb as? NSDictionary,
                                let thumbnail = thumb["medium"] as? String {
                                    coverThumbURL = thumbnail
                            }
                        }
                    }
                }

Upvotes: 1

Views: 325

Answers (1)

aamck
aamck

Reputation: 100

Thanks for the help. I did some looking around & fixed the casting.

var coverThumbURL: String = ""
if let thumbs = bookDictionary["cover"] as? NSDictionary {
let thumbnail = thumbs.valueForKey("medium") as? String
 coverThumbURL = thumbnail!
                }

Upvotes: 1

Related Questions