Apollo GraphQL与Swift:处理查询中的Null值解码错误
解决Apollo iOS调用PokeAPI GraphQL时的Null解码错误
问题诊断
错误GraphQLExecutionError(path: pokemon_v2_pokemon.32.sprites.0.home, underlying: ApolloAPI.JSONDecodingError.nullValue)的核心原因是:查询返回的某个字段为null,但Apollo代码生成器生成的Swift模型将该字段定义为非可选类型,导致JSON解码失败。具体来说,第33个精灵(索引32)的home sprite字段返回了null,而对应的Swift属性是强制非可选的,无法接受null值。
解决方案
最直接且符合GraphQL类型规范的修复方式是修改GraphQL查询,明确标记可能返回null的字段为可选,让代码生成器生成对应可选类型的Swift属性,从而兼容null值。
步骤1:修改GraphQL查询
在查询中给可能返回null的sprite子字段添加?,标记为可选字段:
query GetAllPokemon { pokemon_v2_pokemon(order_by: {pokemon_species_id: asc}) { name id sprites: pokemon_v2_pokemonsprites { home: sprites(path: "other.home.front_default")? showdown: sprites(path: "other.showdown.front_default")? officialArtwork: sprites(path: "other.official-artwork.front_default")? } pokemon_species_id } }
步骤2:重新生成Swift代码
关闭Xcode,回到项目目录执行代码生成命令:
./apollo-ios-cli generate
步骤3:验证修复
重新打开Xcode运行项目,此时生成的GetAllPokemonQuery模型中,home、showdown、officialArtwork字段会被定义为String?(可选类型),解码时遇到null值会自动解析为nil,不再抛出错误。
补充说明
- GraphiQL界面能正常运行查询是因为它不做严格的类型校验,会直接展示null值;而Swift是强类型语言,Apollo严格遵循类型匹配,非可选属性无法接受null。
- 如果
pokemon_v2_pokemonsprites数组本身也可能返回null,可以进一步将其标记为可选:sprites: pokemon_v2_pokemonsprites?,避免数组为null时的解码错误。
内容的提问来源于stack exchange,提问作者Luis Ramirez
相关产品推荐
相关产品推荐

