Adding an ICS iCal file to the iOS Calendar in Swift

  English  

Loading an iCal file over the webcal protocol in iOS, is a fairly straight-forward process if you know the caveats. Since I’ve found almost zero documentation on this, I decided to share my findings with the world.

The following is required for iOS to even want to deal with your iCal file:

  1. The protocol of the URL has to be webcal://
  2. The URL has to end with .ics
  3. The server spewing out the iCal file should send a HTTP 200 OK response
  4. The content-type header should be set to text/calendar and an applicable charset (eg. charset=utf-8)
  5. The content-disposition header should be set to attachment; filename="calendar.ics"

If you’re using NodeJS to present the ics file, I highly recommend the ical-generator package written by Sebastian Pekarek.

In the code snippet below we load the ics file over the webcal protocol after the user presses a button. Opening the url in the background will prompt the user to subscribe to the calendar, once the iCal file has been parsed with success by iOS.

@IBAction func addToCalendar(_ sender: Any) {

    let url = URL(string: "webcal://api.server.com/example.ics")!

    UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
        print("Open webcal: \(success)")
    })

}

Below you can see a few dialog options the user could be presented with.

Bonus: you can set the calendar name with the following lines in an iCal file:

NAME:My Calendar
X-WR-CALNAME:My Calendar

That’s all there is to it, really. Please let me know if you found this to be helpful for your app, any and all feedback is welcome.