我通过API获取标签,文本和图像。当API有数据时,它会显示没有错误。但是当API为nil时,它会抛出错误:
由于未捕获的异常'NSRangeException'而终止应用程序,原因: '*** - [__ NSArray0 objectAtIndex:]:索引0超出了空的边界 NSArray的”。
如果API提供nil值但是防止崩溃,我需要它显示null。任何人都可以帮助解决Swift 3中的这个问题。代码如下:
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?
}
}
答案 0 :(得分:0)
因此,我从您的问题中了解到 您的API可能包含数据,有时没有数据 。这是Optionals
在swift中的行为。因此,您需要使用optional
变量来存储数据。
将NSDictionary
和NSArray
变量更改为optional
可能会有所帮助。请尝试以下代码:
class Instructors: UIViewController {
@IBOutlet var fullName: UILabel!
@IBOutlet var post: UILabel!
@IBOutlet var descriptionName: UITextView!
@IBOutlet var instructorImage: UIImageView!
var dictDataContent:NSDictionary?
var dictData:NSArray?
var dictprofile:NSDictionary?
override func viewDidLoad() {
super.viewDidLoad()
dictData = dictDataContent?.value(forKey: "instructors") as? NSArray
if let count = dictData?.count, count > 0 {
dictprofile = dictData?.object(at: 0) as? NSDictionary
}
if let urlString = dictprofile?.value(forKey: "profile_image") as? String {
if let url = URL(string: urlString) {
SDWebImageManager.shared().downloadImage(with: url, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
if self != nil {
self?.instructorImage.image = image
}
})
}
}
fullName.text = dictprofile?.value(forKey: "full_name") as? String
post.text = dictprofile?.value(forKey: "designation") as? String
descriptionName.text = dictprofile?.value(forKey: "description") as? String
}
}