NSURL、URL 和 NSData、数据 [英] NSURL, URL and NSData, Data
问题描述
我是 Swift 的新手.当我遇到 NSURL
和 URL
和 NSData
和 Data
时,我正在从互联网上提取图像.我真的很困惑.我使用哪些?我使用了以下代码,但我必须转换如下所示的类型.这样做的正确方法是什么,NSURL
和 URL
和 NSData
和 Data
之间有什么区别?有人请帮忙.
I'm new to Swift. I was pulling an image from the Internet when I came across NSURL
and URL
and NSData
and Data
. I'm really confused. Which ones do I use? I used the following code, but I had to convert the types as shown below. What is the proper way of doing this and what is the difference between NSURL
and URL
and NSData
and Data
? Somebody please help.
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 代码,则应仅使用更新的类.在这种情况下,URL
和 Data
.
Many class names dropped the NS
prefix with the release of Swift 3. They should only be used with Objective-C code. If you are writing Swift 3 code you should use only the updated classes. In this case, URL
and Data
.
然而,URL
被桥接到 NSURL
并且 Data
被桥接到 NSData
所以你可以在它们之间进行转换需要时.
However, URL
is bridged to NSURL
and Data
is bridged to NSData
so you can cast between them when needed.
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
code> 在您的代码中.
I don't know where tweet.user.profileImageURL
is defined but it appears to be using NSURL
so you need to cast it to URL
in your code.
这篇关于NSURL、URL 和 NSData、数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!