I am fetching the labels, text and image through API. When API has data , it shows without error. But when the API is nil, it throws error as:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'.
I need it to show null if API provides nil value but prevent from crash. Anyone out there please help to solve this issue in Swift 3. The code is given below:
import UIKit
import Alamofire
class Instructors: UIViewController {
@IBOutlet var fullName: UILabel!
@IBOutlet var post: UILabel!
@IBOutlet var descriptionName: UITextView!
@IBOutlet var instructorImage: UIImageView!
var dictDataContent:NSDictionary = NSDictionary()
var dictData:NSArray = NSArray()
var dictprofile:NSDictionary = NSDictionary()
override func viewDidLoad() {
super.viewDidLoad()
self.dictData = (dictDataContent.value(forKey: "instructors") as AnyObject) as! NSArray
self.dictprofile = (dictData.object(at: 0) as AnyObject) as! NSDictionary
let url:URL = URL(string: (self.dictprofile.value(forKey: "profile_image")) as! String)!
SDWebImageManager.shared().downloadImage(with: url, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
if self != nil {
self?.instructorImage.image = image
}
})
self.fullName.text = dictprofile.value(forKey: "full_name") as! String?
self.post.text = dictprofile.value(forKey: "designation") as! String?
self.descriptionName.text = dictprofile.value(forKey: "description") as! String?
}
}
So what I understand from your problem is your API might have data and sometimes no data. This is the behavior of
Optionalsin swift. So you need to haveoptionalvariables for storing your data.Changing your
NSDictionaryandNSArrayvariables tooptionalmight help. Try the code below: