I want to detect network changes. For example when switching from wifi to 4G or back. But my code doesn't detect these changes. I get only some output when the app has started.
I have this code:
import ReachabilitySwift
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let reachability = Reachability()!
NotificationCenter.default.addObserver(self, selector: #selector(self.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 {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
} else {
print("Network not reachable")
}
}
Did I have implemented something wrong?
The action method takes a parameter so the selector must be
#selector(reachabilityChanged(_:)) // self is not needed
And the method itself is supposed to be
func reachabilityChanged(_ notification: Notification) {
Selector is wrong
change this
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: ReachabilityChangedNotification,object: reachability)
to
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(_:),name: ReachabilityChangedNotification,object: reachability)
I hope this will work.
and also
func reachabilityChanged(note: NSNotification) {
to
func reachabilityChanged(note: NSNotification) {
name is wrong. Change
name: ReachabilityChangedNotification
to
name: NSNotification.Name.reachabilityChanged
or to
name: .reachabilityChanged
It will work.
Related
I am need detect when AVPlayer was closed.
When I am open website with with video content inside webkit and press on player AVPlayer will be opened and I am can detect this using code below:
override func viewDidLoad() {
super.viewDidLoad()
webkit.load(request)
NotificationCenter.default.addObserver(self, selector: #selector(windowDidBecomeVisibleNotification(notif:)), name: NSNotification.Name("UIWindowDidBecomeVisibleNotification"), object: nil)
}
#objc func windowDidBecomeVisibleNotification(notif: Notification) {
if let isWindow = notif.object as? UIWindow {
if (isWindow !== self.view.window) {
print("New window did open, check what is the currect URL")
}
}
}
But I can't understand how rewrite this code if I am wan't opposite action when user close this player.
I am was try rewrite this code but my attempts is fails.
Need create two notificationcented observer for detect maximize and minimize avplayer
override func viewDidLoad() {
super.viewDidLoad()
// listen for videos playing in fullscreen
NotificationCenter.default.addObserver(self, selector: #selector(onDidEnterFullscreen(_:)), name: UIWindow.didBecomeVisibleNotification, object: view.window)
// listen for videos stopping to play in fullscreen
NotificationCenter.default.addObserver(self, selector: #selector(onDidLeaveFullscreen(_:)), name: UIWindow.didBecomeHiddenNotification, object: view.window)
}
#objc func onDidEnterFullscreen(_ notification: Notification) {
print("Enter Fullscreen")
}
#objc func onDidLeaveFullscreen(_ notification: Notification) {
print("Leave Fullscreen")
}
I am trying a very simple code with NotificationCenter. But the addObserver is not getting called. Can any one of you check and let me know what i am missing. There are 2 simple class, one which post notification and another which listens to it. When i run the program, i just see "sending notification" in the console.
Thanks in advance.
Class 1:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("sending notification")
NotificationCenter.default.post(name: Notification.Name("test"), object: nil)
}
}
Class 2:
class secondvc: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("second vc")
NotificationCenter.default.addObserver(self,
selector: #selector(doThisWhenNotify(_:)),
name: Notification.Name("test"),
object: nil)
}
#objc func doThisWhenNotify(_ notification: Notification) {
print("inside notification")
}
}
If, at the time ViewController comes into existence, secondvc does not yet exist, then there is no one there to receive the posted notification and that is why you don't see the notification being received later when secondvc does come into existence.
I have 2 view controllers, one with a switch that when toggled should post the following notification. In the other view controller I have Observers which should trigger the following function which just toggles a boolean. I am not able to get the observers to work and make that function call, am I doing something wrong here? I have another Notification (Doesn't trigger with user input) that is being sent in the opposite direction which works fine.
#IBAction func switchAction(_ sender: Any) {
if switchUI.isOn {
print("Collecting Data ")
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Collect"), object: self)
}
else
{
print("Not Collecting Data")
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Do Not Collect"), object: self)
}
}
func collectDataObserver () {
//Add an Observer
NotificationCenter.default.addObserver(self, selector: #selector(CentralViewController.toggleData(notification:)), name: Notification.Name(rawValue: "Collect"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(CentralViewController.toggleData(notification:)), name: Notification.Name(rawValue: "Do Not Collect"), object: nil)
}
#objc func toggleData(notification: NSNotification) {
let isCollectData = notification.name.rawValue == "Collect"
if(isCollectData){
IsCollectingData = true
}
else
{
IsCollectingData = false
}
}
You need to call collectDataObserver() in viewDidLoad() of CentralViewController, i.e.
override func viewDidLoad() {
super.viewDidLoad()
collectDataObserver()
}
I am using this lib for checking Reachability
And below is my sample code:
override func viewWillAppear(_ animated: Bool) {
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")
}
getUserDetail()
}
#objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
internetConnectionView.isHidden = true
case .cellular:
internetConnectionView.isHidden = true
case .none:
internetConnectionView.isHidden = false
}
}
But I am not able to achieve this when i am switching wifi on and off at run time.
I don't know what I am missing.
Here is my sample project.
Faced the same issue before, to resolve it you need to declare
let reachability = Reachability()!
outside viewWillAppear function and your code will look like:
let reachability = Reachability()!
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
getUserDetail()
}
my app is based on a TabBarController with 4 ViewControllers. All 4 of them are dependent of the same data. This is why I would like to load the data at the App start in the AppDelegate.
However, how does the ViewController know, that the request is completed? For example, if there is an error (e.g. no internet connection), how do I pass this error to any of these 4 ViewController to present an alert?
Use NotificationCenter to implement (Swift 3 code):
extension Notification.Name {
static var RequestCompleted = Notification.Name(rawValue: "MyRequestIsCompleted")
static var RequestError = Notification.Name(rawValue: "MyRequestError")
}
class DataRequest {
func request() {
// if there is error:
let error = NSError(domain: "Error Sample", code: 0, userInfo: nil)
NotificationCenter.default.post(name: .RequestError, object: error)
// if the request is completed
let data = "your data is here"
NotificationCenter.default.post(name: .RequestCompleted, object: data)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(requestCompleted(_:)), name: .RequestCompleted, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(requestError(_:)), name: .RequestError, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func requestCompleted(_ notification: Notification) {
if let obj = notification.object {
print(obj)
}
}
func requestError(_ notification: Notification) {
if let obj = notification.object {
print(obj)
}
}
}