启动应用后,检查iOS应用互联网连接

时间:2017-06-12 10:49:59

标签: ios swift networking

我正在制作一个需要API请求的应用。如果没有任何方式的互联网连接(移动连接,wifi等),我的应用程序中没有用处。因此,只要我的应用中没有互联网连接,我就会尝试填充活动指示器视图。

我找到了非常好的Stack Overflow帖子,让我检查设备的连接状态(Check for internet connection with Swift)。

然而,这是我不确定的一件事。如果我在AppDelegate didFinishLaunchingWithOptions方法中检查iOS设备的网络连接,那么只会在应用程序启动时进行检查,对吗?我希望在没有连接时显示活动指示器视图。为了便于使用此功能,我想知道将该方法放在应用程序中哪个地方最有意义。

5 个答案:

答案 0 :(得分:3)

有一个很棒的图书馆不能使用它。它只是这个图书馆的一小部分。使用alamofire

如何吗

您只能使用此代码检查可达性。

let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")

func listenForReachability() {
    self.reachabilityManager?.listener = { status in
        print("Network Status Changed: \(status)")
        switch status {
        case .NotReachable:
            //Show error state
        case .Reachable(_), .Unknown:
            //Hide error state
        }
    }

    self.reachabilityManager?.startListening()
}

您可以将此代码用作单身人士。请记住保持可达性管理器参考。

答案 1 :(得分:1)

对于swift 3

import SystemConfiguration


public func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
        }
    }) else {
        return false
    }

    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)

    return (isReachable && !needsConnection)
}

然后检查:

if isConnectedToNetwork() 
{
// connected 

}else 
{
// not  connected 
}

答案 2 :(得分:1)

创建以下2个类文件 Singleton Class

import Foundation
import UIKit

class Constants:NSObject{


    let defaults = UserDefaults.standard
    var isNetworkon:Bool?



    override init() {
        super.init()
        CLIENTKEY = ""
    }

    class var sharedInstance: Constants {
        struct Singleton {
            static let instance = Constants()
        }
        return Singleton.instance
    }

    func checkNetwork(vc:UIViewController) -> Bool {
        NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChanged(_:)), name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil)
        Reach().monitorReachabilityChanges()


        let status = Reach().connectionStatus()
        switch status {
        case .unknown, .offline:
            print("Not connected")
            MyCustomAlert .sharedInstance.ShowAlert(vc: vc, myTitle: "No Internet Connection", myMessage: "Make sure your device is connected to the internet.")
            isNetworkon = false;
        case .online(.wwan):
            print("Connected via WWAN")
            isNetworkon = true;
        case .online(.wiFi):
            print("Connected via WiFi")
            isNetworkon = true;
        }
        return isNetworkon!;
    }

    @objc func networkStatusChanged(_ notification: Notification) {
        let userInfo = (notification as NSNotification).userInfo
        print(userInfo?.capacity)
    }


}

达到班级

    import Foundation
import SystemConfiguration


let ReachabilityStatusChangedNotification = "ReachabilityStatusChangedNotification"

enum ReachabilityType: CustomStringConvertible {
    case wwan
    case wiFi

    var description: String {
        switch self {
        case .wwan: return "WWAN"
        case .wiFi: return "WiFi"
        }
    }
}

enum ReachabilityStatus: CustomStringConvertible  {
    case offline
    case online(ReachabilityType)
    case unknown

    var description: String {
        switch self {
        case .offline: return "Offline"
        case .online(let type): return "Online (\(type))"
        case .unknown: return "Unknown"
        }
    }
}

public class Reach {

    func connectionStatus() -> ReachabilityStatus {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
        zeroAddress.sin_family = sa_family_t(AF_INET)

        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return .unknown
        }

        var flags : SCNetworkReachabilityFlags = []
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return .unknown
        }

        return ReachabilityStatus(reachabilityFlags: flags)
    }


    func monitorReachabilityChanges() {
        let host = "holidaycenterglobal.com"
        var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
        let reachability = SCNetworkReachabilityCreateWithName(nil, host)!

        SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
            let status = ReachabilityStatus(reachabilityFlags: flags)

            NotificationCenter.default.post(name: Notification.Name(rawValue: ReachabilityStatusChangedNotification),
                                            object: nil,
                                            userInfo: ["Status": status.description])

            }, &context)

        SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), RunLoopMode.commonModes as CFString)
    }

}

extension ReachabilityStatus {
    init(reachabilityFlags flags: SCNetworkReachabilityFlags) {
        let connectionRequired = flags.contains(.connectionRequired)
        let isReachable = flags.contains(.reachable)
        let isWWAN = flags.contains(.isWWAN)

        if !connectionRequired && isReachable {
            if isWWAN {
                self = .online(.wwan)
            } else {
                self = .online(.wiFi)
            }
        } else {
            self =  .offline
        }
    }
}

使用

访问它
if(Constants.sharedInstance.checkNetwork(vc: self)){
 // Call api here
}

答案 3 :(得分:0)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 ........

 internetReachable = [Reachability reachabilityForInternetConnection];
    [internetReachable startNotifier];
 [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(checkInternetConnectionStatus:)
                                                 name:kReachabilityChangedNotification object:nil];
............

}

- (void)checkInternetConnectionStatus:(NSNotification *)notice {
    // called after network status changes

    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"No active internet connection");
            break;
        }
        case ReachableViaWiFi:
        {
             NSLog(@"The internet is Connected.");
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN!");
            break;
        }
    }
}

使用apple的Reachability类

如果你想手动检查那么

 class func isConnectedToNetwork() -> Bool {

        var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress)
        {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1)
            {
                zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
            return false
        }

        let isReachable = flags == .reachable
        let needsConnection = flags == .connectionRequired

        return isReachable && !needsConnection

    }



    if self.isConnectedToNetwork() == true
{
//make API call
}
else
{
//Display alert(No internet connection)
}

答案 4 :(得分:0)

斯威夫特3: 您可以使用以下类检查网络可访问性:

import Foundation
import SystemConfiguration

public class Reachability {

    class func isConnectedToNetwork() -> Bool {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

        var flags = SCNetworkReachabilityFlags()
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
        }
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        return (isReachable && !needsConnection)
    }
}

<强>用法:

guard Reachability.isConnectedToNetwork() else {
            completion({ throw Errors.Network.noInternet(message: "No internet connection")  })
            return
}