i am working an app in which data is downloaded from server in JSON format. but if Image value is nill then app crashed. i also set a default picture but cursor did not enter in else statement. Kindly guide me how i do my task correctly. Here is my code
func downloadUsersData(){
let email = UserDefaults.standard.value(forKey: "userEmail")
var urlString = "http://nexusvision.net/zeroone/selectuserbasic.php"
urlString.append("?")
urlString.append("id=\(email!)")
print("This is URL : \(urlString)")
let url = URL(string: urlString)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil{
print(error?.localizedDescription)
}
let data = data
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: .utf8)
print("all Countary responseString = \(responseString)")
let responseData = responseString
do {
let jsonValue = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
print("This is Json : \(jsonValue.value(forKey: "product"))")
if let profile = jsonValue.value(forKey: "product") as? NSArray
{
for profileData in profile{
if let dict = profileData as? NSDictionary{
if let firstName = dict.value(forKey: "firstname"){
print("Name is : \(firstName)")
self.defaults.set(firstName, forKey: "firstName")
}
if let lastName = dict.value(forKey: "lastname"){
print("Last Name : \(lastName)")
self.defaults.set(lastName, forKey: "lastName")
}
if let imageData = dict.value(forKey: "picture") {
print("This is Image Json: \(imageData)")
let convertToImage = imageData
let decodedData : NSData = NSData(base64Encoded: convertToImage as! String, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
let decodedimage: UIImage = UIImage(data: decodedData as Data)!
print("Thats Decoded : \(decodedimage)")
self.profilePicImageShow.image = decodedimage
}
else{
self.profilePicImageShow.image = UIImage(named: "Empty")
}
}
}
}
}
catch let error as NSError {
print(error)
}
}.resume()
}