使用通知中心从另一个视图控制器访问模式弹出窗口的视图时遇到困难

时间:2018-06-28 08:50:44

标签: ios swift4 notificationcenter

我尝试在我的应用程序进行网络通话时向用户显示活动指示器,如果它捕获到任何错误,则会显示带有错误消息的视图和重试按钮,单击该按钮可以调用该函数以进行网络通话再次。 我的活动指示符视图和包含重试按钮的错误标签视图位于称为ProgressIndicaterViewController的视图控制器中,并且我做了一个全局函数,该函数进行网络调用,另一个函数则创建一个URLRequest并将其提供给网络呼叫功能。我正在从homeviewcontroller调用URLRequest的方法,并调用另一个进行网络调用的方法。

现在的问题是,每当网络响应为nil时,它都会显示错误消息和一个重试按钮,但是当用户单击重试按钮时,活动指示器就会显示,并且错误消息视图不可见。

这是HomeViewController

class HomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // adding the observer to recall the function again
        NotificationCenter.default.addObserver(self, selector: #selector(loadAccessToken(notification:)), name: NSNotification.Name(rawValue: "AccessToken"), object: nil)

        }

    override func viewDidAppear(_ animated: Bool) {

        // posting to the observer to call the function
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "AccessToken"), object: nil)
    }

    // this method makes the network calls and receives response in the closure
    @objc func loadAccessToken(notification: NSNotification) {

        fetchAccessToken(notification: "AccessToken") {
            self.presentedViewController?.dismiss(animated: false, completion: nil)
            self.performSegue(withIdentifier: "mainViewController", sender: nil)
        }
}

}

这是我的URLRequest方法

extension UIViewController {

    func fetchAccessToken (notification: String, Completion: @escaping ()->()) {
    // accessings the info the plist variables
    let accessUrl = Bundle.main.infoDictionary!["Access_Token"] as! String

    //creating a url request and setting a method
    var request = URLRequest(url: URL(string: accessUrl)!)
    request.httpMethod = "POST"

    // accessings the info the plist variables
    let appKey = Bundle.main.infoDictionary!["App_Key"] as! String

    // adding the parameter to the request
    let postString = "app_key=\(appKey)"
    request.httpBody = postString.data(using: String.Encoding.utf8)

    // making the call to the server
        serverCall(notificationString: notification, request: request) { (Data) in
        do {

            // decoding the response and set the access token to the user defaults
            let access = try JSONDecoder().decode(AccessToken.self, from: Data)
            UserDefaults.standard.set("Bearer \(access.access_token)", forKey: "AccessToken")
            Completion()
        } catch let e {
            print(e)
        }
    }
}
}

AccessToken是模型类

这是进行网络通话的方法

extension UIViewController {

    func serverCall (notificationString: String, request: URLRequest, Completion: @escaping (Data)->()) {

        if presentedViewController != nil {
            presentedViewController?.dismiss(animated: false, completion: nil)
            print("2222")
        }
        let main = UIStoryboard(name: "Main", bundle: nil)
        let desVC = main.instantiateViewController(withIdentifier: "ProgressIndicaterViewController") as! ProgressIndicaterViewController
        desVC.modalPresentationStyle = .overCurrentContext
        desVC.notification = notificationString
        print("openedView")
        self.present(desVC, animated: false, completion: nil)

    //making network call
    _ = URLSession.shared.dataTask(with: request) { (Data, response, error) in

        //checking response for error
        // if error occurs displaying a message with a retry button
        if let statusCode = response as? HTTPURLResponse{
            if statusCode.statusCode == 404 {
                print("404")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "snakeBar"), object: nil)
            }
        } else if response == nil {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "snakeBar"), object: nil)
            print("data")
        }

        //checking if the data is not nil and decoding the json response into the variable
        if Data != nil {
            print("Delete")
            Completion(Data!)
        }
        }.resume()
}
}

这是ProgressIndicaterViewController

class ProgressIndicaterViewController: UIViewController {

    @IBOutlet weak var snakeBar: UIView!
    @IBOutlet weak var reloadView: TicketHole!
    @IBOutlet weak var activityIndicater: UIActivityIndicatorView!
    var notification: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        reloadView.isHidden = false
        activityIndicater.startAnimating()
        snakeBar.isHidden = true

        // adding the observer to recall the function again
        NotificationCenter.default.addObserver(self, selector: #selector(displaySnake(notification:)), name: NSNotification.Name(rawValue: "snakeBar"), object: nil)
    }

    @IBAction func retryButton(_ sender: Any) {
        print("111")
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: notification!), object: nil)
    }

    @objc func displaySnake(notification: NSNotification) {
        DispatchQueue.main.async {
            self.reloadView.isHidden = true
            self.snakeBar.isHidden = false
        }
    }
}

0 个答案:

没有答案