将数据与ContentsOfUrl一起使用

时间:2017-09-06 17:05:10

标签: ios swift

我在这里有这段代码:

let endpointURL = URL(string: "http://foobar.com")

let downloadTask = URLSession.shared.downloadTask(with: endpointURL!, completionHandler: { url, response, error in

    if (error == nil) {

        let dataObject =  NSData(contentsOfURL: endpointURL!)

        let jsonArray: Array = JSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as Array 


    }
})

downloadTask.resume()

我遇到了这个问题:

Ambiguous use of 'init(contentsOfURL:)' for NSData part 

我怎样才能使它明确无误?

1 个答案:

答案 0 :(得分:1)

我建议在Swift 3中使用类似的东西来加载JSON数据dataTaskdownloadTask更合适。

let endpointURL = URL(string: "http://foobar.com")

let dataTask = URLSession.shared.dataTask(with: endpointURL!) { data, response, error in

    guard error == nil else {
        print(error!)
        return
    }
    do {
        // the assumed result type is `[[String:Any]]` cast it to the expected type
        if let jsonArray = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
            print(jsonArray)
        }
    } catch {
        print(error)
    }
}
dataTask.resume()