swift - NSURL、URL 和 NSData、数据

标签 swift url nsurl

我是 Swift 的新手。当我遇到 NSURLURL 以及 NSDataData 时,我正在从 Internet 上提取图像。我真的很困惑。我使用哪些?我使用了以下代码,但我必须如下所示转换类型。这样做的正确方法是什么?NSURLURL 以及 NSDataData 之间有什么区别?有人请帮忙。

if let theProfileImageUrl = tweet.user.profileImageURL{
    if let imageData = NSData(contentsOf: theProfileImageUrl as URL){
        profileImageView.image = UIImage(data: imageData as Data)
    }
}

最佳答案

随着 Swift 3 的发布,许多类名去掉了 NS 前缀。它们应该只用于 Objective-C 代码。如果你正在编写 Swift 3 代码,你应该只使用更新的类。在本例中,URLData

但是,URL 被桥接到 NSURL 并且 Data 被桥接到 NSData 所以你可以在它们之间转换需要时。

if let theProfileImageUrl = tweet.user.profileImageURL {
    do {
        let imageData = try Data(contentsOf: theProfileImageUrl as URL)
        profileImageView.image = UIImage(data: imageData)
    } catch {
        print("Unable to load data: \(error)")
    }
}

我不知道 tweet.user.profileImageURL 在哪里定义,但它似乎正在使用 NSURL 所以你需要将它转换为 URL 在你的代码中。

关于swift - NSURL、URL 和 NSData、数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40812416/

相关文章:

swift - 使用可重用的 TableView 进行排序

asp.net - 编码问题asp.net

java - HTTP URL 连接中出现错误

iphone - NSURL 似乎不想接受我的查询字符串

objective-c - iPhone SDK : Get a Forwarded URL

objective-c - 检查包含 "http://"URL 的字符串

SwiftUI - 表单选择器 - 如何防止导航回到选定的位置?

ios - Swift:如何在firebase中根据用户id读取特定用户数据?

javascript - 将 cooking 脚本注入(inject) WKWebView 后出现意外的 cookie 域

url - https 站点上的 Xhtml 命名空间?