Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURL, URL and NSData, Data

Tags:

url

swift

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)
    }
}
like image 678
Nikhil Sridhar Avatar asked Nov 25 '16 21:11

Nikhil Sridhar


2 Answers

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.

like image 109
rmaddy Avatar answered Sep 19 '22 19:09

rmaddy


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)")
        }
    }
}
like image 21
Bary Levy Avatar answered Sep 17 '22 19:09

Bary Levy