narner
narner

Reputation: 3221

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?

Upvotes: 1

Views: 2073

Answers (2)

Anupam Mishra
Anupam Mishra

Reputation: 3588

Change the line

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

to

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

if item.asset is a string then thy this -

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

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107121

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"
}

Upvotes: 2

Related Questions