简体   繁体   English

重新获得网络连接后发出Alamofire请求

[英]Make an Alamofire request after regaining network connection

I'm building an app that needs to make HTTP requests to an API. 我正在构建一个需要向API发出HTTP请求的应用。 I want to handle the network connection status , so when the network is not reachable it presents a popup dialog and when the network is reachable again the popup dismisses. 我想处理网络连接状态,因此当网络不可访问时,它将显示一个弹出对话框,当网络可访问时,将再次弹出该对话框。

Currently I am able to do that , THE PROBLEM is that when the popup is dismissed because the network is reachable again I do not know how to (or where to) make the HTTP requests again. 当前,我能够做到这一点,问题是,由于再次可以访问网络而关闭弹出窗口时,我不知道如何(或在哪里)再次发出HTTP请求。

I have build a singleton's class to handle reachability: 我建立了一个单例课程来处理可达性:

import Foundation
import PopupDialog
import Alamofire

class Reachability {

private var currentViewController : UIViewController? = nil
private var popup : PopupDialog? = nil

let title = "Network connection error".localized
let message = "It seems you have problems with connection, please check your internet connection.".localized
let settingsButton = DefaultButton(title: "Settings".localized, action: {
    if let url = URL(string:"App-Prefs:root=Settings&path=General") {
        UIApplication.shared.open(url)

    }
})


//shared instance
static let shared = Reachability()
let reachabilityManager = Alamofire.NetworkReachabilityManager(host:   "www.google.com")
 }

 extension Reachability{

/**
 Starts network observer and manages to listen on different kind of network
 changes. Popup warning dialogs will be presented based on different kind of network status
 such as network is not reachable and once network resorts back online defined popup dialog will
 be dismissed automatically.
 **/

public func startNetworkReachabilityObserver() {

    if let status = reachabilityManager?.isReachable, status == false {
        if self.currentViewController != nil{

        }
        self.presentReachabilityPopup()
        return
    }

    reachabilityManager?.listener = { status in
        switch status {
        case .notReachable:
            if self.currentViewController != nil {
                self.presentReachabilityPopup()
            }
            break
        case .unknown :
            break
        case .reachable(.ethernetOrWiFi), .reachable(.wwan):
            if self.popup != nil ,self.currentViewController != nil {
                    self.popup?.dismiss()
            }
            break
        }
    }

    reachabilityManager?.startListening()
}


public func stopNetworkReachabilityObserver() {
    reachabilityManager?.stopListening()
}

// Configure current view controller as a network observer

public func currentViewController(_ vc: UIViewController?) {
    self.currentViewController = vc
    self.startNetworkReachabilityObserver() // Start network observer
}

// Presents an alert dialog box notifying the users concerning the network issues

private func presentReachabilityPopup() {

    self.popup = PopupDialog(title: title, message: message )
    self.popup?.addButton(settingsButton)

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3.5) {
        if self.currentViewController != nil{
            self.currentViewController?.present(self.popup!, animated: true, completion: nil)
        }
    }
}
}

And here is an example of a ViewController that needs to make the HTTP request when the network is reachable again: 这是一个ViewController的示例,当网络再次可访问时,它需要发出HTTP请求:

import UIKit
import GoogleMaps

class ExploreViewController: UIViewController, GMSMapViewDelegate{

//MARK: Properties
var posts:[Post] = []
var followers:[User] = []
var images = [UIImage]()

@IBOutlet weak var mapView: GMSMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.title = "Explore".localized
    // Configure reachability observer on this controller
    Reachability.shared.currentViewController(self)

    if Location.shared.requestAuth(){
        self.fetchPosts()
        self.setUpCameraPosition()

    }

}

The function fetchPosts() contains the HTTP requests I need to perform. 函数fetchPosts()包含我需要执行的HTTP请求。

You can set a flag when the https api network connection is started for the first time. 您可以在首次启动https api网络连接时设置标志。

var networkFlag = true

In that case your program would know that you actually started a network call. 在这种情况下,您的程序将知道您实际上已经开始了网络调用。 Next, when you are in between the request and internet connectivity is not reachable, it would give a popup. 接下来,当您处于请求之间并且无法连接Internet时,将弹出一个对话框。

Solution to trigger https call again: In code, where you check if network Reachability is true, put an if condition, and check the flag you set earlier if network connection was made. 再次触发https调用的解决方案:在代码中,检查网络可达性是否为真,放置if条件,并检查是否建立了网络连接,并设置了先前的标志。

//check for network reachability
if(reachable)
{
//check the flag set earlier which indicates network call was made
if(networkFlag)
{
//make an https call--your network call
//https:call put your method call here
}

Hope this helps :) 希望这可以帮助 :)

Screenshots: 屏幕截图:

在此处输入图片说明

Internet connection OK 可以上网

Reopening app. 重新打开应用程序。 Internet connection: WRONG ( Airplane mode ) 互联网连接:错误(飞行模式)

在此处输入图片说明在此处输入图片说明

Internet connection OK again but not fetching 互联网连接再次正常,但无法获取

在此处输入图片说明

Here is what I have modified: 这是我修改的内容:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.title = "Explore".localized

    // Configure reachability observer on this controller
    Reachability.shared.currentViewController(self)

    if Location.shared.requestAuth(){
        if (Reachability.shared.reachabilityManager?.isReachable)!{
            if self.networkFlag{
                self.fetchPosts()
                self.setUpCameraPosition()
            }
        }else{
            self.networkFlag = false
        }
    }

}

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

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