0

每當我試圖從火力獲取數據這種情況發生斯威夫特3意外地發現,同時展開可選的值爲零

enter image description here

這是我的代碼

覆蓋FUNC的tableView(_的tableView:UITableView的, numberOfRowsInSection部的: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() 

請人應該幫我出

感謝

+0

看起來像用來創建一個URL(imgUrl的)並不是指一個URL字符串。 –

回答

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() 
} 
+0

從崩潰一遍又一遍保存我的應用程序..非常感謝。 – alazmi95

相關問題