我有大量活动想要批量保存到日历中。用户选择哪个日历。他们可以选择导出到 iCloud 日历或 Google 日历。导出到 iCloud 日历时,一切都运行顺利。没问题。然而,当导出到 Google 日历时,我遇到了一些奇怪的问题。要保存的事件数量约为 60-90 个事件。我使用下面提供的功能在后台导出日历事件。该操作运行良好,并且在记录期间包含所有事件,并且在迭代事件时它们都收到了事件标识符。
然而,在任何情况下,大约有 5-10 个事件没有同步到 Google 日历,也没有显示在手机日历上。对于每个导出,未显示的事件都不同,因此不是事件本身有问题。我尝试了很多不同的方法,但没有成功。
我尝试过的:
- 删除了后台操作。
- 删除了日历状态回调。
- 将函数移到闭包之外并直接调用它。
- 删除了@autorelease。
- 检查 EKEventStore 和 EKCalendar 在整个操作过程中是否处于活动状态。
你们有人知道对此有一个很好的解释吗?我检查了谷歌是否对保存有任何限制,但根据文档,在短时间内导入 10 000 多个事件时,日历可能会变成只读,而我什至没有接近这一点。
我希望得到任何反馈。这真让我抓狂。正如我之前所说,iCloud 导出效果很好。
这是我的导出代码:
import UIKit
import EventKit
struct Activity {
var title : String!
var startDate : NSDate!
var endDate : NSDate!
}
class CalendarManager: NSObject {
class func saveToCalendarInBackground(activities: [Activity], eventStore: EKEventStore, calendar: EKCalendar, calendarStatus: (status: String!, progress: Float!) -> (), completion:(success: Bool!, error: NSError!) -> ()) -> Void {
//Run the operations on another thread (not main), but do UI updates on the main thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
if activities.count > 0 {
var formatter = NSDateFormatter()
autoreleasepool {
//Save duties to calendar
for (index, activity) in enumerate(activities) {
//Update status
let progress = Float(index + 1) / Float(activities.count)
//Return callbacks on main thread
dispatch_sync(dispatch_get_main_queue(), {
calendarStatus(status: "Saving \(index+1) of \(activities.count)", progress: progress)
})
//Save activity
var event = EKEvent(eventStore: eventStore)
event.calendar = calendar
event.title = activity.title
event.startDate = activity.startDate
event.endDate = activity.endDate
var saveEventError : NSError?
if eventStore.saveEvent(event, span: EKSpanThisEvent, commit: false, error: &saveEventError) {
println("Activity saved. Commit needed.")
}
else {
println("Save error: \(saveEventError?.localizedDescription)")
}
//
}
}
//Save all pending events
var saveAllEventsError : NSError?
if eventStore.commit(&saveAllEventsError) == true{
println("Save all events complete!")
//Return callbacks on main thread
dispatch_async(dispatch_get_main_queue(), {
println("Calendar Save completion.")
calendarStatus(status: "Calendar save complete!", progress: 1)
completion(success: true, error: nil)
})
return
}
else {
//Return callbacks on main thread
dispatch_async(dispatch_get_main_queue(), {
completion(success: false, error: NSError(domain: "Calendar Save Error", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey : "Error batch saving events: \(saveAllEventsError?.localizedDescription)"]))
})
println("Save all events ERROR: \(saveAllEventsError?.localizedDescription)")
return
}
}
else {
//Return callbacks on main thread
dispatch_async(dispatch_get_main_queue(), {
completion(success: false, error: NSError(domain: "Calendar Save Error", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey : "Found no events to save!"]))
})
return
}
})
}
}