Swift 4 URL下载不起作用

时间:2018-01-19 09:32:46

标签: ios swift image-loading

我正在尝试从此网址下载图片:

https://​i.ebayimg.com/00/s/MTA2NlgxNjAw/z/TaoAAOSwjkdZ57Jm/$_2.jpg

使用此代码:

    guard let escapedQuery = rawUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),
    let url = URL(string: escapedQuery) else { return }

    // check if image is new image, if not, stick with the old image
    if(previousUrl != rawUrl){
        previousUrl = rawUrl
        showActivityIndicatory()
        print("Download Started")
        // download the image from the provided url
        getDataFromUrl(url: url) { data, response, error in
            guard let data = data, error == nil else {
                DispatchQueue.main.async() {
                    // stop the animation/loading icon
                    self.imageLoadingIndicator.stopAnimating()
                    // set a default placeholder image
                    self.image = #imageLiteral(resourceName: "CellDefaultImage")
                }
                return
            }
            print(response?.suggestedFilename ?? url.lastPathComponent)
            print("Download Finished")
            DispatchQueue.main.async() {
                self.image = UIImage(data: data)
                self.imageLoadingIndicator.stopAnimating()
            }
        }
    }

}

func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
    // try to download the raw data on a different thread to provide optimal perfomance regarding UI
    URLSession.shared.dataTask(with: url) { data, response, error in
        completion(data, response, error)
    }.resume()
}

func showActivityIndicatory() {
    imageLoadingIndicator.center = self.center
    imageLoadingIndicator.startAnimating()
}

但我经常遇到:HTTP加载失败(错误代码:-1200 [3:-9802])或错误代码-1002等。

有人可能指出错误,也许我的图片网址格式错误了吗?

1 个答案:

答案 0 :(得分:0)

您检查过的图片链接网址是否正确。所以可能是任意加载许可的问题

因此,要解决此问题,请将以下Key值添加到info.plist文件

<key>NSAppTransportSecurity</key>
 <dict>
      <key>NSAllowsArbitraryLoads</key>
     <true/>
 </dict>