Skip to content

Instantly share code, notes, and snippets.

@ryanmasondavies
Created November 21, 2014 22:22
Show Gist options
  • Save ryanmasondavies/8da9d340f00852d9fd49 to your computer and use it in GitHub Desktop.
Save ryanmasondavies/8da9d340f00852d9fd49 to your computer and use it in GitHub Desktop.
Swift: UIViewController Access Control
//
// AccessController.swift
// FriendChain
//
// Created by Ryan Davies on 20/11/2014.
// Copyright (c) 2014 Ryan Davies. All rights reserved.
//
import UIKit
enum Requirement {
case Authentication(PFUser?)
func isSatisfied() -> Bool {
switch self {
case .Authentication(let user):
return user!.isAuthenticated()
}
}
}
protocol AccessControl {
class func requirementsForSegue(identifier: String) -> [Requirement]
}
class AccessController {
func canViewController(viewController: UIViewController, performSegueWithIdentifier identifier: String) -> Bool {
// this line explodes, so need to rethink pattern
if let subject = viewController as? AccessControl {
let requirements = viewController.dynamicType.requirementsForSegue(identifier)
for requirement in requirements {
if requirement.isSatisfied() == false {
return false
}
}
}
return true
}
}
// IN THEORY, THIS WOULD BE COOL:
class ViewController: UIViewController, AccessControl {
class func requirementsForSegue(identifier: String) -> [Requirement] {
if let segueIdentifier = SegueIdentifier(rawValue: identifier) {
switch segueIdentifier {
case .ShowProfile:
// require the current user to be authenticated!
return [Requirement.Authentication(User.currentUser())]
case .SignUp:
return [Requirement.Authentication(User.currentUser())]
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment