NSURL, URL and NSData, Data

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)")
        }
    }
}

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.

Tags:

Url

Swift