从网址获取图片时出错?

时间:2017-09-21 08:10:35

标签: ios swift3

 let defaultConfiguration = URLSessionConfiguration.default
    let operationQueue = OperationQueue.main
  let defaultSession = URLSession(configuration: defaultConfiguration, delegate: self, delegateQueue: operationQueue)
    if let url = URL(string: "https://newsapi.org/v1/articles?source=abc-news-au&sortBy=top&apiKey=47d2ce48babd47b1bc391b426b89ca23")
    {
        (defaultSession.dataTask(with: url) { (data, response, error) in

            if error != nil{
                return
            }
            do {
                let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
                if var dataDictionary = resultJson {
                    // dataDictionary["access_token"] as AnyObject
                    self.dataArray = dataDictionary["articles"] as! [Any]
                    var dataDictionary22 = self.dataArray[0] as! [String: Any] as [String : AnyObject]
                    let url = URL(string:
                        "\(String(describing: dataDictionary22["urlToImage"]!))")
                     print("url -> \(String(describing: url!))")
                    let task = URLSession.shared.dataTask(with: url!) { data, response, error in
                        guard let data = data, error == nil else {
                            return
                        }


                            self.imageView.image = UIImage(data: data)

                    }

                    task.resume()

                }

            } catch {
                print("Error -> \(error)")
            }

        }).resume()
    }

我正试图通过nsurlsession从open api获取新闻更新,并且它在关键字“urlToImage”中有字典 - > array-> dictionary-> 但我得到像http://www.abc.net.au/news/image/8968140-1x1-700x700.jpg的网址,但没有得到数据中的图像文件是空的可以任何人最小化代码lenth并解决我的问题

1 个答案:

答案 0 :(得分:0)

使用这段代码,您可以成功解析该特定的URL响应,我已在Playground中对其进行了测试。

这:"\(String(describing: dataDictionary22["urlToImage"]!))"不是从String获得AnyObject的方式,您应该使用条件转换。

if let url = URL(string: "https://newsapi.org/v1/articles?source=abc-news-au&sortBy=top&apiKey=47d2ce48babd47b1bc391b426b89ca23"){
    URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
        guard error == nil, let data = data else {
            print(error!);return
        }
        guard let resultJson = (try? JSONSerialization.jsonObject(with: data)) as? [String:Any] else {
            return
        }
        print(resultJson)
        guard let articles = resultJson["articles"] as? [[String:Any]], let firstArticle = articles.first else { return }
        guard let imageUrlString = firstArticle["urlToImage"] as? String, let imageUrl = URL(string: imageUrlString) else { return }
        URLSession.shared.dataTask(with: imageUrl, completionHandler: { data, response, error in
            guard error == nil, let data = data else {
                print(error!);return
            }
            let image = UIImage(data: data)
            DispatchQueue.main.async {
                self.imageView.image = image
            }
        }).resume()
    }).resume()
}

如果您想获得所有文章图片(在您的问题中,您只是解析第一个),只需将guard let articles = resultJson["articles"] as? [[String:Any]], let firstArticle = articles.first else { return }更改为以下内容:

for article in articles {
    guard let imageUrlString = article["urlToImage"] as? String, let imageUrl = URL(string: imageUrlString) else { return }
    URLSession.shared.dataTask(with: imageUrl, completionHandler: { data, response, error in
        guard error == nil, let data = data else {
            print(error!);return
        }
        let image = UIImage(data: data)
        //use the image
    }).resume()
}