从网络json解析图像

时间:2018-06-02 09:54:58

标签: ios json swift swift4

我有一个看起来像这样的json文件:

{
    "adTitle": "My Title",
    "adURL": "https://mylink.com/",
    "adImageURL": "http://mywebsite/bannerx@3x.png"
}

我从网站获取JSON值:http://mywebsite.com/file.json

问题是广告不知道加载了adImageURL,所以当我按下UIImageView时,但是当我按下UIImageView应该是的区域时,它会打开我的adURL。这是我用于JSON的代码:

var imageURL:String = "http://mywebsite/bannerx@3x.png"
    var adURL:String = "https://mylink.com/"

    func loadAdvertisement() {

        // Set up the URL request
        let todoEndpoint: String = "http://mywebsite.com/file.json"

        guard let url = URL(string: todoEndpoint) else {
            print("Error: cannot create URL")
            return
        }
        let urlRequest = URLRequest(url: url)

        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        // make the request
        let task = session.dataTask(with: urlRequest) {
            (data, response, error) in
            // check for any errors
            guard error == nil else {
                // print("error calling GET on /todos/1")
                // print(error!)
                return
            }
            // make sure we got data
            guard let responseData = data else {
                print("Error: did not receive data")
                return
            }
            // parse the result as JSON, since that's what the API provides
            do {
                guard (try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject]) != nil else {
                    print("error trying to convert data to JSON")
                    return
                }

                let json = try JSONSerialization.jsonObject(with: responseData, options:.allowFragments) as! [String:AnyObject]


                if (json != nil) {

                    self.imageURL = (json["adImageURL"] as? String)!
                    self.adURL = (json["adURL"] as? String)!

                    print(self.imageURL)
                    print(self.adURL)

                    DispatchQueue.main.async { () -> Void in

                        self.loadAdImage(self.imageURL)
                    }

                }


            } catch  {
                print("error trying to convert data to JSON")
                return
            }
        }

        task.resume()

        // let jsonURL = URL(string: "http://mywebsite.com/file.json")

        // self.getDataFromUrl(jsonURL!, completion: (data:Data?, response:URLResponse?, error:Error?)) -> Void


    }

    func loadAdImage(_ url:String) {

        getDataFromUrl(URL(string: url)!) { (data, response, error)  in
            DispatchQueue.main.async { () -> Void in
                guard let data = data, error == nil else { return }
                print(response?.suggestedFilename ?? "")
                print("Download Finished")
                self.advertImageView.image = UIImage(data: data)
            }
        }
    }

    func getDataFromUrl(_ url:URL, completion: @escaping ((_ data: Data?, _ response: URLResponse?, _ error: NSError? ) -> Void)) {

        URLSession.shared.dataTask(with: url) { (data:Data?, response:URLResponse?, error:Error?) in

            completion(data, response, error as NSError?)


        }.resume()

    }

在事件LOG中,打印出两个print("error trying to convert data to JSON")命令。我之前在我的项目中使用过这段代码,它工作得很好,但我不知道它为什么不再工作了。

1 个答案:

答案 0 :(得分:1)

添加消息以捕获并检查您实际上出现的错误:

 do {

        let json = try JSONSerialization.jsonObject(with: responseData, options:.allowFragments) as! [String:AnyObject]        

    } catch let message  {
        print("error trying to convert data to JSON" + "\(message)")
        return
    }