簡體   English   中英

如何在將 EKEvent.identifier 保存到 EKEventStore 后立即返回?

[英]How to return the EKEvent.identifier right after saving it to the EKEventStore?

我想編寫一個方法,它接受一個事件對象,它有一個名稱和一個日期參數。 該函數請求訪問/檢查對事件存儲的訪問,創建帶有參數的 EKEvent,將其保存到存儲中,然后將事件標識符作為字符串返回。

到目前為止,我遇到了麻煩,因為 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
    }
}

我找到了解決辦法!

而不是使用.requestAccess(to:completion:)來創建事件。 我只在我明確需要訪問 EKEventStore 時使用它。 並檢查我是否打開.authorizationStatus(for:)

代碼來了:

import EventKit

class EventHelper {

    // MARK: Properties
    var store: EKEventStore!


    // MARK: Methods
    /*
     This thing I got from here     https://stackoverflow.com/questions/28379603/how-to-add-an-event-in-the-device-calendar-using-swift more or less
     */
    func createCalendarEvent(for event: Event) -> String? {
        // Act base upon the current authorisation status
        switch EKEventStore.authorizationStatus(for: .event) {
        case EKAuthorizationStatus.notDetermined:
            // Ask for permission
            requestAuthorisationToCalendar()

            // And try again
            return try createCalendarEvent(for: event)

        case EKAuthorizationStatus.denied:
            print("Access to the Event Store was denied.")

        case EKAuthorizationStatus.restricted:
            print("Access to the Event Store was restricted.")

        case EKAuthorizationStatus.authorized:
            // Create a new event
            let newEvent = EKEvent(eventStore: 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)
            print("Saved event with ID: \(String(describing: newEvent.eventIdentifier))")
                return newEvent.eventIdentifier
            } catch let error as NSError {
                print("Failed to save event with error: \(error)")
                return nil
            }
        }
    }

    // MARK: Privat Methods
    private func requestAuthorisationToCalendar() {
        store.requestAccess(to: .event) { (granted, error)  in
            if (granted) && (error == nil) {
                DispatchQueue.main.async {
                    print("User has granted access to calendar")
                }
            } else {
                DispatchQueue.main.async {
                    print("User has denied access to calendar")
                }
            }    
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM