简体   繁体   English

如何访问alamofire响应

[英]How to access alamofire response

I'm new to iOS and I have some Swift code in app that's supposed to switch cases depending on the error message that I receive from the server. 我是iOS的新手,我在应用程序中有一些Swift代码,该代码根据我从服务器收到的错误消息来切换大小写。 The message is wrapped and I'm having trouble getting to it. 邮件已包装好,我很难到达。 Here's the code 这是代码

func sendAlamofireRequest(submissionURL: URL, parameters: Parameters, chosenTracker: String) -> String {

    var outputMessage = ""

    Alamofire.request(submissionURL, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseString() {
        response in
        switch response.result {
        case .success:
            print("Validation Successful...\(String(describing: response.value))")

            print("response value: \(String(response.value!))")
            switch response.value {
            case "error_none"?:
                outputMessage = "No matching Group Code. If you are having trouble, please go to \nhttps://app.phillyscientists.com"
                break
            case "error_tooManyIDs"?:
                outputMessage = "Error, please contact developer."
                break
            case "error_noGroupIDReceived"?:
                outputMessage = "Try Again."
                break
            default:

                let JSONResponse : JSON = JSON.init(parseJSON: response.result.value!)

                //uncomment this section for debugging
                //                        print("=================<JSON RESP>=================");
                //                        print(JSONResponse)
                //                        print("=================</JSON RESP/>=================");
                //
                let teacherNameGot = self.parseJSONData(json: JSONResponse, trackerValuePassed: chosenTracker)
                self.saveJSONDataToUserDefaults(teacher: teacherNameGot)

//                    outputMessage = "Logged In Successfully!"

                break
            }

        case .failure(let error):
            outputMessage = String(error.localizedDescription)
            print(outputMessage)

        }
    }
    return outputMessage
}

Here's the output from console: 这是控制台的输出:

Validation Successful...Optional("{\"Error\":\"error_none\"}")
response value: Optional("{\"Error\":\"error_none\"}")

How do I get to the value so that the switch case actually starts working? 如何获得该值,以便开关盒真正开始工作? Thanks! 谢谢!

you can use Alamofire method .responseJSON which will give you an http object that has several attributes like request and response . 您可以使用Alamofire方法.responseJSON ,这将为您提供一个http对象,该对象具有几个属性,例如requestresponse Take this code as an example: 以以下代码为例:

Alamofire.request("https://your-service-url.com/api", method: .post, parameters: paremeters, encoding: JSONEncoding.default, headers: headers).responseJSON{ (data) in

            guard let statusCode = data.response?.statusCode, statusCode == 200, let result = data.result.value as? [[String: Any]] else{
                print("Error with HTTP status \(data.response?.statusCode ?? 0)")

                return
            }
            var events : [Event] = []
            result.forEach({ (rawEvent) in
                events.append(Event(from: rawEvent))
            })


            handler(events, statusCode)
    }

Notice how I play there with the objects that .responseJSON provides, and how I get the resulting array from the service by accessing data.result.value (that being said this will depend on the data structure of your service response) 注意我如何在其中处理.responseJSON提供的对象,以及如何通过访问data.result.value从服务获取结果数组(也就是说,这将取决于服务响应的数据结构)

It seems that the output is in Json, so i'll need to map it into an object(or class,whatever you call it). 似乎输出在Json中,因此我需要将其映射到一个对象(或类,无论您叫什么)。 If you think its not worth it, you can convert it into an Dictionary, i think it will work as well 如果您认为它不值得,则可以将其转换为字典,我认为它也可以使用

@Gustavo caiafa is right, Mapping it to JSON did the trick. @Gustavo caiafa是正确的,将其映射到JSON可以解决问题。 Here's the code for anyone who gets stuck on something similar: 这是任何陷入类似困境的人的代码:

Alamofire.request(submissionURL, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseString() { (response) in

        let outputResponseJSON : JSON = JSON.init(parseJSON: response.result.value!)
        let outputResponseText = JSON(outputResponseJSON)["Error"].stringValue

        switch response.result {
        case .success:
            print("Validation Successful...\(String(describing: response.value))")

            print("response value: \(String(describing: String(outputResponseText)))")
            switch outputResponseText {
            case "error_none":
                outputMessage = "No matching Group Code. If you are having trouble, please go to \nhttps://app.phillyscientists.com"
                print(outputMessage)
                break
            case "error_tooManyIDs":
                outputMessage = "Error, please contact developer."
                print(outputMessage)
                break
            case "error_noGroupIDReceived":
                outputMessage = "Try Again."
                print(outputMessage)
                break
            default:

                let JSONResponse : JSON = JSON.init(parseJSON: response.result.value!)

The answer is using SwiftyJSON for the outputResponseJSON and outputResponseText values. 答案是使用SwiftyJSON作为outputResponseJSON和outputResponseText值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM