TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.