我想编写一个方法,该方法带有一个事件对象,该方法具有一个名称和一个日期参数。该函数请求访问/检查对事件存储的访问,使用参数创建EKEvent,将其保存到存储中,然后将Eventidentifier作为String返回。
到目前为止,我遇到了麻烦,因为eventStore.requestAccess(To :)方法闭包转义了,并且在实际创建EKEvent对象并将其保存到存储之前返回了字符串。
我的方法位于EventHelper类的代码中,该类是EventStore和Apples EKEventStore之间的抽象层。
import EventKit
struct Event {
var name: String
var date: Date
var id: String?
}
class EventHelper {
// MARK: Properties
var store: EKEventStore!
// MARK: Methods
func createCalendarEvent(for event: Event) -> String? {
// Prepare a place to store the eventIdentifier
var identifier : String?
// Get acces to the eventstore
store.requestAccess(to: .event) { (granted, error) in
if (granted) && (error == nil) {
print("Calendar event creation.")
print("granted: \(granted)")
print("error: \(String(describing: error))")
// Create a new event kit event
let newEvent = EKEvent(eventStore: self.store)
newEvent.title = event.name
newEvent.startDate = event.date
// Create a timeinterval for the end date
let twoHourTimeInterval = TimeInterval(exactly: 7200)
newEvent.endDate = event.date.addingTimeInterval(twoHourTimeInterval!)
// choose the calender the event should be assinged to
newEvent.calendar = self.store.defaultCalendarForNewEvents
// try to save the new event in the event store
do {
try self.store.save(newEvent, span: .thisEvent, commit: true)
identifier = newEvent.eventIdentifier
print("Saved event with ID: \(String(describing: newEvent.eventIdentifier))")
// The event gets created and the ID is printed to the console but at a time when the whole function already has returned (nil)
} catch let error as NSError {
print("Failed to save event with error: \(error)")
}
}
else {
print("Failed to save event with error \(String(describing: error)) or access not granted")
}
}
print("new Event: \(String(describing: identifier))")
return identifier
}
}
答案 0 :(得分:1)
我找到了解决方法!
不要使用componentDidMount() {
// One signal notification settings
OneSignal.configure();
OneSignal.setLogLevel(5, 0); // adb logcat debug (5) logs
OneSignal.init('xxxxxxxxxxxx');
OneSignal.inFocusDisplaying(2);
OneSignal.addEventListener('ids', this.onIds);
OneSignal.getPermissionSubscriptionState((status) => {
if(status.userId)
// update userID using props
});
}
onIds = (device) => {
const userId = device.userId;
if(userId)
// update userID using props
OneSignal.removeEventListener('ids', this.onIds);
}
来创建事件。我仅在明确需要访问EKEventStore的情况下使用它。
并检查我是否打开react-native-onesignal: 3.2.11
react-native: 0.57.4
react: 16.6.0-alpha.8af6728
代码如下:
.requestAccess(to:completion:)