leo0019 leo0019 - 2 months ago 41
Swift Question

ambiguous reference to member datatask swift Xcode 8

I just updated my Xcode and have been trying to learn more about it. This is my code for Collection View Cell. I'm trying to get data from URL but I've been annoyed with this error. I tried all the solutions in here but they have different function structure. Also other solutions didn't work.

import UIKit


class PersonCell: UICollectionViewCell {

@IBOutlet weak var personImage : UIImageView!



func ConfigureCell (imgURL : String)
{

}

func DownloadImage ( url : NSURL)
{

}

func GetDatafromURL (URL : NSURL , completion : @escaping (( _ data : NSData? , _ response : URLResponse? , _ error : NSError?) -> Void))
{
URLSession.shared.dataTask(with: URL) { (data , response , error) in
completion (data , response, error)
}.resume()
}
}


the code that worked in the tutorial video is something like this

func GetDatafromURL (URL : NSURL , completion : (( data : NSData? , response : NSURLResponse? , error : NSError?) -> Void))
{


NSURLSession.sharedSession.dataTaskWithURL( URL) { (data , response , error) in

completion(data : data , responce : response, error : error)


}.resume()

Answer

You can convert your NSURL to a URL using .absoluteURL

guard let url = URL.absoluteURL else { return }

URLSession.shared.dataTask(with: url) { (data, response, error) in
    //
}.resume()

But the more sensible approach is to do what @vadian has suggested.

UPDATE

Your completion block has the wrong types. You're using NSData instead of Data and NSError instead of Error. Here's an example of what it should look like below.

func getData(from url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void)
{
    URLSession.shared.dataTask(with: url) { data, response, error
        completion(data, response, error)
    }
}
Comments