简体   繁体   中英

Swift 4 : Cannot convert value of type 'Data' to expected argument type 'Data'

I'm using Xcode 9, Swift 4.

I'm trying to show an image in ImageView from URL using below code :

func getImageFromUrl(sourceUrl: String) -> UIImage {
        let url = URL(string: sourceUrl)
        let dict = NSDictionary(contentsOf: url!)
        let data = Data(dictionary: dict!)
        let image = UIImage(data: data!)
        return image
}

But I got an error in let image = UIImage(data: data!) .

The compiler says :

Cannot convert value of type 'Data' to expected argument type 'Data'

What am I doing wrong?

/// Returns nil if image data is not correct or some network error has happened
func getImageFromUrl(sourceUrl: String) -> UIImage? {
  if let url = URL(string: sourceUrl) {
    if let imageData = try? Data(contentsOf:url) {
      return UIImage(data: imageData)
    }
  }
  return nil
}

I had a similar problem with a network call. I had to explicitly type Foundation.Data to make sure there wasn't some weird namespace thing going on.

  func getMediaItems(completion: @escaping (Foundation.Data?, ResponseError?) -> ()) {
         let session = URLSession(configuration: .default)
         let url = self.makeURL()
         let task = session.dataTask(with: url, completionHandler: 
              { data, response, error in
                   if let imageData = data {
                        completion(data, nil) // had error here
             //etc, etc...

Pretty annoying. I'm not sure if I'm missing something or it's Swift 4 bug but it seemed to solve the issue. Without "Foundation" I got the same area at completion(data,nil) (ps. do not use this code as it's a sample and doesn't include error handling)

Please check any class name has Data (that you have created)in the project. Due to class name conflicts, swift may not be able to identify Foudation's Data class or your Project's Data class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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