mirror of
https://github.com/samsonjs/Advanced-NSOperations.git
synced 2026-03-25 08:25:47 +00:00
81 lines
2.4 KiB
Swift
81 lines
2.4 KiB
Swift
/*
|
||
Copyright (C) 2015 Apple Inc. All Rights Reserved.
|
||
See LICENSE.txt for this sample’s licensing information
|
||
|
||
Abstract:
|
||
This file shows an example of implementing the OperationCondition protocol.
|
||
*/
|
||
|
||
import EventKit
|
||
|
||
/// A condition for verifying access to the user's calendar.
|
||
struct CalendarCondition: OperationCondition {
|
||
|
||
static let name = "Calendar"
|
||
static let entityTypeKey = "EKEntityType"
|
||
static let isMutuallyExclusive = false
|
||
|
||
let entityType: EKEntityType
|
||
|
||
init(entityType: EKEntityType) {
|
||
self.entityType = entityType
|
||
}
|
||
|
||
func dependencyForOperation(operation: Operation) -> NSOperation? {
|
||
return CalendarPermissionOperation(entityType: entityType)
|
||
}
|
||
|
||
func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
|
||
switch EKEventStore.authorizationStatusForEntityType(entityType) {
|
||
case .Authorized:
|
||
completion(.Satisfied)
|
||
|
||
default:
|
||
// We are not authorized to access entities of this type.
|
||
let error = NSError(code: .ConditionFailed, userInfo: [
|
||
OperationConditionKey: self.dynamicType.name,
|
||
self.dynamicType.entityTypeKey: entityType.rawValue
|
||
])
|
||
|
||
completion(.Failed(error))
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
`EKEventStore` takes a while to initialize, so we should create
|
||
one and then keep it around for future use, instead of creating
|
||
a new one every time a `CalendarPermissionOperation` runs.
|
||
*/
|
||
private let SharedEventStore = EKEventStore()
|
||
|
||
/**
|
||
A private `Operation` that will request access to the user's Calendar/Reminders,
|
||
if it has not already been granted.
|
||
*/
|
||
private class CalendarPermissionOperation: Operation {
|
||
let entityType: EKEntityType
|
||
|
||
init(entityType: EKEntityType) {
|
||
self.entityType = entityType
|
||
super.init()
|
||
addCondition(AlertPresentation())
|
||
}
|
||
|
||
override func execute() {
|
||
let status = EKEventStore.authorizationStatusForEntityType(entityType)
|
||
|
||
switch status {
|
||
case .NotDetermined:
|
||
dispatch_async(dispatch_get_main_queue()) {
|
||
SharedEventStore.requestAccessToEntityType(self.entityType) { granted, error in
|
||
self.finish()
|
||
}
|
||
}
|
||
|
||
default:
|
||
finish()
|
||
}
|
||
}
|
||
|
||
}
|