AltBrian AltBrian -4 years ago 97
JSON Question

Trying to access an Array as part of JSON api in Swift 3.0

I am trying to access an Array as part of an JSON api. The api does is not part of a dictionary. The function I have is the following:

func downloadJsonwithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in

if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSArray {
print(jsonObj!)

if let albumsArray = jsonObj! as? NSArray {
for album in albumsArray{
if let albumDict = album as? NSDictionary {
if let name = albumDict.value(forKey: "title") {
self.nameArray.append(name as! String)
}
if let name = albumDict.value(forKey: "artist") {
self.albumArray.append(name as! String)
}
if let name = albumDict.value(forKey: "thumbnail_image") {
self.imgURLArray.append(name as! String)
}
if let name = albumDict.value(forKey: "image") {
self.albumURLArray.append(name as! String)
}
}

}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}

}).resume()

}


The error I get is

Non-optional expression of type 'NSArray' used in a check for optionals.


How can I fix this? Any help would be appreciated.

Answer Source

In the if-let binding if let jsonObj = try? JSONSerialization.jsonObject you cast jsonObj to an NSArray. Therefore, the if-let: if let albumsArray = jsonObj! as? NSArray { } is unnecessary. You can delete that line of code (and corresponding closing curly brace) and rename jsonObj to albumsArray.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download