Reputation: 61880
I need to make some things in my app, once device is connected to wifi. It is not about "does it connected to wifi?", instead "tell me when device connected to wifi, while it was offline before?"
In other words I need to response on event when iPhone just connected to internet with any way.
Is it possible with AFNetworking
or maybe custom API?
Upvotes: 1
Views: 138
Reputation: 61880
Simple usage for AFNetworking
:
Add observer:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("networkDidChangeStatus"), name: AFNetworkingReachabilityDidChangeNotification, object: nil)
Implement custom Selector
:
func networkDidChangeStatus() {
if AFNetworkReachabilityManager.sharedManager().reachable {
print("connected")
} else {
print("disconnected")
}
}
Start monitoring:
AFNetworkReachabilityManager.sharedManager().startMonitoring()
Upvotes: 0
Reputation: 71862
You can use Reachability.
In the sample code you will find:
import UIKit
let useClosures = false
class ViewController: UIViewController {
@IBOutlet weak var networkStatus: UILabel!
let reachability = Reachability.reachabilityForInternetConnection()
override func viewDidLoad() {
super.viewDidLoad()
if (useClosures) {
reachability?.whenReachable = { reachability in
self.updateLabelColourWhenReachable(reachability)
}
reachability?.whenUnreachable = { reachability in
self.updateLabelColourWhenNotReachable(reachability)
}
} else {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
}
reachability?.startNotifier()
// Initial reachability check
if let reachability = reachability {
if reachability.isReachable() {
updateLabelColourWhenReachable(reachability)
} else {
updateLabelColourWhenNotReachable(reachability)
}
}
}
deinit {
reachability?.stopNotifier()
if (!useClosures) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
}
}
func updateLabelColourWhenReachable(reachability: Reachability) {
if reachability.isReachableViaWiFi() {
self.networkStatus.textColor = UIColor.greenColor()
} else {
self.networkStatus.textColor = UIColor.blueColor()
}
self.networkStatus.text = reachability.currentReachabilityString
}
func updateLabelColourWhenNotReachable(reachability: Reachability) {
self.networkStatus.textColor = UIColor.redColor()
self.networkStatus.text = reachability.currentReachabilityString
}
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
if reachability.isReachable() {
updateLabelColourWhenReachable(reachability)
} else {
updateLabelColourWhenNotReachable(reachability)
}
}
}
Upvotes: 1