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

时间:2018-10-20 08:53:07

标签: ios swift alamofire

我正在构建一个需要向API发出HTTP请求的应用。我想处理网络连接状态,因此当网络不可访问时,它将显示一个弹出对话框,而当网络可访问时,将弹出一个对话框。

当前,我能够做到这一点,问题是,由于再次可以访问网络而关闭弹出窗口时,我不知道如何(或在哪里)再次发出HTTP请求。

我已经建立了一个单例课程来处理可达性:

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)
        }
    }
}
}

这是一个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()

    }

}

fetchPosts()函数包含我需要执行的HTTP请求。

2 个答案:

答案 0 :(得分:0)

您可以在首次启动https api网络连接时设置一个标志。

var networkFlag = true

在这种情况下,您的程序将知道您实际上已经开始了网络呼叫。 接下来,当您处于请求之间并且无法访问Internet时,将弹出一个对话框。

再次触发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
}

希望这会有所帮助:)

答案 1 :(得分:-2)

屏幕截图:

enter image description here

互联网连接正常

重新打开应用程序。互联网连接:错误(飞行模式)

enter image description here enter image description here

互联网连接可以,但不能获取

enter image description here

这是我修改的内容:

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
        }
    }

}