0

I'm trying to use Swift 4 Codable feature to get JSON but for some reason it creates an error that says:

Argument type string does not conform to expected type decoder

Here is my code:

Xcode Screenshot

import UIKit

struct aURL : Codable {
    let title: String
    let aurl: String
    //    let style: URLStyle
}

 class SectionTableViewController: UITableViewController {

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    do {
        let queue = DispatchQueue(label: "cool")
        queue.async {

            if let somedata = try? Data(contentsOf: URL(from: "http://json-schema.org/example/geo.json")!, options: []) {

                let json = try? JSONSerialization.jsonObject(with: somedata, options: [])
                print(json)

                DispatchQueue.main.async {

                }
            }

        }
    } catch let error as NSError {
        print("Error: \(error)")
    }

}

and if I try to fix it using Xcode suggested fix as shown in the image:

Xcode Screenshot

I get this error:

Xcode Screenshot

Could not cast value of type 'Swift.String' (0x1015acf68) to 'Swift.Decoder' (0x1015ec460).

1 Answer 1

3

There is a misunderstanding.

The URL API

init(from decoder: Decoder) throws

can only be used within the custom struct to create an URL from a given Decoder very similar to the init(coder API of the class related NSCoding protocol.


In the context to create an URL from a string you have to use URL(string

URL(string: "http://json-schema.org/example/geo.json")!

That's exactly what the error message says: I'm expecting a Decoder but I'm getting a String


Important note:

Never load data from a remote URL with the synchronous API Data(contentsOF: – not even in an asynchronous dispatch queue – and don't carelessly ignore errors with try?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.