Я использую graphql для получения значений API с помощью Apollo. Я успешно загрузил schema.json и получил значения из grpahql. но я не могу получить массив значений значений json.
Это мой пример ответа:
{
"data": {
"team_Dashboard": {
"activeMission": "Food Mission",
"currentMissionChallenges": [
{
"id": "123",
"title": "Challenge",
"estTime": "5",
"location": "Anywhere",
"maxPts": "30",
"status": "Not yet started"
},
{
"id": "1234",
"title": " II Challenge",
"estTime": "5",
"location": "Anywhere",
"maxPts": "70",
"status": "Not yet started"
}
]
}
}
}
Запрос Graphql:
query teamDashboard($teamId: ID!) {
team_Dashboard(teamId: $teamId) {
activeMission
currentMissionChallenges
}
}
Ответ схемы Graphql:
missionDeadLine: String
currentMissionChallenges: [JSON]
Когда я добавляю currentMissionChallenges ([JSON]) в свой запрос Graphql, получаю ответ с ошибкой от сервера. но когда я удаляю currentMissionChallenges из запроса Graphql, получаю успешный ответ и значения с сервера.
Проблема в том, что currentMissionChallenges имеет формат [JSON]. Когда я меняю свой запрос graphql Это ответ graphql
query teamDashboard($teamId: ID!) {
team_Dashboard(teamId: $teamId) {
activeMission
currentMissionChallenges {
id
title
estTime
location
maxPts
status
}
}
}
Следующее отображение ошибки в dashBord.grpahql
Field "currentMissionChallenges" must not have a selection since type "[JSON]" has no subfields.
Как я могу получить значения массива json из graphql. в чем проблема для получения значений Json? Помогите, пожалуйста!

Я предлагаю вам использовать собственный скаляр.
import Apollo
public typealias JSON = [String: Any]
extension Dictionary: JSONDecodable {
public init(jsonValue value: JSONValue) throws {
if let array = value as? NSArray {
self.init()
if var dict = self as? [String: JSONDecodable & JSONEncodable] {
dict["data"] = array as! [[String: Any]]
self = dict as! Dictionary<Key, Value>
return
}
}
guard let dictionary = value as? Dictionary else {
throw JSONDecodingError.couldNotConvert(value: value, to: Dictionary.self)
}
self = dictionary
}
}
var currentMissionChallanges = [JSON]()
func getTeamDashboard(id:String) {
let query = TeamDashboardQuery(id:id)
apollo.fetch(query:query) { [weak self] result, error in
if let dashboards = result.data?.team_dashboard {
if let array = dashboards!["currentMissionChallanges"] as?
[JSON] {
self?.currentMissionChallanges = array
}
}
}
}
The best thing about GraphQL is we can use the query as model
Поскольку ответ будет таким же, как и запрос, поэтому лучше назначить ответ переменной типа Query.
Разрешите пояснить на примере: -
Предположим, если мне нужно запросить данные моего профиля,
Profile.graphql
query MyProfile{
player {
me {
id
secret
name
email
state
country
timezone
picture
pictureType
audio
rank
}
}
countries{
value
viewValue
}
}
Once we'll build the app, it'll create MyProfileQuery in API.swift. In viewController we can use the response as below-
var myProfileData: MyProfileQuery.Data.Player.Me? // Declaring the valiable of player Type
ApolloClientManager.sharedInstance
.fetchQuery(MyProfileQuery(), showLoader: true,
viewController: self) { (response) in // Fetching response using Apollo Client Manager
if let allData = response {
if let profiledata = allData.player?.me {
self.myProfileData = profiledata // Assigning response into the variable declared
self.myEdittingProfileData = profiledata
self.updateUI()
}
if let countryData = allData.countries {
self.allCountrydata = countryData
self.getPickerDataForState(comppletion: {
self.openTimeZonePicker(completion: {
print("got timeZone Data")
})
})
}
}
}
Now we have response into the myProfileData variable which we can use as follows -
Теперь мы можем получить доступ ко всем значениям, упомянутым в нашем запросе, как показано ниже.
print("player id is- \(myProfileData?.id)")
print("player name is- \(myProfileData?.name)")
print("player email is- \(myProfileData?.email)")
print("player state is- \(myProfileData?.state)")
print("player rank is- \(myProfileData?.rank)")
print("player pictureType is- \(myProfileData?.pictureType)")
// player id is- 10
// player name is- jordan
// player email is- [email protected]
// player state is- Ohio
// player rank is- 101
// player pictureType is- custome
//
Надеюсь, это поможет вам ???