Parsing EKEventKit
Recently I’ve been working with the iOS EKEventKit in order to access calendar events. The different entities (EKParticipants, EKEvent…) all have a description field of type String. The EKParticipant is of special interest in my app where and its description field contains a ton of information such as name, email, status, role and type that I need to use. I expected the description field would use a common format like JSON or XML, however, for some reason Apple elected to use the following format: {UUID = 0CE9-203D; name = White House; email = abc@example.com; status = 2;}; Luckily this format is consistent (and consistent across entities) which allowed me to create a simple Swift extension for extracting the required information.
extension String{
func componentFromDescription(component: String) -> String {
let descriptionArray = self.componentSeperatedByString(" ")
let value = descriptionArray[descriptionArray.indexOf(component)! + 2].
// removes trailing semicolon
stringByReplacingOccurrencesOfString(";", withString: "")
return value
}
}
The component represents the value you want to search for. In this example I am trying to find the participants email address. This extension splits the description string based on spaces and then given the component, in this case email, finds that words index in the array moves ahead 2 values to return the proper value for the component. Say you wanted to return the organizer of a calendar events email address you could:
let email = event.organizer?.description.componentFromDescription("email")
Of course, it would be much easier if Apple decided to switch the event descriptions format to a more widely used format such as JSON.