NEVPNManager check is connected after restart the app? - ios

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

Related

stopVPNTunnel is not disconnecting the VPN connection in iOS

I have implemented one successful vpn connection. But When i close and Open app while the VPN is connected, then i can't disconnect the VPN.
public func connectVPN() {
//For no known reason the process of saving/loading the VPN configurations fails.On the 2nd time it works
Log.d(message: "connectVPN")
NSLog("ConnectVPN")
self.vpnManager.loadFromPreferences(completionHandler: self.vpnLoadHandler)
NotificationCenter.default.addObserver(forName: NSNotification.Name.NEVPNStatusDidChange, object: nil , queue: nil) {
notification in
let nevpnconn = notification.object as! NEVPNConnection
let status = nevpnconn.status
self.vpnDelegate?.checkNES(status: status)
}
}
public func disconnectVPN() ->Void {
Log.d(message: "Disconnect VPN Called")
Log.d(message: "Log Disconnect VPN Called")
print("vpnManager:disconnectVPN \(self.vpnManager.connection) ") // object available
self.vpnManager.connection.stopVPNTunnel()
}
I could not find out why it is not disconnecting.
Call stopVPNTunnel() inside loadFromPreferences closure.
NEVPNManager.shared().loadFromPreferences { error in
assert(error == nil, "Failed to load preferences: \(error!.localizedDescription)")
NEVPNManager.shared().connection.stopVPNTunnel()
}

How do i check the wifi switch in between my data uploading

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

update the Viewcontroller based on Network Availblilty in swift

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

App crashes on Launch in Airplane Mode

I am currently using Ashley Mill's Reachability Class. If the application launches with network connectivity then I am able to toggle between connectivity availability without any issues and able to display a network connectivity Alert Controller properly. However if the application is launched when the app starts without internet connection/on airplane mode it abruptly crashes.
override func viewDidLoad()
{
super.viewDidLoad()
setUpReachability (nil)
}
func setUpReachability(hostName: String?)
{
do
{
let reachability = try hostName == nil ? Reachability.reachabilityForInternetConnection() : Reachability(hostname: hostName!)
self.reachability = reachability
try! self.reachability?.startNotifier()
}
catch ReachabilityError.FailedToCreateWithAddress(let address)
{
print("\(address)")
return
} catch {}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability)
}
func reachabilityChanged(notification: NSNotification)
{
let reachability = notification.object as! Reachability
if reachability.isReachable()
{
if reachability.isReachableViaWiFi()
{
connected = true
}
else
{
connected = true
}
}
else
{
let alert = UIAlertController( title: "No Network Connection Available", message:"Try Again", preferredStyle: .Alert)
alert.addAction(UIAlertAction( title: "Will Do!" , style: .Default) { _ in } )
presentViewController ( alert, animated: true ) {}
connected = false
}
}
What can be done to allow the iPhone application to launch and display an alert saying there is no network connection rather than abruptly crash?
Error Message:
fatal error: unexpectedly found nil while unwrapping an Optional value
But I would think that reachability changed would catch this in the else statement and pop the error message up?
Shouldn't the else in the reachability.isReachableViaWiFi() if statement be:connected = false ?
The error was that I was in fact trying to download data at the launch of the app instead of first allowing the initialization of the app to finish to then send a request to the server to access information.

Get notification from Reachability when the app is not running

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.

Resources