简体   繁体   中英

Parsed JSON data not being printed to the console

I have written a simple code that takes specific data from a News API and prints it to the console.

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.
}

However, strangely, this returns no errors AND doesn't print the desired "title" to the console either. Why is this?

I guess the problem would be the App Transport Security.

Make sure you set up these keys in your plist file.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM