如何迅速获得错误消息出现在控制台中以快速在UI中进行验证?

时间:2018-09-18 02:44:52

标签: ios swift

如何将this error message in console添加到我的API服务验证中?如果用户输入无效的事件代码,我将无法获得如何向API服务添加验证的逻辑。希望能为您提供帮助。谢谢

示例API服务代码

func validatePasscode(passcode: String, completionHandler: @escaping ((Event?, Error?) -> Void))
{
let passcodeURL = URL (string: "\(PASSCODE_CHECKER_URL)/\(passcode)")


Alamofire.request(passcodeURL!, method: .get).responseJSON { (response) in
        print(response)

    switch response.result {
    case .success:
        if let passcodeJSON = response.result.value as? [[String : Any]],
            let passcodeObj = passcodeJSON.first {
            print(passcodeObj)
            let event = Event.init(JSON: passcodeObj);

            completionHandler(event, nil)


            }

    case .failure(let error):
        print("failure with error: \(error.localizedDescription)")
        completionHandler(nil, error)
        }

    }

}

API响应

SUCCESS: (
    {
    "closed_datetime" = "<null>";
    "closed_flag" = 0;
    "date_created" = "2018-07-12T12:53:00.000";
    "delete_flag" = 0;
    "deleted_datetime" = "<null>";
    "end_datetime" = "2018-07-13T13:00:00.000";
    "event_id" = "707024c4-8b93-46d6-b34d-e95b53b45750";
    "event_location" = "IT Room";
    "event_name" = "Laugh Trip";
    hasRaffle = 0;
    "participant_count" = 6;
    "registered_participants_count" = 5;
    "registration_req" = 0;
    "reopen_datetime" = "<null>";
    "reopen_flag" = 0;
    "start_datetime" = "2018-07-13T12:00:00.000";
  }
 )

1 个答案:

答案 0 :(得分:0)

如果我没看错,我认为您的if let passcodeJSON = response.result.value as? [[String : Any]]检查可能失败。

我认为应该是if let passcodeJSON = response.result.value as? [String : Any],然后您可以使用if let message = passcodeJSON["message"] as? String

访问字典中的值
 case .success:
        if let passcodeJSON = response.result.value as? [String : Any],
            let passcodeObj = passcodeJSON.first {
            print(passcodeObj)
            let event = Event.init(JSON: passcodeObj);

            // Can be used here
            if let message = passcodeJSON["message"] as? String {
                print(message)
            }

            completionHandler(event, nil)


            }