I am new in Swift Programming, I have consumed API for my project when the data is available it working perfect, if the data is not available app getting crashes in JSONSerialization
, the problem is in data?.count != 0
, because data.count
getting mostly 2 or some other number. If I try to change that line causing error. I don't know how to solve this, can anyone suggest a solution?
func getData() {
guard let URL = Foundation.URL(string:"http://xxxxx/xxx?xx=\(userid)") else {
return
}
let request = URLRequest(url: URL)
let task = URLSession.shared.dataTask(with: request, completionHandler: { data,response,error in
guard error == nil && data != nil else {
let alert = UIAlertController(title: "Check your Internet Connection", message: "", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
let when = DispatchTime.now() + 3
DispatchQueue.main.asyncAfter(deadline: when) {
// your code with delay
alert.dismiss(animated: true, completion: nil)
}
return
}
print(data?.count)
if data?.count != 0 {
let received = try! JSONSerialization.jsonObject(with: data!, options:.allowFragments) //Here getting thread error
print(received)
})
task.resume()
}
}
The problem is in this part.
if data?.count != 0
{
let received = try! JSONSerialization.jsonObject(with: data!, options:.allowFragments) //Here getting thread error
print(received)
}
So rewrite it using if let or guard.
guard let responseData = data else{
return
}
Now you can use responseData in JSONSerialization method. So the entire code snippet will look like
guard let responseData = data else{
return
}
let received = try! JSONSerialization.jsonObject(with: responseData, options:.allowFragments)
print(received)
In Swift if let and guard are used for unwrapping optionals. Using the "!" to unwrap an optional will cause a crash if the unwrapped value is nil. We use if let or guard to unwrap optionals safely. So as a thumb rule, you should only use "!" to unwrap optionals when you are 101% sure that it won't contain nil values.