Can’t use advanced custom fields value from WordPress

I am trying to use values from my WordPress server in my Swift project. I get the information in JSON format. The values that I want is created by “advanced custom fields” on the wordpress server.

I am loading it from another view controller and use this code to load it:

Read More
let nummer = NSUserDefaults.standardUserDefaults().valueForKey("nummer")
print(nummer)

Then I get this result:

{
    attachments =     (
    );
    author =     {
        description = "";
        "first_name" = "";
        id = 1;
        "last_name" = "";
        name = admin;
        nickname = admin;
        slug = admin;
        url = "";
    };
    categories =     (
    );
    "comment_count" = 0;
    "comment_status" = open;
    comments =     (
    );
    content = "<p>text</p>n";
    "custom_fields" =     {
        latitude =         (
            "22.324432"
        );
        longitude =         (
            "40.233221"
        );
    };
    date = "2015-12-11 08:12:31";
    excerpt = "<p>text</p>n";
    id = 37;
    modified = "2015-12-11 08:12:31";
    slug = "test-2";
    status = publish;
    tags =     (
    );
    title = test;
    "title_plain" = test;
    type = post;
    url = "http://localhost:8080/wordpress/2015/12/11/test-2/";
}

To get the title I use this code:

let dict = nummer!["title"] as? String
print(dict)

And get this result:
Optional(“test”)

I use this code to get longitude value:

let dict = nummer!["custom_fields"]
let longitude = dict!!["longitude"]
print(longitude)

Result:
Optional((
“40.233221”
))

Now I want to convert it to a double. But it returns nil:

let longitude = dict!!["longitude"] as? Double
print(longitude)

Result: nil

Why does it returns nil and not the double value?

Related posts

2 comments

  1. When you use as? you are attempting to downcast the unwrapped value to a Double, but it isn’t a Double it’s an Array.

    if let longitudeArray = dict!!["longitude"] as? Array<String> {
        if let longitude = Double(longitudeArray[0]) {
            print(longitude)
        }
    }
    
  2. Because this variable is a String not Double. You have to convert it

    if let longitudeString = dict!!["longitude"] as? String {
        let longitude = Double(longitudeString)
    }
    

    or

    if let longitudeString = dict!!["longitude"] as? String {
        let longitude = longitudeString.doubleValue
    }
    

Comments are closed.