我有进口Reachability.h的.m文件,就像写在这里为我的雨燕的项目,但开始后观察者/事件处理程序将不会被调用,为什么呢?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: nil)
let hostReachability = Reachability(hostName: "www.apple.com");
hostReachability.startNotifier();
return true
}
func reachabilityChanged(note: NSNotification) { // <- DOES NOT GET CALLED
let reachability: Reachability = note.object as Reachability;
if(reachability.currentReachabilityStatus() != .NotReachable) {
}
}
Run Code Online (Sandbox Code Playgroud)
Yat*_*B L 11
Reachability返回的对象是一个自动释放的对象,因此它已取消分配,因此通知不会触发.您可以通过保持对它的强引用来解决问题.
创建一个属性来保存Reachability对象
var reachability:Reachability?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name:kReachabilityChangedNotification, object: nil)
reachability = Reachability(hostName: "www.apple.com");
reachability?.startNotifier();
return true
}
Run Code Online (Sandbox Code Playgroud)
这将解决您的问题.
观察者的名称从ReachabilityChangedNotification更改为kReachabilityChangedNotification.注意"k"