如何将数据从可解码模型传递或实现到ViewController?

问题描述 投票:0回答:1

我不知道如何将数据从Decodable模型传递或实现到ViewController。我希望在我的视图控制器中得到状态200或msg "成功"。因此,我可以把它放在我的UIButton中,向用户显示服务器已连接。

我刚才尝试了debugPrint(response),API工作正常。

我的模型

struct ServerStatus: Decodable {

    let status: Int?
    let service: String?
    let function: String?
    let msg: String?

  enum CodingKeys: String, CodingKey {

    case status = "status"
    case service = "service"
    case function = "function"
    case msg = "msg"
  }
}

我使用Alamofire 5.0的API调用。

class APIManager {
    static let sharedInstance = APIManager()

    let headers: HTTPHeaders = [
         .authorization(APIDefinitions.api_id)
    ]

    func fetchServerStatus(parameters: Parameters, completion:@escaping (_ data: ServerStatus?, _ error: String?) -> Void){
        AF.request(APIDefinitions.getServerStatus, method: .get, headers: headers).responseDecodable(of: ServerStatus.self) { (response) in
            print(response)
            switch response.result{
                case .success(let serverStatus):
                    completion(serverStatus, nil)
                    break
                case .failure( _):
                    completion(nil, "The Internet connection appears to be offline.")
                    break
            }
        }
    }
}
ios swift xcode alamofire
1个回答
-1
投票

你已经用APIManager处理了网络部分。现在你只需要在ViewController的 viewDidLoad,像这样。

class ViewController: UIViewController {
    let button = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()
        APIManager.sharedInstance.fetchServerStatus(parameters: nil) { (response, error) in
            if let error = error {
                button.setTitle("Connection Failed", for: .normal)
            } else if let status = status {
                if response.status == 200 || response.msg == "success" {
                    button.setTitle("Connected", for: .normal)
                } else {
                    button.setTitle("Connection Failed", for: .normal)
                }
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.