Advanced-NSOperations/Earthquakes/Operations/CalendarCondition.swift
2022-02-16 22:16:09 -08:00

81 lines
2.4 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this samples 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()
}
}
}