Извлечение Json данных, в NSArray на swift в xCode11 - PullRequest
0 голосов
/ 04 мая 2020

Я новичок ie по быстрому программированию, и я хочу знать, как извлечь данные из JSON в NSArray, вот мой код:

let urlPath = "http://localhost:8000/service.php" //this will be changed to the path where service.php lives

func downloadItems() {

    let url: URL = URL(string: urlPath)!
    let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)

    let task = defaultSession.dataTask(with: url) { (data, response, error) in

        if error != nil {
            print("Failed to download data")
        }else {
            print("Data downloaded")
            self.parseJSON(data!)
                        }
    }
    task.resume()
}
func parseJSON(_ data:Data) {

    var jsonResult = NSArray()

    do{
        jsonResult =  try JSONSerialization.jsonObject(with: data, options: [.mutableContainers, .allowFragments]) as! NSArray
        print(jsonResult)
    }
    catch let error as NSError {
        print(error)
    }
    var jsonElement = NSDictionary()
    let locations = NSMutableArray()

    for i in 0 ..< jsonResult.count
    {
        jsonElement = jsonResult[i] as! NSDictionary

        let location = LocationModel()

        //the following insures none of the JsonElement values are nil through optional binding
        if let name = jsonElement["Name"] as? String,
            let address = jsonElement["Address"] as? String,
            let latitude = jsonElement["Latitude"] as? String,
            let longitude = jsonElement["Longitude"] as? String

        {
            location.name = name
            location.address = address
            location.latitude = latitude
            location.longitude = longitude
        }

        locations.add(location)
    }

    DispatchQueue.main.async(execute: { () -> Void in
        self.delegate.itemsDownloaded(items: locations)
    })

Все, кажется, хорошо , но когда я запускаю свой код, он возвращал значение nil, и я пробовал несколько способов, таких как изменение NSArray на строку или даже на некоторые объекты, но значение все еще nil. Со стороны веб-сервиса, я думаю, в этом нет ничего плохого, мой веб-сервис выдает json, например:

[{
"Name": "Apple",
"Address": "Cupertino",
"Latitude": "37",
"Longitude": "122"
}, {
    "Name": "Google2",
    "Address": "Mountain",
    "Latitude": "37",
    "Longitude": "122"
}, {
    "Name": "GoogleEplex",
    "Address": "Mountain",
    "Latitude": "37",
    "Longitude": "122"
}]

может кто-то мне помочь, что происходит, почему я все еще получаю нулевое значение от линия

jsonResult =  try JSONSerialization.jsonObject(with: data, options: [.mutableContainers, .allowFragments]) as! NSArray
print(jsonResult)

Спасибо 101

...