narner narner - 3 months ago 19
iOS Question

Could not cast value of type NSURL to NSString when String is specified (Swift)

I have a method that is intended to load a website inside a

UIWebView
:

func setImageForURL(urlString:String, completion:((image:UIImage?)->Void)?) {

self.completion = completion

guard let url = NSURL(string: urlString) else {
self.completion?(nil)
return
}

let request = NSURLRequest(URL: url)
webview = UIWebView(frame: self.bounds)
webview!.delegate = self
webview?.scalesPageToFit = true
webview!.loadRequest(request);

}


That method is called in the following
loadWebsite
method:

func loadWebsite(item:ShareItem) {
activitySpinner.startAnimating()
imageView.setImageForURL((item.asset as? String)!) { (image) in
self.showActionButton(true)
self.activitySpinner.stopAnimating()
self.actionButton.titleLabel?.text = "Open"
}
}


I'm getting a crash at the following line:

imageView.setImageForURL((item.asset as? String)!) { (image) in


of
Could not cast value of type 'NSURL' (0x10fd8ee98) to 'NSString' (0x10eccdb48).


I'm not understanding why, as I'm specifying the type to be a
String
, not an
NSString
. Anyone have some insight?

Answer

You can't convert NSURL to String like that way (From your error log, I assume that item.asset returns an NSURL not a String).

You need to use:

imageView.setImageForURL(item.asset.absoluteString) { (image) in
    self.showActionButton(true)
    self.activitySpinner.stopAnimating()
    self.actionButton.titleLabel?.text = "Open"
}