In our iOS app we have a timepicker widget to book appointments. This has worked fine for a long time. We just changed iOS developer and when he rebuilt the app the timepicker is broken for some reason we cannot tell. Has something changed recently in XCode/iOS that could explain why the layout suddenly is broken?
How it was
How it is now
This is the code responsible:
This timepicker is based on the standard iOS UIDatePicker.
class TimePickerController: UIViewController {
#IBOutlet weak var notAvailableLbl: UILabel!
#IBOutlet weak var fromPicker: UIDatePicker!
#IBOutlet weak var toPicker: UIDatePicker!
#IBOutlet weak var switchNotAvailable: UISwitch!
var object: EventElement?
var delegate:TimePickerControllerDelegate?
var name: DEFAULT_AVAILABILITY_CONST!
var startTime,endTime: Date?
var isFromSettings:Bool = false
var isNotAvailable: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = AppColors.Primary
switchNotAvailable.setOn(isNotAvailable, animated: true)
switchChanged(switchNotAvailable)
setPickerLocale(withIdentifier: "en_GB")
setPickerTimezone(withIdentifier: "UTC")
initPickerDates()
if object?.type == EVENT_CONST.lunch{
switchNotAvailable.isHidden = true
notAvailableLbl.isHidden = true
}else{
switchNotAvailable.isHidden = false
notAvailableLbl.isHidden = false
}
}
func setPickerLocale(withIdentifier locale: String) {
// Changing to 24 hrs
let local = NSLocale(localeIdentifier: locale) as Locale
fromPicker.locale = local
toPicker.locale = local
}
func setPickerTimezone(withIdentifier timeZone: String) {
//set timezone
fromPicker.timeZone = TimeZone.init(identifier: timeZone)
toPicker.timeZone = TimeZone.init(identifier: timeZone)
}
func initPickerDates() {
if let obj = object {
let startTime = obj.start.split(separator: "Z")
let endTime = obj.end.split(separator: "Z")
if(startTime.first == endTime.first)
{
fromPicker.date = getTimeFromString(stringTime: String("08:00"))
toPicker.date = getTimeFromString(stringTime: String("22:00"))
}
else{
fromPicker.date = getTimeFromString(stringTime: String(startTime.first ?? "08:00"))
toPicker.date = getTimeFromString(stringTime: String(endTime.first ?? "22:00"))
}
}else {
if let start = startTime,let end = endTime {
if(start == end)
{
// 8.00 to 22.00
fromPicker.date = start
toPicker.date = end.dateByAddingHours(hours: 14)
}
else{
fromPicker.date = start
toPicker.date = end
}
}
}
}
func getTimeFromString(stringTime: String) -> Date
{
let local = NSLocale(localeIdentifier: "en_GB") as Locale
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.locale = local
dateFormatter.timeZone = TimeZone.init(identifier: "UTC")
let date = dateFormatter.date(from: stringTime) ?? Date()
print(date)
return date
}
#IBAction func btnDone(_ sender: Any) {
print(fromPicker.date)
print(toPicker.date)
updateEvent()
}
func updateEvent() {
var start = fromPicker.date.timeDisplay + "Z"
var end = toPicker.date.timeDisplay + "Z"
var createdDate:String = ""
var id:String = ""
var name:String = ""
if object == nil {
start = fromPicker.date.ISOISO8601StringForAvailability + "Z"
end = toPicker.date.ISOISO8601StringForAvailability + "Z"
createdDate = Date().toString(format: DateFormat.Custom("yyyy-MM-dd'T'HH:mm:ss")) + "Z"
id = UUID().uuidString.lowercased()
name = self.name.rawValue
}
else{
createdDate = object?.created ?? ""
id = object?.id ?? ""
name = (object?.name.rawValue) ?? ""
}
print("switch state",switchNotAvailable.isOn)
if switchNotAvailable.isOn {
if let startT = startTime,let endT = endTime {
let startDt = "08:00Z".formatDateWithTime(referenceDate: startT)
let endDt = "08:00Z".formatDateWithTime(referenceDate: endT)
start = startDt!.toString(format: DateFormat.Custom("yyyy-MM-dd'T'HH:mm"),timezone: "UTC") + "Z"
end = endDt!.toString(format: DateFormat.Custom("yyyy-MM-dd'T'HH:mm"),timezone: "UTC") + "Z"
}
else{
start = "08:00Z"
end = "08:00Z"
}
}
ActivityIndicator().showIndicator(backgroundColor: nil)
print("start and end date : ",start," ",end)
let type:String?
if isFromSettings == true{
type = object?.type.rawValue
}
else{
type = "AVAILABILITY_PATCH"
}
print(type ?? "AVAILABILITY_PATCH")
APICalls().updateAvailability(start: start, end: end, name: name, type: type ?? "AVAILABILITY_PATCH", created: createdDate,id: id ) { (response) in
ActivityIndicator().hideIndicator()
if let result = response
{
let res = Event.init(dictionary: result as? NSDictionary ?? [:])
DatabaseManager.getInstance().saveAvailability(object: res)
self.delegate?.didSelectTime(from: self.fromPicker.date, to: self.toPicker.date)
self.navigationController?.popViewController(animated: true)
}
}
}
To disable this time picker style, you have to add below line.
fromPicker.preferredDatePickerStyle = .wheels
In IOS 14 we have to define DatePickerStyle.
Please write these two lines in initPickerDates() method to set picker wheel style
fromPicker.preferredDatePickerStyle = .wheels
toPicker.preferredDatePickerStyle = .wheels
In IOS 14, we have multiple styles for date pickers. So this is the default behavior in iOS 14.
You just need to add the following line in the initPickerDates() method.
fromPicker.preferredDatePickerStyle = .wheels
toPicker.preferredDatePickerStyle = .wheels
Related
I have a code for my calculator
How could I do so that when the user would enter the numbers he would be separated by a space automatically?
I've been trying to find an answer for a long time, but nothing fits that it was displayed right away
var currentInput: Double {
get {
return Double (displayResultLabel.text!)!
}
set {
let value = "\(newValue)"
let ValueArray = (value.components(separatedBy:"."))
if ValueArray[1] == "0" {
displayResultLabel.text = "\(ValueArray[0])"
} else {
displayResultLabel.text = "\(newValue)"
}
stillTyping = false
}
}
#IBAction func numberPressed(_ sender: UIButton) {
let number = sender.currentTitle!
if stillTyping {
if (displayResultLabel.text?.characters.count)! < 14 {
displayResultLabel.text = displayResultLabel.text! + number
}
} else {
displayResultLabel.text = number
stillTyping = true
}
}
Then what happened:
#IBAction func numberPressed(_ sender: UIButton) {
let number = sender.currentTitle!
if stillTyping {
if (displayResultLabel.text?.characters.count)! < 14 {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let newNumber = NSNumber(value: Double(displayResultLabel.text! + number)!)
displayResultLabel.text = formatter.string(from: newNumber)
}
} else {
displayResultLabel.text = number
stillTyping = true
}
}
Error
var stillTyping = false
var dotIsPlaced = false
var firstOperand: Double = 0
var secondOperand: Double = 0
var operationSign: String = ""
It is better to accumulate your value in a separate string that doesn't have the formatting applied rather than using the text field as your data model. You can then format the decimal and display it in the label as required using a NumberFormatter:
let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
var currentInput: String = "0" {
didSet {
self.displayResultLabel?.text = self.currentDisplay
}
var currentValue: Double {
return Double(self.currentInput) ?? 0
}
var currentDisplay: String {
return formatter.string(from: NSNumber(value:self.currentValue)) ?? "0"
}
func addDigit(_ digit: Int) {
if currentInput.count < 14 {
let newValue = self.currentValue * 10 + Double(digit)
self.currentInput = "\(newValue)"
}
}
#IBAction func numberPressed(_ sender: UIButton) {
guard let digit = Int(sender.currentTitle!) else {
return
}
self.addDigit(digit)
}
This is what NumberFormatters are for
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
if let newNumber = formatter.number(from: displayResultLabel.text! + number){
displayResultLabel.text = formatter.string(from: newNumber)
}
Note that NumberFormatters go both ways, and you can (and probably should) use them to parse numbers from strings, too
Apologies for this one, I'm sure that I'm missing a swift fundamental here.
I have a navigation app that I'm working on in swift.
Earlier on I made it as a single view and have changed it to a tab bar controller application.
In the background the location manager does its work and when is does the update locations work it displays the lat and long on a label.
When the app was a single view app this was no problem however now that it is a tab bar app, as soon as I change to a different tab when the location manager function fires it crashes the app with the following code (which I suspect means nothing much on its own) EXC_BREAKPOINT (code=1, subcode=0x10039bb54
I strongly suspect that I am doing something fundamentally wrong with trying to update a label on a view controller that is not active at the time.
distanceLabel.text = "Currently \(distanceText) from destination"
lbl_location.text = String(mylat) + ", " + String(mylong)
I have copied in all of my code below only taking out a few sensitive bits so that you can see the big picture.
Open to constructive feedback as to better coding practices.
Thanks
Bruce
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
//in the original view controller which has now been incorporated into tabs
#IBOutlet weak var distanceLabel: UILabel!
#IBOutlet weak var lbl_location: UILabel!
//on a new view controller on another tab
#IBOutlet weak var employeeNameSetup: UITextField!
#IBOutlet weak var employeeNumberSetup: UITextField!
#IBOutlet weak var contactNumberSetup: UITextField!
#IBOutlet weak var managerNameSetup: UITextField!
#IBOutlet weak var managerEmailSetup: UITextField!
#IBOutlet weak var adminPasswordSetup: UITextField!
#IBAction func setAppDefaults(_ sender: Any) {
if (employeeNameSetup.text?.isEmpty)! || (employeeNumberSetup.text?.isEmpty)! || (contactNumberSetup.text?.isEmpty)! || (managerNameSetup.text?.isEmpty)! || (managerEmailSetup.text?.isEmpty)!{
let noGoAlert = UIAlertController(title: "Insufficient Fields Filled out", message: "Only the Password field is optional, please fill out all other fields before pressing button", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .default, handler: nil)
noGoAlert.addAction(defaultAction)
present(noGoAlert, animated: true, completion: nil)
}
else{
let defaults = UserDefaults.standard
defaults.set(employeeNameSetup.text, forKey: "employeeName")
defaults.set(employeeNumberSetup.text, forKey: "employeeNumber")
defaults.set(contactNumberSetup.text, forKey: "contactNumber")
defaults.set(managerNameSetup.text, forKey: "managerName")
defaults.set(managerEmailSetup.text, forKey: "managerEmail")
}
}
#IBAction func submit_button(_ sender: Any) {
uploadData()
}
let location_process = CLLocationManager()
var mylat :Double = 0
var mylong :Double = 0
var destination = CLLocation(latitude: #####, longitude: #####)
var distanceToDest :Int = 0
var dburl = NSURL(string: "#########")
let contact_name = "#####"
let contact_number = "#####"
let unique_id = "###"
let employee_number = "#####"
var distanceText = ""
var runOnce = false
var isAdmin = false
var adminPassword = "#######"
func sendEmail(messageText: String){
let url = URL (string: "########")
let session = URLSession.shared
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let paramtosend = #########
request.httpBody = paramtosend.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request)
task.resume()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let mylocation = locations[0]
mylat = mylocation.coordinate.latitude
mylong = mylocation.coordinate.longitude
distanceToDest = Int(mylocation.distance(from: destination))
if distanceToDest > 1000 {
distanceText = String(Int(distanceToDest/1000))
distanceText = distanceText + " km"
}
else if distanceToDest < 100 {
let current_date_time = Date()
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
formatter.dateFormat = "HH:mm dd MMM yyyy"
formatter.timeZone = TimeZone.autoupdatingCurrent
let timestamp = formatter.string(from: current_date_time)
if !runOnce {
sendEmail(messageText: "\(contact_name); Employee \(employee_number) Arrived at destination \(destination.coordinate.latitude), \(destination.coordinate.longitude) at \(timestamp)")
}
distanceText = String(distanceToDest)
distanceText = distanceText + " m"
runOnce = true
}
else {
distanceText = String(distanceToDest)
distanceText = distanceText + " m"
}
distanceLabel.text = "Currently \(distanceText) from destination"
lbl_location.text = String(mylat) + ", " + String(mylong)
uploadData()
}
#IBAction func uploadData()
{
var httprequest = URLRequest(url: dburl! as URL)
httprequest.httpMethod = "POST"
var dataString = "####" // starting POST string with a secretWord
// the POST string has entries separated by &
dataString = dataString + "&unique_id=" + unique_id
dataString = dataString + "&mylat=" + String(mylat) // add items as name and value
dataString = dataString + "&mylong=" + String(mylong)
dataString = dataString + "&contact_name=" + contact_name
dataString = dataString + "&contact_number=" + contact_number
dataString = dataString + "&employee_number=" + employee_number
let current_date_time = Date()
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
formatter.dateFormat = "HH:mm dd MMM yyyy"
formatter.timeZone = TimeZone.autoupdatingCurrent
let timestamp = formatter.string(from: current_date_time)
dataString = dataString + "×tamp=" + timestamp
// convert the post string to utf8 format
let dataD = dataString.data(using: .utf8) // convert to utf8 string
do
{
// the upload task, uploadJob, is defined here
let uploadJob = URLSession.shared.uploadTask(with: httprequest, from: dataD!)
//let uploadJob = URLSession.shared.uploadTask(with: httprequest, from: dataD)
uploadJob.resume()
}
}
override func viewDidLoad() {
super.viewDidLoad()
location_process.delegate = self
location_process.pausesLocationUpdatesAutomatically = false
location_process.desiredAccuracy = kCLLocationAccuracyBest
location_process.requestWhenInUseAuthorization()
location_process.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled()
{
location_process.distanceFilter = 50
location_process.allowsBackgroundLocationUpdates = true
location_process.startUpdatingLocation()
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Hi I am trying to schedule a local notification to fire at 9:00am on weekdays (mon - fri) and cant seem to find any documentation on how to do this. Here is my code so far:
#IBAction func scheduleLocal(sender: UIButton) {
guard let settings = UIApplication.sharedApplication().currentUserNotificationSettings() else { return
}
if settings.types == .None {
let ac = UIAlertController(title: "Cant Schedule", message: "No Permission", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
return
}
let notification = UILocalNotification()
notification.fireDate = NSDate()
notification.alertBody = "Come Exercise"
notification.alertAction = "Exercise Time"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["customField1": "w00t"]
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
and in viewDidLoad:
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
This is my class example you can use it as you want , i also support Arabic language by translate Arabic number to English .
//
// notification.swift
// NSFetchController Pro
//
// Created by Mr.Geeker on 08/02/15.
// Copyright (c) 2015 X2coder. All rights reserved.
//
import UIKit
class notification {
func createNotification(#hour:String, day:String, msgBody:String)->Bool
{
if(self.checkifNotificationOnOrOff())
{
//println("\(araToString(hour))")
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var convertedTime:String = ""
var testDate:NSDate = NSDate()
var timeFormat:NSString = dateFormatter.stringFromDate(testDate)
// Get the range of date (AM OR PM )
var amRange:NSRange = timeFormat.rangeOfString(dateFormatter.AMSymbol)
var pmRange:NSRange = timeFormat.rangeOfString(dateFormatter.PMSymbol)
var is24h:Bool = (amRange.location == NSNotFound && pmRange.location == NSNotFound)
if is24h {
araToString(hour)
}else{
var dateFormatter2:NSDateFormatter = NSDateFormatter()
dateFormatter2.dateFormat = "HH:mm"
var hourDate:NSDate = dateFormatter2.dateFromString(hour)!
var pmAmDateString:NSString = dateFormatter2.stringFromDate(hourDate)
convertedTime = pmAmDateString
println(convertedTime)
}
var hourAndMiOnly:NSArray = convertedTime.componentsSeparatedByString(":")
var onlyHour:Int = 0
var onlyMinuts:Int = 0
for var i:Int = 0; i < 2; i++ {
for thimes in hourAndMiOnly
{
if i == 0
{
onlyMinuts = thimes.integerValue
}
if i == 1 {
// we should add -1 before the class
onlyHour = (thimes.integerValue)
if onlyHour < 1
{
onlyHour = 00
}
break
}
}
}
let DaysDic = [0:"None",1:"Sunday",2 :"Monday",3 :"Tuesday",4 :"Wednesday",5 :"Thursday",6 :"Friday",7 :"Saturday"]
var ConvertDayToInt:Int?{
for (key,value) in DaysDic
{
if value == day
{
return key
}
}
return nil
}
//println("Hour is \(onlyHour) And Minut \(onlyMinuts) AND Day \(ConvertDayToInt)")
let date = NSDate()
var userInfo: [NSObject : AnyObject]?
var createCalender:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var dateComponenet:NSDateComponents = createCalender.components(NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.WeekCalendarUnit, fromDate: date)
dateComponenet.weekday = ConvertDayToInt!
dateComponenet.hour = onlyHour
dateComponenet.minute = onlyMinuts
var fireDateToRun:NSDate = createCalender.dateFromComponents(dateComponenet)!
var notificationClass:UILocalNotification = UILocalNotification()
notificationClass.alertBody = msgBody
notificationClass.fireDate = fireDateToRun
notificationClass.soundName = UILocalNotificationDefaultSoundName
notificationClass.repeatInterval = NSCalendarUnit.WeekCalendarUnit
notificationClass.timeZone = NSTimeZone.defaultTimeZone()
notificationClass.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
UIApplication.sharedApplication().scheduledLocalNotifications = [notificationClass]
}else{
// call protocol function not support notification
}
return true
}
func araToString(numericString:String)->NSString
{
var nsMutString:NSMutableString = NSMutableString(string: numericString)
let ArabicString:NSString = "١٢٣٤٥٦٧٨٩:"
let EnglishString:NSString = "123456789:"
for ( var i:Int = 0 ; i < ArabicString.length ; i++)
{
var a:NSString = ArabicString.substringWithRange(NSMakeRange(i, 1))
var w:NSString = EnglishString.substringWithRange(NSMakeRange(i, 1))
nsMutString.replaceOccurrencesOfString(a, withString: w, options: NSStringCompareOptions.LiteralSearch, range:NSMakeRange(0, nsMutString.length))
}
return nsMutString
}
func deleteAll(){
let appnoti = UIApplication.sharedApplication()
let delArray = appnoti.scheduledLocalNotifications
if delArray.count > 0
{
appnoti.cancelAllLocalNotifications()
}
}
func checkifNotificationOnOrOff()->Bool
{
let systemVer:String = UIDevice.currentDevice().systemVersion
var finalFloat:Float = NSString(string: systemVer).floatValue
if finalFloat < 8 {
return false
}else{
return true
}
}
}
I have an NSArray, inside I have a var of kind NSDate
which give this format "timeStamp = "2015-08-18 16:58:31"
I want to compare in all the array the date only 2015-08-18
compare it and if same date only the first one show full NSDate
and the rest with same date show only the time on UI
This is what I did so far:
func getAllMessages() -> NSArray{
var allMessages = self.mutableSetValueForKey("messages").allObjects as NSArray
let timeStampSortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: true)
var sortByTime = allMessages.sortedArrayUsingDescriptors([timeStampSortDescriptor])
println("\(sortByTime)")
return sortByTime
}
screen shot
http://i.stack.imgur.com/wcsSz.jpg
After some research i did made a solution as following
First this extension is very good and my way is depends on it
https://stackoverflow.com/a/27369380/5188737
If anyone have better solution or clean
I will appreciate if you can post it here
I'm sorry there's no comments
func loadMessages(){
if chatRoom!.messages.count > 0{
var i = 0
var tempMsgDate:NSDate?
var chatMessage:ChatMessage?
for message in chatRoom!.getAllMessages(){
let msg = message as! Message
if i == 0{
tempMsgDate = msg.timeStamp
chatMessage = ChatMessage(incoming: msg.income, text: msg.message, sentDate: convertNSDateToString(msg.timeStamp))
i++
}else{
//if the tempMsgDate (which is the first of the same
//date in the nsarray)
if checkIfSameDayDate(tempMsgDate!,date2: msg.timeStamp){
var tempDate = msg.timeStamp.time
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.dateFromString(tempDate)
println("loadmessages method: \(date?.time)")
chatMessage = ChatMessage(incoming: msg.income, text: msg.message, sentDate: msg.timeStamp.time)
}else{//after he got to different date it save it as
//first of same date to follow
tempMsgDate = msg.timeStamp
chatMessage = ChatMessage(incoming: msg.income, text: msg.message, sentDate: convertNSDateToString(msg.timeStamp))
}
}
var msgCollection:[ChatMessage] = [ChatMessage]()
msgCollection.append(chatMessage!)
chat.loadedMessages.append(msgCollection)
}
}
}
func convertNSDateToString(date:NSDate) -> String{
let dateString = date.date + " " + date.time
println("in convert: \(dateString)")
return dateString
}
func checkIfSameDateFromSendMSGAndReciveMSG(date:NSDate) -> Bool{
for message in chatRoom!.getAllMessages(){
let msg = message as! Message
if msg.timeStamp.date == date.date{
return true
}
}
return false
}
//checks if the date1 equal to date2
func checkIfSameDayDate(date1:NSDate,date2:NSDate) -> Bool{
if date1.date == date2.date{
return true
}
return false
}
I'm trying to call a method that will get a calendar when creating an event. This method I'm sure is meant to use calendarWithIdentifier which gets the ID of the
Here's my code for the creating the event and calling the method that will get the calendar. I need to call a specific calendar
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? {
// ...
}
I'm aware of this
func calendarWithIdentifier(_ identifier: String!) -> EKCalendar!
which is from Apple's EventKit Documentation used to return a calendar by id. So I'm using the Calendar's name ("Calendarname") as the argument, but this doesn't seem to be right. It's returning nil.
Can someone help me get the Calendar correctly? Thank you
The method calendarWithIdentifier expects a UID rather than a readable name. You need to retrieve them from your store like this:
var calUid:String = "?"
for cal in store.calendarsForEntityType(EKEntityTypeEvent) {
if cal.title == "Calendarname" { calUid = cal.calendarIdentifier }
}
and later you can use it like
calendar = store.calendarWithIdentifier(calUid)
I was able to get it working. Here's the getCalendar function now:
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
}