【问题标题】:Open calendar from Swift app从 Swift 应用程序打开日历
【发布时间】:2015-06-23 10:22:45
【问题描述】:

如何从 Swift 应用打开日历(例如按下按钮时)?或者有没有办法在应用程序的视图控制器中嵌入日历? 我想避免使用其他人编写的外部日历。谢谢!

【问题讨论】:

    标签: swift events calendar


    【解决方案1】:

    您可以使用 url scheme calshow:// 打开日历应用:

    斯威夫特 3+

    guard let url = URL(string: "calshow://") else { return }
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
    

    Swift 2 及以下

     UIApplication.sharedApplication().openURL(NSURL(string: "calshow://")!)
    

    使用 EventKit,您可以实现自己的日历。您应该阅读 Apple 网站上的 Calendar and Reminders Programming Guide

    【讨论】:

    • 我找不到适用于 Swift 的日历编程指南,仅适用于 Objective-C。我更喜欢 Swift。
    • 您可以将自己的代码翻译成swift。或者看看这个:gist.github.com/mchirico/d072c4e38bda61040f91#file-cal-swift
    • 我们可以打开像 UIApplication.sharedApplication().openURL(NSURL(string: "calshow://")!) 这样的默认提醒吗?
    • @Hoa 谢谢你的回答,让我开心!
    【解决方案2】:

    正如 HoaParis 已经提到的,您可以使用 openURL 方法调用日历。

    默认情况下,Apple 没有嵌入式日历,但您可以查看其他日历,例如 github 上提供的开源日历 CVCalendar。因此,您可以在项目中使用它,也可以检查开发人员是如何编写日历的。

    【讨论】:

      【解决方案3】:

      openURL 在 iOS10 中已弃用

      来自 Apple 在 iOS 中的 What’s New 指南,位于 UIKit 部分:

      新的 UIApplication 方法 openURL:options:completionHandler:,其中 异步执行并调用指定的完成处理程序 在主队列上(此方法替换 openURL:)。

      斯威夫特 3

      func open(scheme: String) {
        if let url = URL(string: scheme) {
          if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:],
              completionHandler: {
                (success) in
                 print("Open \(scheme): \(success)")
             })
          } else {
            let success = UIApplication.shared.openURL(url)
            print("Open \(scheme): \(success)")
          }
        }
      }
      
      // Typical usage
      open(scheme: "calshow://")
      

      Objective-C

      - (void)openScheme:(NSString *)scheme {
        UIApplication *application = [UIApplication sharedApplication];
        NSURL *URL = [NSURL URLWithString:scheme];
      
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
          [application openURL:URL options:@{}
             completionHandler:^(BOOL success) {
            NSLog(@"Open %@: %d",scheme,success);
          }];
        } else {
          BOOL success = [application openURL:URL];
          NSLog(@"Open %@: %d",scheme,success);
        }
      }
      
      // Typical usage
      [self openScheme:@"calshow://"];
      

      注意:- 不要忘记在 info.plist 文件中添加隐私使用说明。如果您尝试打开任何系统应用程序,那么在 iOS 10+ 中您需要在您的 info.plist 文件中指定隐私使用说明,否则您的应用会崩溃。

      【讨论】:

        最近更新 更多