Home > database >  Parse Wiki Nearby
Parse Wiki Nearby

Time:01-18

I'm new to Swift, and trying to figure out how to parse the JSON returned by Wiki Nearby. With the help of https://www.youtube.com/watch?v=sqo844saoC4 here's where I am right now:

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let url = "https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gscoord=37.7891838|-122.4033522&gsradius=10000&gslimit=2&format=json"
        getData(from: url)
        
        
    }
    
    private func getData(from url: String) {
        
        let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in
            
            guard let data = data, error == nil else {
                print("Something went wrong")
                return
            }

            
            var result: Response?
            do {
                result = try JSONDecoder().decode(Response.self, from: data)
            }
            catch {
                print("failed to convert \(error.localizedDescription) ")
            }
            
            guard let json = result else {
                return
            }
            
            print(type(of: json.query.geosearch))
            print(json.query.geosearch.self)
            
            
        })
        task.resume()
    }
    
    
}



struct Response: Codable {
    let batchcomplete: String
    let query: Query
}

struct Query: Codable {
    let geosearch: [Geosearch]?
}

struct Geosearch: Codable {
    
    let pageid: Int?
    let title: String?
}

Following Need help parsing wikipedia json api in SWIFT I believe that geosearch is a dictionary. The code runs, but how do I retrieve the title or pageid from geosearch (print(json.query.geosearch.title) gives an error)?

Sorry - probably something really basic... any pointers would be appreciated.

Philipp

CodePudding user response:

You need to access the item of array to get the pageid or title like:

print(json.query.geosearch?[0].title ?? "")

Since the json returns an array

{
  "batchcomplete": "",
  "query": {
    "geosearch": [
      {
        "pageid": 18618509,
        "ns": 0,
        "title": "Wikimedia Foundation",
        "lat": 37.78916666666667,
        "lon": -122.40333333333334,
        "dist": 2.5,
        "primary": ""
      },
      {
        "pageid": 42936625,
        "ns": 0,
        "title": "Foxcroft Building",
        "lat": 37.78916666666667,
        "lon": -122.40333333333334,
        "dist": 2.5,
        "primary": ""
      }
    ]
  }
}

CodePudding user response:

print(json.query.geosearch.self) //This will store the repsone in the let geosearch: [Geosearch]?


//You can check the individual result for the 1st and 2nd object 
print(json.query.geosearch[0].pageid)//18618509
print(json.query.geosearch[0].title) //"Wikimedia Foundation"

print(json.query.geosearch[1].pageid)//42936625
print(json.query.geosearch[1].title) //"Foxcroft Building"


CodePudding user response:

try the following code. It uses a completion closure to "wait" until the results are fetched before returning them. Since geosearch is an array you need to loop through it. Note, the json response is parsed without errors. Works for me.

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let url = "https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gscoord=37.7891838|-122.4033522&gsradius=10000&gslimit=2&format=json"
        
        getData(from: url) { response in
            if let result = response,
               let geosearch = result.query.geosearch {
                print("-----> result: \(result) \n")
                for geo in geosearch {
                    print("geo.title: \(geo.title)")
                }
            }
        }
    }
    
   func getData(from url: String, completion: @escaping(Response?) -> ()) {
    if let theURL = URL(string: url) {
        let task = URLSession.shared.dataTask(with: theURL) { data, response, error in
            guard let data = data, error == nil else {
                print("Something went wrong")
                completion(nil)
                return
            }
            do {
                let result = try JSONDecoder().decode(Response.self, from: data)
                completion(result)
            } catch {
                print("failed to convert \(error) ")
                completion(nil)
            }
        }
        task.resume()
    }
}
    
}
  •  Tags:  
  • Related