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

10,969

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.

Share:
10,969
user2511882
Author by

user2511882

Updated on June 04, 2022

Comments

  • user2511882
    user2511882 almost 2 years

    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.

  • user2511882
    user2511882 over 7 years
    ahhh i see...the URL is actually being built as an optional NSUrl variable..that does make sense. Where can we find the documentation for swift 2.0 API' s and the respective changes. I am referring this: developer.apple.com/reference/foundation/nsdata. But this doesn't show the changes for the init method from 2.0 to 3.0. Thanks!!