Использование Alamofire для POST и анализа ответа | Swift 5 - PullRequest
0 голосов
/ 21 января 2020

У меня есть следующее JSON, которое выдается, когда параметр occupation имеет значение POST:

[
    {
        "group": "GR2923",
        "number": "0239039",
    }
]

Мне нужно проанализировать эти данные в Swift и присвоить значение group для переменная groupValue и значение числа для переменной numberValue.

Я пытался использовать что-то подобное, но я не уверен, как реализовать массив JSON, который у меня есть, в Alamofire:

Alamofire.request(url, method: .get)
  .responseJSON { response in
      if response.data != nil {
        let json = JSON(data: response.data!)
        let name = json["group"][0][""].string
        if name != nil {
          print(name!)
        }
      }
  }

Ответы [ 2 ]

0 голосов
/ 21 января 2020

Вы можете использовать это для разбора json. Сначала вы должны проверить json значение NSDictionary или нет.

  Alamofire.request(stringURL, method: .get)
        .responseJSON { response in
            if let value = response.result.value as? NSDictionary {
                //    print(value)

                if let group =   value["group"] as? String {
                //    print(group)

}
}
}
0 голосов
/ 21 января 2020

Вы можете попробовать это:

Alamofire.request(url, method: .get)
  .responseJSON { response in
    if let value = response.value {
        let json = JSON(value).arrayValue
        if let name = json[0]["group"].string {
             print(name!)
         }
     }
}

Для отправки запроса с параметрами вы можете использовать это

 func getResult(url:String, paramKey:[String], paramValue:[Any], completion: @escaping (Bool, Any?) -> Void) {

        let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
        let params : Parameters = getParams(paramKey: paramKey, paramValue: paramValue)

        guard let url = URL(string: url) else {
            completion(false, nil)
            return
        }

        Alamofire.request(url,
                          method: .post,
                          parameters: params, encoding: URLEncoding.httpBody , headers: _headers)
            .validate()
            .responseJSON { response in

                guard response.result.isSuccess else {
                    completion(false, nil)
                    return
                }

                if let value = response.result.value{
                    let json = JSON(value)

                    if json["status_code"].stringValue == "200" {
                        completion(true, json)
                    } else {
                        completion(false, json)
                    }
                }
        }
    }

    func getParams(paramKey:[String], paramValue:[Any]) -> [String:Any] {

        var dictionary =  [String:Any]()

        dictionary.updateValue(Constants.API_TOKEN, forKey: HTTPParams.PARAM_API_TOKEN)

        for index in 0..<paramKey.count {
            dictionary.updateValue(paramValue[index], forKey: paramKey[index])
        }

        return dictionary
    }

А из ViewController вы можете использовать это для вызова

    let url = "Your API Url"
    let params = ["occupation"] // Param key
    let paramValues = ["doctor"] // Param values  
   // UrlRequest the file name where the method is placed 
    UrlRequest().getResult(url: url, paramKey: params, paramValue: paramValues) { (success, data) in
        if success {
          // Success result with data
        }else{
            // Failed 
        }
    }
...