I am very new to swift and in my code I get JSON from a certain email, the JSON data is first put into an Array in swift, however if the array is null or there is no Json Data I get this error
Could not cast value of type 'NSNull' (0x1067a5748) to 'NSArray' (0x1067a4c58).
I been trying to fix this by reading other posts such as Check if optional array is empty but it is not working. The issue comes with this code below
session.dataTask(with:request, completionHandler: {(data, response, error) in
if error != nil {
print(error)
} else {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
if let musicJob = parsedData["music"] as! [AnyObject]? {
for S in musicjob {
if let genre = S["genre"] as? String {
self.genres.append(genre)
}
}
}
If the Json is null I get the error on this line right here
if let musicJob = parsedData["music"] as! [AnyObject]?
The musicJob counts the number of objects such as "30 values or 44 values " etc . If there is no Json then it returns nil and it crashes . Is there anyway that I can catch the value of nil or an empty array so that the app does not crash ? Again everything works as long as the musicJob array is not empty .