【问题标题】:how do i convert image string into url using swift?When I am converting string in to URL, i am getting nill value in URL如何使用 swift 将图像字符串转换为 url?当我将字符串转换为 URL 时,我在 URL 中得到 nill 值
【发布时间】:2018-06-08 16:32:11
【问题描述】:

我正在将图像字符串转换为 URL,但是当我转换它时,我在 URL 中得到了零值。 这是我的代码:

func tableView(_ tbldata: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tbldata.dequeueReusableCell(withIdentifier: "ServiceCheckCell", for: indexPath) as! ServiceCheckTableViewCell
               cell.selectionStyle = .none

    //save image in imagestr
               let imagestr = (self.data[indexPath.row] as AnyObject).value(forKey:"service_image") as? String

                let URLString = imagestr
    //convert URLSting into URL
                let URL = NSURL(string: URLString!)
                cell.service_image.hnk_setImageFromURL(URL! as URL )

                return cell
            }

【问题讨论】:

标签: swift


【解决方案1】:

将字符串转换为 URL 的正确方法是

let url = URL(string: URLString)

不要像上面那样使用 NSURL,它应该仍然可以工作,但最好使用 URL,因为它是一个结构并且使用线程更安全。

但是,如果 URLString 不能形成有效的 URL,这仍然可能返回 nil

如果 URL 不能用字符串组成(例如,如果 该字符串包含 URL 中的非法字符,或者是 空字符串)。

所以你可以使用诸如

之类的东西
if let url = URL(string: URLString) {
  cell.service_image.hnk_setImageFromURL(URL! as URL ) 
} else {
   // fix your string perhaps it needs percent encoding
  fatalError("Check your source data")
}

【讨论】:

  • 您是正确的,没有被弃用,但鼓励使用较新的非 NS,即尽可能使用结构而不是类。
猜你喜欢
  • 1970-01-01
  • 2018-03-08
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 2016-04-26
相关资源
最近更新 更多