2015-06-21 61 views
0

我想調用創建事件時會得到日曆的方法。我敢肯定,這種方法意味着使用calendarWithIdentifier獲得的ID爲用calendarWithIdentifier返回單個日曆

這是我的代碼,用於創建事件並調用將獲取日曆的方法。我需要調用特定日曆

var store = EKEventStore() 

func applicationDidFinishLaunching(aNotification: NSNotification) { 
// ask for permission 
// call methods 
} 

// Create new calendar 
func createCalendar() -> EKCalendar? { 
    var calendar = EKCalendar(forEntityType: EKEntityTypeEvent, eventStore: self.store) 
    calendar.title = "Calendarname" 
    // ... 
    return calendar 
} 

func createEvent(){  
    var newEvent : EKEvent = EKEvent(eventStore: store) 
    var error : NSError? = nil 
    newEvent.title = "day off" 
    newEvent.location = "London" 

    var startDate : String = "2015-07-16"; 
    var dateFmt1 = NSDateFormatter() 
    dateFmt1.dateFormat = "yyyy-MM-dd" 
    var date1:NSDate = dateFmt1.dateFromString(startDate)!; 

    var endDate : String = "2015-07-17"; 
    var dateFmt2 = NSDateFormatter() 
    dateFmt2.dateFormat = "yyyy-MM-dd" 
    var date2:NSDate = dateFmt2.dateFromString(endDate)!; 

    newEvent.startDate = date1 
    newEvent.endDate = date2 
    newEvent.notes = "testing the event" 
    newEvent.calendar = getCalendar() 

    self.store.saveEvent(newEvent, span: EKSpanThisEvent, commit: true, error: nil) 

} 

func getCalendar() -> EKCalendar? { 
    // ... 
} 

我意識到這

func calendarWithIdentifier(_ identifier: String!) -> EKCalendar! 

這是從使用的ID返回日曆蘋果的EventKit文檔。所以我使用日曆的名稱(「日曆名稱」)作爲參數,但這似乎並不正確。它返回零。

有人可以幫助我正確地得到日曆嗎?謝謝

+0

請向我們展示如何初始化'store',因爲這是至關重要的。 –

+0

啊,對不起。我看到問題出在哪裏。回答如下 –

回答

0

我能得到它的工作。下面是getCalendar功能:

func getPSACalendar() -> EKCalendar{ 
    var calUID:String = "?" 
    var cal = store.calendarsForEntityType(EKEntityTypeEvent) as [EKCalendar] 
    for i in cal { 
     if i.title == "Calendarname" { 
      calUID = i.calendarIdentifier 
     } 
    } 
    var calendar = store.calendarWithIdentifier(calUID) 
    return calendar 
} 
0

方法calendarWithIdentifier需要一個UID而不是一個可讀的名稱。您需要從您的store檢索它們是這樣的:

var calUid:String = "?" 
for cal in store.calendarsForEntityType(EKEntityTypeEvent) { 
    if cal.title == "Calendarname" { calUid = cal.calendarIdentifier } 
} 

,以後你可以用它像

calendar = store.calendarWithIdentifier(calUid) 
+0

謝謝托馬斯。我現在可以用特定的日曆創建活動:) – Yelims01