如何使我的ios应用程序响应wifi更改事件 [英] How to make my ios app reactive to wifi change events

查看:227
本文介绍了如何使我的ios应用程序响应wifi更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果连接的wifi网络发生变化(与新的ntwk断开连接或连接到新的ntwk),是否可以通知ios应用程序(可能未激活)?

Can an ios app (possibly not active) be notified if there is a change in wifi network connected to(getting disconnected from, or getting connected to new ntwk)?

我要构建一个应用程序(即使处于非活动状态)应该在连接到特定的wifi网络时得到通知并做一些事情。

I am to build an app that (even in inactive state) should get notified when connected to a particular wifi network and do some stuff.

在android中我能够使用BroadcastReceiver实现它ios中有任何这样的设施吗?

In android i was able to achieve it using BroadcastReceiver is there any such facility in ios?

谢谢,
Praneeth。

Thanks, Praneeth.

推荐答案

iOS中有一个名为 Reachability 的类用于检测任何网络闪烁/断开/连接。

可以在这里找到可达性等级

We have a class called Reachability in iOS for detecting any network flicker/disconnection/connection.
Reachability class can be found here

用法

在项目中添加 Reachability.swift 类。


这是一个Swift 2.x版本代码而不是3.0

对于 Swift 3.x 版本,请检查我的答案此处

For Swift 3.x version check my answer here

样本 Swift 3.x
https://www.dropbox.com/sh/bph33b12tyc7fpd/AAD2pGbgW3UnqgQoe7MGPpKPa?dl=0

在你的 AppDelegate 使对象可达性 class

In your AppDelegate make an object of Reachability class

private var reachability:Reachability!

didFinishLaunchingWithOptions 为您的网络添加观察者可达性

In didFinishLaunchingWithOptions add a observer for your network reachability

//Network Reachability Notification check 

//add an observer to detect whenever network changes.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(checkForReachability), name: ReachabilityChangedNotification, object: nil)

do {self.reachability = try Reachability.reachabilityForInternetConnection()
} catch {
}

do {
try self.reachability.startNotifier()
} catch{
}

并使你的选择器功能 checkForReachability 来检测网络变化/网络断开连接 AppDelegate

And make your selector function checkForReachability to detect network changes/network disconnects in AppDelegate

func checkForReachability(notification:NSNotification) {
    let reachability = notification.object as! Reachability
    if reachability.isReachable() {
        if reachability.isReachableViaWiFi() {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    } else {
        print("Network not reachable")
    }
}

每当网络发生变化/网络中断或网络闪烁时,可达性类将触发一个 ReachabilityChangedNotification ,它最终将调用此用户定义的方法 checkForReachability 。所以,你可以在这里处理任何事情。

Whenever there is a network change/network break or whenever network will flicker, the Reachability class will fire a ReachabilityChangedNotification which will ultimately call this user defined method checkForReachability. So, you can handle anything here.

这篇关于如何使我的ios应用程序响应wifi更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆