Nikhil Sridhar Nikhil Sridhar - 7 days ago 6
Swift Question

NSURL, URL and 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)
}
}

Answer

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.

Comments