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)
}
}
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
.
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)")
}
}
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.
SWIFT 5.0 + fetch on background
private func fetchImage(_ photoURL: URL?) {
guard let imageURL = photoURL else { return }
DispatchQueue.global(qos: .userInitiated).async {
do{
let imageData: Data = try Data(contentsOf: imageURL)
DispatchQueue.main.async {
let image = UIImage(data: imageData)
self.userImageView.image = image
self.userImageView.sizeToFit()
}
}catch{
print("Unable to load data: \(error)")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With