在展开Optional值时,Swift 3意外地发现了nil

时间:2017-06-25 00:10:50

标签: swift uitableview firebase-realtime-database firebase-authentication optional

每当我尝试从firebase获取数据时,就会发生这种情况

enter image description here

这是我的代码

覆盖func tableView(_ tableView:UITableView,numberOfRowsInSection section:Int) - > Int {         返回1     }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: self.postCell, for: indexPath) as! PostCell

    cell.postedImage.downloadImageUrl(from: setPost[indexPath.section].userPostImage)
    cell.postItemPriceLabel.text = setPost[indexPath.section].userPriceTag
    cell.selectionStyle = .none

    return cell
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: self.headerCell) as! HeaderCell
    cell.profileImage.downloadImageUrl(from: setPost[section].userphoto)
    cell.fullname.text = setPost[section].fullname
    cell.backgroundColor = UIColor.white
    return cell
}


 extension UIImageView {
   func downloadImageUrl(from imgUrl: String!){

    let url = URLRequest(url: URL(string: imgUrl)!)

    let session = URLSession.shared

    session.dataTask(with: url){
        (data, response, err) in

        if err != nil {
            print(err!)
            return
        }
        DispatchQueue.main.async {
            self.image = UIImage(data: data!)
        }
        }.resume()

请有人帮助我

由于

1 个答案:

答案 0 :(得分:3)

您需要确保用于创建URL对象的字符串(imgUrl)可用于创建URL对象,如果它没有,则您不应该继续。

可以使用if let声明:

if let url = URL(string: imgUrl) {

    let urlRequest = URLRequest(url: url)

    let session = URLSession.shared

    session.dataTask(with: urlRequest){
        (data, response, err) in

        if err != nil {
            print(err!)
            return
        }
        DispatchQueue.main.async {
            self.image = UIImage(data: data!)
        }
        }.resume()
}