I need an event or like an observer while switching between wifi networks or wifi to cellular and vice versa. Can anybody help me with it? I am uploading a video file and while uploading I am switching between wifi networks or auto-switch between cellular to wifi. So need an event for the same.
It is included in the example on the Reachability github page
//declare this property where it won't go out of scope relative to your listener
let reachability = try! Reachability()
//declare this inside of viewWillAppear
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
And the method
#objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
print("Reachable via WiFi")
case .cellular:
print("Reachable via Cellular")
case .unavailable:
print("Network not reachable")
}
}
To check whether the device is connected or not, you can use NWPathMonitor, like this:
import Network
struct ConnectivityMonitor {
static let monitor = NWPathMonitor()
static func setup() {
ConnectivityMonitor.monitor.pathUpdateHandler = { path in
//path.isExpensive tells you whether the user is using cellular data as opposed to wifi. "true" if cellular data.
if path.status == .satisfied {
//Connected
} else {
//Not connected
}
}
let queue = DispatchQueue(label: "Monitor")
ConnectivityMonitor.monitor.start(queue: queue)
}
}
Related
I am working on iOS application. I have to call api while user online and offline.
I have viewcontroller 1 class and there I am calling api.
override func viewDidLoad() {
super.viewDidLoad()
if let reachability = manager.sharedInstance.internetReachability {
NotificationCenter.default.addObserver( self, selector: #selector( self.reachabilityChanged),name: Notification.Name.reachabilityChanged, object: reachability )
}
}
#IBAction func callAPI(_ sender: Any) {
self.callApi()
}
func callApi() {
//call api
}
#objc private func reachabilityChanged( notification: NSNotification ) {
let reachability = notification.object as! Reachability
switch reachability.connection {
case .wifi:
self.callApi()
case .cellular:
self.callApi()
case .none:
case .unavailable:
}
}
The issue is here if I am in viewcontroller 2 class and app comes to online, The api is not getting trigger in Viewcontroller 1.
The requirement is, If user is offline and comes to online, user is in viewcontroller 2, I have to call that api in viewcontroller 1 without any action, Just by tracking internet is active and I have to call API.
Any suggestions?
The problem is if there is no instance of the view controller 1 existed at the time of connectivity changes, you have no chance to call the API.
If you have no reason having to keep the calling API inside the view controller 1 when connectivity changes, I suggest moving the observer to somewhere that can alive throughout your app's lifetime. The simplest place is in AppDelegate.
What I did,
if no internet then store data in database
make a function in appdelegate e.g callApi()
when app comes to online (internet on) reachabilityChanged( notification: NSNotification ) call, So my code looks like
#objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
print("Reachable via WiFi")
appDel.UploadUserRecord() //callApi()
case .cellular:
print("Reachable via Cellular")
appDel.UploadUserRecord() //callApi()
case .unavailable:
print("Network not reachable")
case .none:
print("Network none")
}
}
I'm Used Reachability class globally
I am new to ios development, i have to check the internet network based on that i will show the view controllers, i used this code for test the network.
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
// do some tasks..
}
else {
}
with this code i am getting network network status, my aim is when the application launch time if don't have network show the default page, if enable the network automatically it will show the main page please help me.
try this code
let reachability = Reachability()!
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
#objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
print("Reachable via WiFi")
case .cellular:
print("Reachable via Cellular")
case .none:
print("Network not reachable")
}
}
I am using DropboxSwiftApi to upload images and pdf files to my dropbox account, I want to give user the ability to select images and pdfs even when he/she has no internet connection, so they are uploaded automatically when internet is available . Which approach would be better to achieve this? is there anything like background upload? Can i add this data to some pool_list so internet is available it will be uploaded. Please Help. Thanks.
You can use Reachability.swift to observe your internet connection.
If internet is not available you can temporarily store data in database as soon as internet connection is available you can upload all data to the server
//declare this property where it won't go out of scope relative to your listener
let reachability = Reachability()!
//declare this inside of viewWillAppear
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(_:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
When internet is available this method will be called
func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
print("Reachable via WiFi")
case .cellular:
print("Reachable via Cellular")
case .none:
print("Network not reachable")
}
}
Hope this solves your problem.
I coding a VPN tool, using the NetworkExtension framework. I can connect IPSec through NEVPNManager.sharedManager, and can grab the notification when VPN connect status changed. But when I kill the app, and reopen it, the NEVPNManager.Connect.Status always Zero, than means can't display the correct connect state. How to solve it?
William Sterling comment does make sense, & it works for me,
Before adding observer for NEVPNStatusDidChange load preferences for VPN Manager object like bellow,
override func viewDidLoad() {
super.viewDidLoad()
self.vpnManager.loadFromPreferences { (error) in
if error != nil {
print(error.debugDescription)
}
else{
print("No error from loading VPN viewDidLoad")
}
}
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.VPNStatusDidChange(_:)), name: NSNotification.Name.NEVPNStatusDidChange, object: nil)
}
Try this:
func viewDidLoad() {
// Register to be notified of changes in the status. These notifications only work when app is in foreground.
notificationObserver = NSNotificationCenter.defaultCenter().addObserverForName(NEVPNStatusDidChangeNotification, object: nil , queue: nil) {
notification in
print("received NEVPNStatusDidChangeNotification")
let nevpnconn = notification.object as! NEVPNConnection
let status = nevpnconn.status
self.checkNEStatus(status)
}
}
func checkNEStatus( status:NEVPNStatus ) {
switch status {
case NEVPNStatus.Invalid:
print("NEVPNConnection: Invalid")
case NEVPNStatus.Disconnected:
print("NEVPNConnection: Disconnected")
case NEVPNStatus.Connecting:
print("NEVPNConnection: Connecting")
case NEVPNStatus.Connected:
print("NEVPNConnection: Connected")
case NEVPNStatus.Reasserting:
print("NEVPNConnection: Reasserting")
case NEVPNStatus.Disconnecting:
print("NEVPNConnection: Disconnecting")
}
}
The above code should generate the following messages when running the app with VPN already connected:
checkNEStatus: NEVPNConnection: Invalid
viewDidLoad: received NEVPNStatusDidChangeNotification
checkNEStatus: NEVPNConnection: Connected
I used Reachability library for checking that th iPhone reachs to the internet. If the app is running, It receive fine the notification. My question is how to make the app receive the notification when It isn't running?
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AutoCheckin.reachabilityChanged(_:)),name: ReachabilityChangedNotification,object: reachability)
do{
try reachability?.startNotifier()
}catch{
print("could not start reachability notifier")
}
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
if reachability.isReachable() {
if reachability.isReachableViaWiFi() {
logMessage("Reachable via WiFi: ")
print("Reachable via WiFi: ")
} else {
logMessage("Reachable via Cellular: ")
print("Reachable via Cellular")
}
self.pushLocalNotification()
}else{
logMessage("Network not reachable")
print("Network not reachable")
}
}
And also I need to send a local notification if there is an internet.