如何模拟EKEventStore
问题描述:
我有一个简单的函数来请求访问,以便在日历中添加事件。如何模拟EKEventStore
typealias BoolCallback = (Bool) ->()
class SimpleCalendar {
let store: EKEventStore
init(store: EKEventStore = EKEventStore()) {
self.store = store
}
/// Request access to EventKit API for Calendar intergration
///
/// - Parameter callback: returns if access was recived or denied
func requestAccess(callback: @escaping BoolCallback) {
let status = EKEventStore.authorizationStatus(for: .event)
switch status {
case .authorized:
callback(true)
// case .notDetermined: //should ask for access
// case .denied, .restricted: //should open a ask permission view
default:
store.requestAccess(to: .event) { accessGranted, _ in
DispatchQueue.main.async {
callback(accessGranted)
}
}
}
}
}
有没有办法模拟EKEventStore
获取状态?
我也有一个简单的函数来检查日历是否存在。
func doesCalendarExist(name: String) -> Bool {
let calendars = store.calendars(for: .event)
if calendars.contains(where: { $0.title == name }) {
return true
}
return false
}
有没有办法嘲笑存储对象为获得store.calendars
感谢
我切换
let status = EKEventStore.authorizationStatus(for: .event)
到
let status = type(of: store).authorizationStatus(for: .event)
答
我想你可以在这里使用DI。取而代之的内创造店无功SimpleCalendar你可以为它创建构造函数参数店把责任:EKEventStore,并将它传递有:
init(store: EKEventStore = EKEventStore()) {/*code*/}
这样,您就可以通过自己的模仿对象。
覆盖类方法有什么问题?我现在无法检查,但假设这是可能的。
任何方式,其他选项是嘲笑你可以创建协议与您正在使用的所有方法 - EventStoreProtocol。这些方法必须是在EKEventStore我想,这样你就可以很容易地使用扩展采纳:
extension EKEventStore: EventStoreProtocol {}
然后强似EKEventStore来构造,通过有EventStoreProtocol。
你的模拟对象将不子类,而只是类确认到该协议,实现所有所需的方法
对于类的方法,而不是EKEventStore.authorizationStatus使用类型(组成:存储).authorizationStatus
我能想到的关于你的问题的唯一的事情是下一个:
extension EKEventStore {
func eventAuthorizationStatus() -> EKAuthorizationStatus {
return EKEventStore.authorizationStatus(for: .event)
}
}
然后OVERR在子类中使用这个方法。因为EKEventStore是NSObject,它应该工作(但我不确定)。这种方式,而不是使用类型(的:store).authorizationStatus您可以调用此方法。
但问题是 - 你真的需要这个吗?你不能就这样离开吗?如果没有,检查这一做法,并告诉我,如果它的工作原理
请检查新的更新 –