Показване на предупреждение за състояние на достъпност

Използвам Reachability на ashleymills: https://github.com/ashleymills/Reachability.swift/releases

В Xcode 7 написах функция за показване на предупреждение за състояние на достъпност.

Сигналът обаче никога не се появява.

Ето моят код:

let reachability = Reachability.reachabilityForInternetConnection()
reachability!.whenReachable = { reachability in
    if reachability.isReachableViaWiFi() {
        let alertController = UIAlertController(title: "Alert", message: "Reachable via WiFi", preferredStyle: .Alert)
        let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)

        alertController.addAction(defaultAction)

        self.presentViewController(alertController, animated: true, completion: nil)
    }
    else {
        let alertController = UIAlertController(title: "Alert", message: "Reachable via Cellular", preferredStyle: .Alert)
        let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)

        alertController.addAction(defaultAction)

        self.presentViewController(alertController, animated: true, completion: nil)
    }
}

reachability!.whenUnreachable = { reachability in
    let alertController = UIAlertController(title: "Alert", message: "Please connect to internet", preferredStyle: .Alert)
    let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)

    alertController.addAction(defaultAction)

    self.presentViewController(alertController, animated: true, completion: nil)
}

reachability!.startNotifier()

person GPH    schedule 04.10.2015    source източник
comment
Мисля, че проблемът може да е, че затварянето не се извиква в главната нишка, така че опаковането на вашия UIAlertController код в dispatch_async(dispatch_get_main_queue()) { … } трябва да го разреши   -  person Ashley Mills    schedule 05.10.2015


Отговори (1)


Моля, заменете кода си с този и той трябва да работи, може да има грешка в Reachability след swift 1.2, така че тук просто проверявам дали е достъпен или не и мисля, че е достатъчно.

Според мен не е нужно да проверявате дали това е wifi или клетъчна мрежа. Причината зад предупреждението не се показва, защото не влиза в блоковете за показване на предупреждението:

let useClosures = false

class ViewController: UIViewController {

    let reachability = Reachability.reachabilityForInternetConnection()

    override func viewDidLoad() {
        super.viewDidLoad()

        if (useClosures) {
            reachability?.whenReachable = { reachability in
                print("Reachable")
            }
            reachability?.whenUnreachable = { reachability in
                print("Unreachable")
            }
        } else {
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
        }

        reachability?.startNotifier()

        // Initial reachability check when the app starts
        if let reachability = reachability {
              dispatch_async(dispatch_get_main_queue()) {
            if reachability.isReachable() {
                let alertController = UIAlertController(title: "Alert", message: "Reachable", preferredStyle: .Alert)
                let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)

                alertController.addAction(defaultAction)

                self.presentViewController(alertController, animated: true, completion: nil)
            } else {
                let alertController = UIAlertController(title: "Alert", message: "Please connect to internet", preferredStyle: .Alert)
                let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)

                alertController.addAction(defaultAction)

                self.presentViewController(alertController, animated: true, completion: nil)
            }
            }
        }
    }

    deinit {

        reachability?.stopNotifier()

        if (!useClosures) {
            NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
        }
    }


    func reachabilityChanged(note: NSNotification) {
        let reachability = note.object as! Reachability
        // Initial reachability check while surfing in the app
        if reachability.isReachable() {
            let alertController = UIAlertController(title: "Alert", message: "Reachable", preferredStyle: .Alert)
            let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)

            alertController.addAction(defaultAction)

            self.presentViewController(alertController, animated: true, completion: nil)

        } else {
            let alertController = UIAlertController(title: "Alert", message: "Please connect to internet", preferredStyle: .Alert)
            let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)

            alertController.addAction(defaultAction)

            self.presentViewController(alertController, animated: true, completion: nil)
        }
    }
}

Забележка: Казахте, че имате webView в приложението си, не забравяйте, че трябва да опресните или актуализирате, когато е достъпно.

person AaoIi    schedule 04.10.2015
comment
Благодаря ти! Просто тествайте кода си, но предупреждението никога не се показва. - person GPH; 04.10.2015
comment
@GPH, къде поставяш този код? в viewDidLoad ? btw в моя случай се показва! - person AaoIi; 04.10.2015
comment
Да, във функцията viewDidLoad на ViewController.swift - person GPH; 04.10.2015
comment
показва се само при стартиране на приложението, ако интернет връзката се промени след стартиране на приложението, не показва предупреждението. Btw уеб изгледът не може да покаже нищо след добавяне на кода. - person GPH; 04.10.2015
comment
Поправям някои от проблемите си и добавям вашия код. показва грешка, както е показано по-долу - person GPH; 05.10.2015
comment
/Volumes/web/MAC/untitled folder/hksalonhk/hksalonhk/SecondViewController.swift:23:13: Инициализирането на неизменна стойност 'useClosures' никога не е използвано; обмислете замяната с присвояване на „_“ или премахването му /Volumes/web/MAC/untitled folder/hksalonhk/hksalonhk/SecondViewController.swift:32:21: Декларацията на клас не може да затвори над стойността „useClosures“, дефинирана във външния обхват /Volumes/web /MAC/untitled folder/hksalonhk/hksalonhk/SecondViewController.swift:71:22: Декларацията на клас не може да се затвори над стойността 'useClosures', дефинирана във външния обхват - person GPH; 05.10.2015
comment
Вече всичко е наред, много ви благодаря! Преди направих грешка. - person GPH; 05.10.2015