如何在swift3中获取UILabel中的JSON数据

时间:2017-12-28 06:48:52

标签: ios json swift uilabel

我正在尝试使用谷歌地图从坐标中获取位置详细信息。我正在获取JSON格式的信息。但我收到以下错误 - “条件绑定的初始化程序必须具有可选类型,而不是'任何'”下面是我的代码。请指导我如何继续 提前致谢

    func getAddressForLatLng(currentlocation: CLLocation) {

    let baseUrl = "https://maps.googleapis.com/maps/api/geocode/json?"
    let apikey = "XYZ"

    let url = NSURL(string: "\(baseUrl)latlng=\(currentlocation.coordinate.latitude),\(currentlocation.coordinate.longitude)&key=\(apikey)")
    let data = NSData(contentsOf: url! as URL)
    let json = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
    if let result = json["results"] as? NSArray {
            let address = result[0]
     //should try something here

    }
    }

我的地址数据是:

 {
"address_components" =     (
            {
        "long_name" = "Woodpecker Nature Trail";
        "short_name" = "Woodpecker Nature Trail";
        types =             (
            route
        );
    },
            {
        "long_name" = "Point Reyes Station";
        "short_name" = "Point Reyes Station";
        types =             (
            locality,
            political
        );
    },
            {
        "long_name" = "Marin County";
        "short_name" = "Marin County";
        types =             (
            "administrative_area_level_2",
            political
        );
    },
            {
        "long_name" = California;
        "short_name" = CA;
        types =             (
            "administrative_area_level_1",
            political
        );
    },
            {
        "long_name" = "United States";
        "short_name" = US;
        types =             (
            country,
            political
        );
    },
            {
        "long_name" = 94956;
        "short_name" = 94956;
        types =             (
            "postal_code"
        );
    }
);
"formatted_address" = "Woodpecker Nature Trail, Point Reyes Station, CA 94956, USA";
geometry =     {
    bounds =         {
        northeast =             {
            lat = "38.0396711";
            lng = "-122.8005417";
        };
        southwest =             {
            lat = "38.0376697";
            lng = "-122.8028458";
        };
    };
    location =         {
        lat = "38.0376744";
        lng = "-122.802158";
    };
    "location_type" = "GEOMETRIC_CENTER";
    viewport =         {
        northeast =             {
            lat = "38.0400193802915";
            lng = "-122.8003447697085";
        };
        southwest =             {
            lat = "38.0373214197085";
            lng = "-122.8030427302915";
        };
    };
};
"place_id" = ChIJAQAAwK7GhYARCiC5K45QogM;
types =     (
    route
 );
}

2 个答案:

答案 0 :(得分:1)

试试这段代码,

func getAddressForLatLng(latitude: String, longitude: String) {
    let url = NSURL(string: "\(baseUrl)latlng=\(latitude),\(longitude)&key=\(apikey)")
    let data = NSData(contentsOfURL: url!)
    let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
    if let result = json["results"] as? NSArray {
        if let address = result[0]["address_components"] as? NSArray {
            let number = address[0]["short_name"] as! String
            let street = address[1]["short_name"] as! String
            let city = address[2]["short_name"] as! String
            let state = address[4]["short_name"] as! String
            let zip = address[6]["short_name"] as! String
            print("\n\(number) \(street), \(city), \(state) \(zip)")
        }
    }
}

从这里开始Reference

答案 1 :(得分:1)

您提供的代码工作正常,因此我认为您在尝试将address对象转换为某些内容时会收到错误。

检查以下代码:

if let result = json["results"] as? NSArray {
        if let address = result[0] as? [String: AnyObject] {  //Cast your object here
            let formatted_address = address["formatted_address"] as? String ?? ""
            print(formatted_address) //Here you will get your coordinate address
        }
    }