简体   繁体   English

NSData init?(contentsOf url: URL) 从 Swift 2 迁移到 Swift 3

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

New to iOS/Swift. 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:我正在尝试将一个项目(它只是通过NSData init()方法从 URL 中获取内容)从 Swift 2 迁移到 Swift 3。原始代码如下所示:

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: Swift 3 迁移:

 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.我不确定为什么我们需要将NSData返回值转换为URL ,然后在 Swift 3 中加载图像时再次将返回值转换为Data类型。我们将原始数据分配给两个版本中的变量loadedImageData . 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.似乎UIImage init()方法需要 Swift 3 中的数据对象。但是对于 Swift 2 没有相同的转换。 Why is that?这是为什么?

Thanks for the help.谢谢您的帮助。

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.在 Swift 2 中, NSData(contentsOfURL:)UIImage(data:)分别采用NSURLNSData

Currently, they have been changed to NSData(contentsOf:) and UIImage(data:) that accept, respectively, URL ( struct ) and Data (instead of NSData );目前,它们已更改为分别接受URL ( struct ) 和Data (而不是NSData )的NSData(contentsOf:)UIImage(data:) as a result, the casts are necessary unless you constructed your URL from type URL instead of NSURL .因此,除非您从类型URL而不是NSURL构建 URL,否则强制转换是必要的。

You could use, instead, Data(contentsOf: URL) to avoid the cast as well.您也可以使用Data(contentsOf: URL)来避免强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM