NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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.

1      

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

1      

In info.plist I do not see Security Settings.

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

Thank you!

1      

Hacking with Swift is sponsored by MadMachine

SPONSORED Want to explore your Swift skill outside of the Apple world? Join the MadMachine community and start to program microcontrollers in Swift.

Get it now

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.