WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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() {
        super.viewDidLoad()

        let url = URL(string: "https://jsonplaceholder.typicode.com/users")!

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

    }

}

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.

4      

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

4      

In info.plist I do not see Security Settings.

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

Thank you!

4      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.