Как получить доступ к данным JSON из URL в Swift 5 - PullRequest
0 голосов
/ 01 октября 2019

Я создаю список данных из списка JSON с веб-сайта. Однако URLSession.shared.dataTask возвращает пустые данные.

Я пробовал печатать вне функции URLSession.shared.dataTask, JSONSerilization, JSONDecoder, Различные формы URL

Я работаю над этим почти неделю и все еще могуне понять, в чем проблема. Сейчас я думаю, что это потому, что я печатаю внутри функции, но из обучающих программ в Интернете я вижу, что все они печатаются внутри.

Любая помощь будет принята с благодарностью! :)

if let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!){
            URLSession.shared.dataTask(with: url) { (data, response, error) in

                guard let data = data else {
                    print("Data != Data")
                    return

                }

                let dataStr = String(decoding: data, as: UTF8.self)
                print("DataStr" + dataStr) //Empty


                do {
                    let dataParse = try? JSONDecoder().decode(OuterData.self, from: data)
                    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)

                    print(dataParse) //nil
                    print(json)//empty data


                } catch let jsonError {
                    print ("jsonError")
                    print (jsonError)
                }

            }.resume()

//Created from https://app.quicktype.io/#l=go

struct Suggestion: Codable {
    let id: String
    let name: String
    let audience_size: Int
    let path = [String]()
    let description: String?
    let topic: Topic?
    let disambiguation_category: String?

    enum CodingKeys: String, CodingKey {
        case id, name
        case audience_size = "audience_size"
        case path
        case description = "description"
        case topic
        case disambiguation_category = "disambiguation_category"
    }
}

struct OuterData: Codable{
    let dataSuggestion: [Suggestion]
}

enum Topic: String, Codable {
    case businessAndIndustry = "Business and industry"
    case education = "Education"
    case foodAndDrink = "Food and drink"
    case hobbiesAndActivities = "Hobbies and activities"
    case lifestyleAndCulture = "Lifestyle and culture"
    case newsAndEntertainment = "News and entertainment"
    case people = "People"
    case shoppingAndFashion = "Shopping and fashion"
    case sportsAndOutdoors = "Sports and outdoors"
    case technology = "Technology"
    case travelPlacesAndEvents = "Travel, places and events"
}

Ожидаемый результат:

{
   "data": [
      {
         "id": "6008740787350",
         "name": "Business and industry",
         "audience_size": 1759626900,
         "path": [
            "Interests",
            "Business and industry"
         ],
         "description": ""
      },
      {
         "id": "6003402305839",
         "name": "Business",
         "audience_size": 1231141110,
         "path": [
            "Interests",
            "Business and industry",
            "Business"
         ],
         "description": "",
         "topic": "Business and industry"
      },
      {
         "id": "6003248297213",
         "name": "Product (business)",
         "audience_size": 935729470,
         "path": [
            "Interests",
            "Additional Interests",
            "Product (business)"
         ],
         "description": null,
         "topic": "Business and industry"
      },
      {
         "id": "6004037932409",
         "name": "Management",
         "audience_size": 323096480,
         "path": [
            "Interests",
            "Business and industry",
            "Management"
         ],
         "description": "",
         "topic": "Business and industry"
      },
      {
         "id": "6002840040679",
         "name": "Music industry",
         "audience_size": 251698230,
         "path": [
            "Interests",
            "Additional Interests",
            "Music industry"
         ],
         "description": null,
         "topic": "News and entertainment"
      },
      {
         "id": "6002884511422",
         "name": "Small business",
         "audience_size": 87865033,
         "path": [
            "Interests",
            "Business and industry",
            "Small business"
         ],
         "description": "",
         "topic": "Business and industry"
      },
      {
         "id": "6003165841322",
         "name": "Distribution (business)",
         "audience_size": 79327710,
         "path": [
            "Interests",
            "Additional Interests",
            "Distribution (business)"
         ],
         "description": null,
         "topic": "Business and industry"
      },
      {
         "id": "6003342222945",
         "name": "Show business",
         "audience_size": 69642870,
         "path": [
            "Interests",
            "Additional Interests",
            "Show business"
         ],
         "description": null,
         "topic": "News and entertainment"
      },
      {
         "id": "6002932439173",
         "name": "Subscription business model",
         "audience_size": 64490740,
         "path": [
            "Interests",
            "Additional Interests",
            "Subscription business model"
         ],
         "description": null,
         "topic": "Business and industry"
      },
      {
         "id": "6003464157303",
         "name": "Business Insider",
         "audience_size": 62085690,
         "path": [
            "Interests",
            "Additional Interests",
            "Business Insider"
         ],
         "description": null,
         "topic": "Business and industry"
      },
      {
         "id": "6003190330534",
         "name": "Order (business)",
         "audience_size": 60961920,
         "path": [
            "Interests",
            "Additional Interests",
            "Order (business)"
         ],
         "description": null,
         "topic": "Travel, places and events"
      },
    ...
}

1 Ответ

0 голосов
/ 01 октября 2019

Просто замените

let dataSuggestion: [Suggestion]

на

let data: [Suggestion]

Имена членов структуры должны совпадать с соответствующими ключами JSON, если вы не добавляете CodingKeys.

И - какпредлагается в комментариях - всегда удаляйте вопросительный знак в try? внутри do - catch блока

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...