Search code examples
jsonswiftswift3

Failed to get a Wordpress JSON


I have a problem with a JSON that I recover from a site with WordPress, the problem is that when I try to consult the JSON, my query does not return anything.

I tried using Alamofire to recover my JSON but it does not work either, I do not know how to recover the JSON that returns my site with WordPress

I have tried to recover the JSON in the following way but it does not work, it does not return anything:

let urlString = URL(string: "https://www.sitioWeb.org.mx/wp-json/wp/v2/posts?per_page=100&tags=(id)")

    let request = URLRequest(url: urlString!)

    let task = URLSession.shared.dataTask(with: request){data, response, error in
        guard let data = data else{
            print("Solicitud fallida \(error!)")
            return
        }

        do{
            print("Recibimos respuesta")

            if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: String]{
                DispatchQueue.main.async {
                    let titulo = json["rendered"]
                    let content = json["content"]
                    let excerpt = json["excerpt"]

                    print(json)
                    print(titulo!)
                    print(content!)
                    print(excerpt!)
                }
            }
        }catch let parseError {
            print("Error al parsear: \(parseError)")
            let responseString = String(data: data, encoding: .utf8)
            print("respuesta: \(responseString!)")
        }
    }
    task.resume()

I have also tried with Alamofire in the following way:

Alamofire.request("https://www.sitioWeb.org.mx/wp-json/wp/v2/posts?per_page=100&tags=(id)").responseJSON(completionHandler: { response in

        if let json = response.result.value as? JSON{
            print(json)
        }

    })

But it still does not work.

This is the structure that JSON has:

[ { "id": 3438, "date": "2019-04-01T06:02:50", "date_gmt": "2019-04-01T12:02:50", "guid": { "rendered": "https://sitioWeb.org.mx/?p=3438" }, "modified": "2019-04-01T06:02:50", "modified_gmt": "2019-04-01T12:02:50", "slug": "documento-2019", "status": "publish", "type": "post", "link": "https://sitioWeb.org.mx/documento-2019 /", "title": { "rendered": "Documento 2019" }, "content": { "rendered": "https://sitioWeb.org.mx/wp-content/uploads/2019/04/document.pdf \" class=\"pdfemb-viewer\" style=\"\" data-width=\"max\" data-height=\"max\" data-mobile-width=\"500\" data-scrollbar=\"none\" data-download=\"off\" data-tracking=\"on\" data-newwindow=\"on\" data-pagetextbox=\"off\" data-scrolltotop=\"off\" data-startzoom=\"100\" data-startfpzoom=\"100\" data-toolbar=\"bottom\" data-toolbar-fixed=\"off\">document.pdf
\n", "protected": false }, "excerpt": { "rendered": "", "protected": false }, "author": 1, "featured_media": 0, "comment_status": "closed", "ping_status": "closed", "sticky": false, "template": "", "format": "standard", "meta": [], "categories": [ 39 ], "tags": [ 54, 55 ], "_links": { "self": [ { "href": "https://sitioWeb.org.mx/wp-json/wp/v2/posts/3438" } ], "collection": [ { "href": "https://sitioWeb.org.mx/wp-json/wp/v2/posts" } ], "about": [ { "href": "https://sitioWeb.org.mx/wp-json/wp/v2/types/post" } ], "author": [ { "embeddable": true, "href": "https://sitioWeb.org.mx/wp-json/wp/v2/users/1" } ], "replies": [ { "embeddable": true, "href": "https://sitioWeb.org.mx/wp-json/wp/v2/comments?post=3438" } ], "version-history": [ { "count": 1, "href": "https://sitioWeb.org.mx/wp-json/wp/v2/posts/3438/revisions" } ], "predecessor-version": [ { "id": 3440, "href": "https://sitioWeb.org.mx/wp-json/wp/v2/posts/3438/revisions/3440" } ], "wp:attachment": [ { "href": "https://sitioWeb.org.mx/wp-json/wp/v2/media?parent=3438" } ], "wp:term": [ { "taxonomy": "category", "embeddable": true, "href": "https://sitioWeb.org.mx/wp-json/wp/v2/categories?post=3438" }, { "taxonomy": "post_tag", "embeddable": true, "href": "https://sitioWeb.org.mx/wp-json/wp/v2/tags?post=3438" } ], "curies": [ { "name": "wp", "href": "https://api.w.org/{rel}", "templated": true } ] } }]

The console does not return any errors on the JSON

enter image description here


Solution

  • The correct type is [[String: Any]].

    if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]

    To get the URL for the author, drill down into the JSON like this:

    if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
        if let links = json[0]["links"] as? [[String: Any]] {
            if let author = links[0]["author"]? as? [String: Any] {
                if let authorURL = author["href"] as? String {
    
                }
            }
        }
    }