Anton Kurniawan
Anton Kurniawan

Reputation: 11

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?

Upvotes: 1

Views: 11214

Answers (3)

Bandish Kumar
Bandish Kumar

Reputation: 2238

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.

Upvotes: 3

davidrynn
davidrynn

Reputation: 2376

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)

Upvotes: 1

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39978

/// 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
}

Upvotes: 1

Related Questions