如何创建一个函数来在我的应用程序视图中显示评论 (Swift-JSON)



我正在按照此文档 https://developers.google.com/places/web-service/details 添加有关某个地方的所有信息,例如添加"几何"

 "geometry" : {
         "location" : {
            "lat" : -33.866651,
            "lng" : 151.195827
         },

我在类中创建的这个函数运行良好

private let geometryKey = "geometry"
private let locationKey = "location"
private let latitudeKey = "lat"
private let longitudeKey = "lng"
class EClass: NSObject  {
 var location: CLLocationCoordinate2D?
init(placeInfo:[String: Any]) {
        placeId = placeInfo["place_id"] as! String

        // coordinates
        if let g = placeInfo[geometryKey] as? [String:Any] {
            if let l = g[locationKey] as? [String:Double] {
                if let lat = l[latitudeKey], let lng = l[longitudeKey] {
                    location = CLLocationCoordinate2D.init(latitude: lat, longitude: lng)
                }
            }
        }
      }  

但是我很难添加"评论">

"reviews" : [
         {
            "author_name" : "Robert Ardill",
            "author_url" : "https://www.google.com/maps/contrib/106422854611155436041/reviews",
            "language" : "en",
            "profile_photo_url" : "https://lh3.googleusercontent.com/-T47KxWuAoJU/AAAAAAAAAAI/AAAAAAAAAZo/BDmyI12BZAs/s128-c0x00000000-cc-rp-mo-ba1/photo.jpg",
            "rating" : 5,
            "relative_time_description" : "a month ago",
            "text" : "Awesome offices. Great facilities, location and views. Staff are great hosts",
            "time" : 1491144016
         }
      ],

试图遵循我为几何创建的函数的相同概念,就像这样

if let t = place.details?["reviews"] as? [String:Any] {
                   if let n = t["author_name"], let m = t["text"] {
                       Mylabel.text = "(t)"
                   }

但是不起作用,我也尝试添加一个断点,只有第一行进入。我能做什么?如何创建构建以显示带有标签或任何我需要的内容的评论?

利用 Swift 4 中的Codable。您可以简单地将 JSON 转换为特定结构。例如,根据您的 JSON :

let json = """
    {
        "reviews" : [
            {
                "author_name" : "Robert Ardill",
                "author_url" : "https://www.google.com/maps/contrib/106422854611155436041/reviews",
                "language" : "en",
                "profile_photo_url" : "https://lh3.googleusercontent.com/-T47KxWuAoJU/AAAAAAAAAAI/AAAAAAAAAZo/BDmyI12BZAs/s128-c0x00000000-cc-rp-mo-ba1/photo.jpg",
                "rating" : 5,
                "relative_time_description" : "a month ago",
                "text" : "Awesome offices. Great facilities, location and views. Staff are great hosts",
                "time" : 1491144016
            }
        ]
    }
    """

可以使用以下代码将其转换为 Response 结构:

struct Response: Codable {
    struct Review: Codable, CustomStringConvertible {
        let text: String
        let authorName: String
        var description: String {
            return "Review text: (text) authorName: (authorName)"
        }
        enum CodingKeys: String, CodingKey {
            case text
            case authorName = "author_name"
        }
    }
    let reviews: [Review]
}
do {
    if let data = json.data(using: .utf8) {
        let decoder = JSONDecoder()
        let decoded = try decoder.decode(Response.self, from: data)
        print(decoded.reviews)
    } else {
        print("data is not available")
    }
} catch (let e) {
    print(e)
}

> 在你的代码中,t不是一个Dictionary而是一个Array。所以试着做这样的事情。其余的您可以根据自己的逻辑进行更改。

if let t = place.details?["reviews"] as? [String:Any] {
    for dic in t {
        if let n = dic["author_name"], let m = dic["text"] {
            Mylabel.text = "(t)"
        } 
    }
}

是的,但你也可以尝试这样做:

struct reviews: Codable{
    var reviews: [review]?
}
struct review: Codable{
    var author_name: String?
    var author_url: String?
    var language: String?
    var profile_photo_url: String?
    var rating: Int?
    var relative_time_description: String?
    var text: String?
    var time: Int?
}

然后:

if let dict = place.details?["reviews"] as? [String: Any], 
   let dataToDecode = dict.data(using: .utf8){
    do{
        let decodedReviews = try JSONDecoder().decode(reviews.self, from: dataToDecode)
     // here you have decoded reviews in array
    }catch let err{
        print(err)
    }
}

最新更新