ios - 指定字符串时无法将 NSURL 类型的值转换为 NSString (Swift)

标签 ios swift string nsstring nsurl

我有一个方法旨在将网站加载到 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);

}

该方法在以下 loadWebsite 方法中调用:

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

我在以下行遇到崩溃:

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

无法将类型“NSURL”(0x10fd8ee98)的值转换为“NSString”(0x10eccdb48)。

我不明白为什么,因为我将类型指定为 String,而不是 NSString。任何人都有一些见解?

最佳答案

你不能像那样将 NSURL 转换为字符串(从你的错误日志中,我假设 item.asset 返回一个 NSURL 而不是 String)

你需要使用:

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

关于ios - 指定字符串时无法将 NSURL 类型的值转换为 NSString (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894515/

相关文章:

java - 我可以禁用 JVM 字符串池吗?

c# - 有没有更好的方法来编写 new List<string> {"a", "b"}.Contains(str)?

java - 使用 Java 读取和处理带有自定义列和行分隔符的文本文件

iphone - iOS : Getting FriendList along with respective name, 使用 FBGraph API 的 id 和图片

ios - AdMob 插页式广告 : No ad to load (works on one project but not on another)

ios - 代码 8 : linker command failed with exit code 1 (use -v to see invocation)

ios - 模仿 UIBarButtonItem 的按钮

ios - 如何将 ImageView 转换为自定义形状(swift3)

iphone - core-plot,无法绘制两个图

ios - 添加一个简单的 UIView 作为 UICollectionView 的标题