I am using this code to read data from NSDictionary:
let itemsArray: NSArray = response.objectForKey("items") as! NSArray;
let nextPageToken: String = response.objectForKey("nextPageToken") as! String
var videoIdArray: [String] = []
for (item) in itemsArray {
let videoId: String? = item.valueForKey("id")!.valueForKey("videoId") as? String
videoIdArray.append(videoId!)
}
But when i items or nextPageToken are not exist i get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Any idea why? how i can fix it?
There are two issues in your code:
valueForKey: instead of objectForKey: for retrieving data from a dictionary. Use objectForKey: instead of valueForKey: for getting data from a dictionary.You can fix the crash by:
let itemsArray: NSArray? = response.objectForKey("items") as? NSArray;
let nextPageToken: String? = response.objectForKey("nextPageToken") as? String
var videoIdArray: [String] = []
if let itemsArray = itemsArray
{
for (item) in itemsArray
{
let videoId: String? = item.objectForKey("id")?.objectForKey("videoId") as? String
if (videoId != nil)
{
videoIdArray.append(videoId!)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With