-1

I am converting image string in to URL, but when i am converting it I am getting nill vaalue in URL. This is my code :

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
            }
Ruchi
  • 13
  • 1
  • 5

1 Answers1

0

The correct way to convert a string to a URL is

let url = URL(string: URLString)

Do not use NSURL as you did above, it should still work but it is preferred to use URL as it is a struct and is thread safer to use.

However, this still may return nil if the URLString cannot form a valid URL

Returns nil if a URL cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).

So you could use something such as

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")
}
Ryan Heitner
  • 13,119
  • 6
  • 77
  • 119
  • You are correct, not deprecated but it is encouraged to use newer non-NS i.e. Structs rather than Class where possible. – Ryan Heitner Dec 31 '17 at 19:11