如何使用swift在设备日历中添加事件? [英] How to add an event in the device calendar using swift?

查看:31
本文介绍了如何使用swift在设备日历中添加事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道如何在设备中添加日历事件,但要使用 swift.我知道有一些用 Objective-C 制作的例子,但目前没有什么是 swift 的.非常感谢.

I would be interested in knowing how to add a calendar event in the device, but using swift. I know there are some examples made in Objective-C, but at the moment nothing in swift. Many thanks.

推荐答案

注意:如果您的应用程序崩溃 此应用程序崩溃是因为它试图在没有使用说明.应用程序的 Info.plist 必须包含一个 NSCalendarsUsageDescription 键和一个字符串值,向用户解释应用程序如何使用这些数据.,您需要将 NSCalendarsUsageDescription 添加到您的 info.plist.可以参考这里.

Note: If your app is crashing with This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSCalendarsUsageDescription key with a string value explaining to the user how the app uses this data., you'll need to add NSCalendarsUsageDescription to your info.plist. Can follow the example here.

Swift 5.0 版本

import Foundation
import EventKit

let eventStore : EKEventStore = EKEventStore()
      
// 'EKEntityTypeReminder' or 'EKEntityTypeEvent'

eventStore.requestAccess(to: .event) { (granted, error) in
  
  if (granted) && (error == nil) {
      print("granted \(granted)")
      print("error \(error)")
      
      let event:EKEvent = EKEvent(eventStore: eventStore)
      
      event.title = "Test Title"
      event.startDate = Date()
      event.endDate = Date()
      event.notes = "This is a note"
      event.calendar = eventStore.defaultCalendarForNewEvents
      do {
          try eventStore.save(event, span: .thisEvent)
      } catch let error as NSError {
          print("failed to save event with error : \(error)")
      }
      print("Saved Event")
  }
  else{
  
      print("failed to save event with error : \(error) or access not granted")
  }
}   

参考:https://gist.github.com/mchirico/d072c4e38bda61040f91

Reference : https://gist.github.com/mchirico/d072c4e38bda61040f91

这篇关于如何使用swift在设备日历中添加事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆