0

I have a class to check internet connection that i found here: Check for internet connection with Swift

In my methods i use it:

     override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if Reachability.isConnectedToNetwork() == false {
            let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
            alert.show()
            return
        }
    }

but can i make a decorator or something to write something like:

@check_internet_connection
override func viewWillAppear(animated: Bool) {

}

or for example use it for all methods in class:

@check_internet_connection
class MyClass: UIViewController {
    ...
}
Community
  • 1
  • 1
Arti
  • 7,356
  • 12
  • 57
  • 122

2 Answers2

0

Inheritance Approach

You can create ReachabilityAwareViewController as base class.

class ReachabilityAwareViewController: UIViewController{

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if Reachability.isConnectedToNetwork() == false {
            // your code goes here
        }
    }
}

and create subclass that inherit all behaviour from ReachabilityAwareViewController.

class myViewController: ReachabilityAwareViewController{
    // ..
}

Composition Approach

This approach looks more like the decorator. Using protocol extension

protocol ReachabilityAware{
    func checkReachibility()
}

extension ReachabilityAware where Self: UIViewController{

    func checkReachibility(){
        if Reachability.isConnectedToNetwork() == false {
            let alertController = UIAlertController(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: .Alert)
            let okAction = UIAlertAction(title: "OK", style: .Cancel){ action in }
            alertController.addAction(okAction)
            presentViewController(alertController, animated: true, completion: nil)
        }
    }
}

class myViewController: UIViewController, ReachabilityAware{

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        checkReachibility()
    }
}
nRewik
  • 8,958
  • 4
  • 23
  • 30
0

In Swift these are called Attributes. Currently (as of Swift 2.1), you cannot define your own.

Why not write a global function to handle this?

// In global scope
func check_internet_connection() -> Bool {
    if Reachability.isConnectedToNetwork() == false {
        let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
        alert.show()
        return false
    } else {
        return true
    }
}

…

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    if !check_internet_connection() { return }
}
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117