如何将我的网络代码与ViewController分开

时间:2018-07-27 08:27:23

标签: ios swift networking alamofire

此刻,我正在使用Alamofire进行发帖请求。我首先在ViewController中建立了它并开始工作。但是后来我试图通过在另一个class中构建它来将其分离。我使用singleton,并且在致电ViewController时仍然可以使用。唯一的问题是状态恢复成功后,我试图在用户登录时实例化另一个ViewController。我不想在网络课程中这样做,我想在我的内部完成它ViewController。我该如何实现?

enum Status: Int {
    case Success = 200
    case Failure = 401
}

enum HTTPMethod: String {
    case Post = "POST"
    case Get = "GET" 
}

enum APIKey: String {
    case value = "somevalueeeeeeeee"
    case key = "somekeyyyyyyyyyyyyyy"
}

import Foundation
import Alamofire
import UIKit

class NetworkManager {
    static let shared = NetworkManager()

    func makePostRequest(url: URL, params: Parameters, headers: HTTPHeaders, credential: URLCredential) {
        Alamofire.request(url, method: .post, parameters: params, headers: headers).authenticate(usingCredential: credential)
            .responseJSON { response in
                print(response)
                let status = response.response?.statusCode
                switch status {
                case Status.Success.rawValue:
                    print("I would like to instantiate my viewcontroller here")
                case Status.Failure.rawValue:
                    print("Bad Request")
                default:
                    break
                }
        }
    }
}

import UIKit
import Alamofire

class LoginViewController: UIViewController {
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextfield: UITextField!

    private func login() {
        guard let userName = emailTextField.text else { return }
        guard let passWord = passwordTextfield.text else { return }

        let params: Parameters = [
            "username": userName,
            "password": passWord
        ]
        guard let url = URL(string: URLS.url.rawValue) else { return }
        let headers = [APIKey.key.rawValue: APIKey.value.rawValue]
        let credential = URLCredential(user: userName, password: passWord, persistence: .forSession)

        NetworkManager.shared.makePostRequest(url: url, params: params, headers: headers, credential: credential)
    }

    @IBAction func onLoginTapped(_ sender: UIButton) {
            login()
        }
    }

2 个答案:

答案 0 :(得分:2)

将完成块添加到您的函数中:

user.members

并从ViewController中这样调用它:

related_name='members'

答案 1 :(得分:1)

您可以从网络管理器类将完成处理程序传递给控制器​​。

 func makePostRequest(url: URL, params: Parameters, headers: HTTPHeaders, credential: URLCredential, completion:@escaping (Result<Any>)->()) {
        Alamofire.request(url, method: .post, parameters: params, headers: headers).authenticate(usingCredential: credential)
            .responseJSON { response in
                print(response)
                completion(response.result)
                let status = response.response?.statusCode
                switch status {
                case Status.Success.rawValue:
                    print("I would like to instantiate my viewcontroller here")
                     completion(response.result)
                    break
                case Status.Failure.rawValue:
                    print("Bad Request")
                     completion(response.result)
                    break
                default:
                    break
                }
        }
    }

现在您可以像下面这样调用该函数

  NetworkManager.shared.makePostRequest(url: url, params: , headers: param, credential: credential, completion: { (response) in
         if result.isSuccess, let json = result.value {
            // Use json variable to handle json
        } else {
            self.showAlert(R.string.keys.somethingWentWrong())
        }
   })