解析的JSON数据未打印到控制台

时间:2017-01-29 05:29:23

标签: ios

我编写了一个简单的代码,它从News API获取特定数据并将其打印到控制台。

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let url = URL(string: "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=af5f94cdf07e42ee877a3f2c2199d097")

    let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
        if error != nil {
            print("Error")
        }
        else {
            if let content = data {
                do {
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    if let articles = myJson["articles"] as? NSDictionary {
                        if let title = articles["title"] {
                            print(title)
                        }
                    }
                }
                catch {}
            }
        }
    }
    task.resume()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

然而,奇怪的是,这不会返回任何错误,也不会向控制台打印所需的“标题”。这是为什么?

1 个答案:

答案 0 :(得分:1)

我猜问题是App Transport Security。

确保在plist文件中设置这些键。

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