FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

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.

   

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 Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

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

Reply to this topic…

You need to create an account or log in to reply.

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.