Question: NSData init?(contentsOf url: URL) migration from Swift 2 to Swift 3

Question

NSData init?(contentsOf url: URL) migration from Swift 2 to Swift 3

Answers 1
Added at 2016-12-22 21:12
Tags
Question

New to iOS/Swift. I am trying to migrate a project (that simply fetches contents from a URL via the NSData init() method) from Swift 2 to Swift 3. The original code looks like this:

let loadedImageData = NSData(contentsOfURL: imageURL)
            dispatch_async(dispatch_get_main_queue()) {
                if imageURL == user.profileImageURL {
                    if let imageData = loadedImageData  {
                        self.profileImageView?.image = UIImage(data: imageData)
                    }
                }
            }

Swift 3 migration:

 let loadedImageData = NSData(contentsOf: imageURL as URL)
            DispatchQueue.main.async {
                if imageURL == user.profileImageURL {
                    if let imageData = loadedImageData  {
                        self.profileImageView?.image = UIImage(data: imageData as Data)
                    }
                }
            }

I am not sure as to why we need to cast the NSData return value as a URL and then cast that return again to a Data type while loading the image within Swift 3. We are assigning the raw data to a variable loadedImageData in both the version. Why the casting then? It seems that the UIImage init() method needs a data object within Swift 3. However for Swift 2 there is no casting for the same. Why is that?

Thanks for the help.

Answers to

NSData init?(contentsOf url: URL) migration from Swift 2 to Swift 3

nr: #1 dodano: 2016-12-22 21:12

The migration consists of some changes in those methods' signatures, namely, the types they accept.

In Swift 2, NSData(contentsOfURL:) and UIImage(data:) take NSURL and NSData, respectively.

Currently, they have been changed to NSData(contentsOf:) and UIImage(data:) that accept, respectively, URL (struct) and Data (instead of NSData); as a result, the casts are necessary unless you constructed your URL from type URL instead of NSURL.

You could use, instead, Data(contentsOf: URL) to avoid the cast as well.

Source Show
◀ Wstecz