对成员'datatask(with:completionhandler :)'的暧昧参考

时间:2017-01-21 14:36:54

标签: ios swift request swift3

我的代码出了问题。我试图通过StringBuilder下载图片,然后将其设置为UIImage我似乎遇到了问题,我希望有人能看到我做错了。

setUI:

uiMovieTitle.text = self.movies![movieIndex].title

    var finalImageUrl = StringBuilder()

    let session = URLSession(configuration: .default)

    let downloadPicTask = session.dataTask(with: finalImageUrl) { (data, response, error) in
        // The download has finished.
        if let e = error {
            print("Error downloading cat picture: \(e)")
        } else {
            // No errors found.
            // It would be weird if we didn't have a response, so check for that too.
            if let res = response as? HTTPURLResponse {
                print("Downloaded cat picture with response code \(res.statusCode)")
                if let imageData = data {
                    // Finally convert that Data into an image and do what you wish with it.
                    let image = UIImage(data: imageData)
                    // Do something with your image.
                    uiMoviePoster.image = image
                } else {
                    print("Couldn't get image: Image is nil")
                }
            } else {
                print("Couldn't get response code for some reason")
            }
        }
    }

   downloadPicTask.resume()

}

的StringBuilder

func StringBuilder() -> (String){
    let posterBase = "http://image.tmdb.org/t/p/w1920"
    let linkEnd = self.movies?[movieIndex].posterPath

    var finalLink = ""

    finalLink = posterBase + linkEnd!

    return finalLink

}

我还有另一个下载,它可以获取电影列表(JSON),对于StringBuilder至关重要。

1 个答案:

答案 0 :(得分:0)

编译器抱怨,因为函数SwiftBuilder返回StringURLSession上有多个名为dataTask(with:completion:)的方法,但没有一个方法占用String为第一个参数。

如果您需要SwiftBuilder继续为代码的其他部分返回字符串,那么在这里您需要将该字符串转换为URL。

以下内容应该有效:

let session = URLSession(configuration: .default)

let imageUrlString = StringBuilder()
if let imageUrl = URL(string: imageUrlString) {
let downloadPicTask = session.dataTask(with: imageUrl) { (data, response, error) in
    // The download has finished.

等等......让我知道这是否有意义。