NEW: Learn SwiftData for free with my all-new book! >>

How to read JSON with Swift and macOS

Forums > macOS

I could find some information how to read JSON for iOS. Nothing about macOS. When I try to apply the iOS code to macOS it gives me an error. For instance, this works in iOS but not macOS:

struct User: Codable {
    let name: String
    let email: String

class ViewController: NSViewController {

    override func viewDidLoad() {

        let url = URL(string: "")!

        URLSession.shared.dataTask(with: url) { data, _, _ in
            if let data = data {
                let users = try? JSONDecoder().decode([User].self, from: data)
                print (users![0].name)



In the console I have a long error, at the end it says: NSLocalizedDescription=A server with the specified hostname could not be found. But this works in iOS and if you put the address in a browser it goes to a JSON file.


This isn't an issue with reading the JSON, it's an issue with connecting to the web.

You need to go into your project's capabilities and make sure that App Sandbox is on and Outgoing Connections are allowed.

App Sandbox settings in Project Capabilities

You'll also need to go into your Info.plist and add App Transport Security Settings and, under that, Allow Arbitrary Loads in Web Content.

App Transport Security Settins in Info.plist


In info.plist I do not see Security Settings.

In any case, with the Outgoing Connections it seems the problem is solved

Thank you!


Hacking with Swift is sponsored by Swiftable

SPONSORED An iOS conference hosted in Buenos Aires, Argentina – join us for the third edition from November 29th to December 1st!

Get your ticket

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.