代码之家  ›  专栏  ›  技术社区  ›  Angel F Syrus patel jigar

如何调用graphqlapi

  •  1
  • Angel F Syrus patel jigar  · 技术社区  · 7 年前

    如何在视图控制器中调用graphqlapi

    let url = URL(string: "http://xxxx.com/graphql")!
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    
    let query = "{query:mutation {\n  signin(email: \"adc.inlove@gmail.com\", password: \"qwerty\") {\n    result {\n      token\n      firstName\n      lastName\n      profileImage\n      status\n    }\n  }\n}\n}"
    let body = ["query": query]
    request.httpBody = try! JSONSerialization.data(withJSONObject: body, options: [])
    request.cachePolicy = .reloadIgnoringLocalCacheData
    
    let task = URLSession.shared.dataTask(with: request, completionHandler: { data, _, error in
        if let error = error { print(error); return }
        guard let data = data else { print("Data is missing."); return }
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            print(json)
        } catch let e {
            print("Parse error: \(e)")
        }
    })
    task.resume()`
    

    但它显示的错误是,

    Error Domain=NSCocoaErrorDomain Code=3840“字符0周围的值无效。”UserInfo={NSDebugDescription=字符0周围的值无效。}

    而且它在邮递员和获取输出方面也非常有效。任何人请帮助我找出解决方案。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Daniel Rearden    7 年前

    这是您当前发送的文档:

    {
      query:mutation  {
        signin(email: "adc.inlove@gmail.com", password: "qwerty") {
          result {
            token
            firstName
            lastName
            profileImage
            status
          }
        }
      }
    }
    

    对于GraphQL文档,这是不正确的语法。根据规范,文档应具有以下格式:

    OperationType [Name] [VariableDefinitions] [Directives] SelectionSet
    

    query mutation subscription

    如果省略了操作类型,则假定文档是一个查询。这被称为“查询速记”。所以给出一个有效的查询,比如:

    query SomeOperationName {
      users {
        name
      }
    }
    

    {
      users {
        name
      }
    }
    

    不过,以上只适用于查询,而不适用于突变。鉴于以上所有情况,您的文档有一组额外的花括号和无效的操作类型。至少,将其更改为:

    mutation {
      signin (email: "adc.inlove@gmail.com", password: "qwerty") {
        result {
          token
          firstName
          lastName
          profileImage
          status
        }
      }
    }
    

    或者。。。

    let query = "mutation { signin(email: \"adc.inlove@gmail.com\", password: \"qwerty\") { result { token firstName lastName profileImage status } } }"