Can't get a Navigation item with CalendarKit - calendarkit

I've tried to get it to work like so:
class CalendarViewController: DayViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "CalendarKit Demo"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Dark",
style: .done,
target: self,
action: #selector(changeStyle))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Change Date",
style: .plain,
target: self,
action: #selector(presentDatePicker))
navigationController?.navigationBar.isTranslucent = false
dayView.autoScrollToFirstEvent = true
reloadData()
}
#objc func changeStyle() {
print("clicked change style")
}
#objc func presentDatePicker() {
print("clicked date picker")
}
override func eventsForDate(_ date: Date) -> [EventDescriptor] {
let models = [Happening(startDate: Date(), endDate: Date(timeInterval: 3600, since: Date()), title: "Test Event", location: "on mother earth")]
var events = [Event]()
for model in models {
let event = Event()
event.startDate = model.startDate
event.endDate = model.endDate
let info = [model.title, model.location]
event.text = info.reduce("", {$0 + $1 + "\n"})
events.append(event)
}
return events
}
}
struct Happening {
let startDate: Date
let endDate: Date
let title: String
let location: String
init (startDate: Date, endDate: Date, title: String, location: String) {
self.startDate = startDate
self.endDate = endDate
self.title = title
self.location = location
}
}
Calendar shows up but I'm neither getting a title nor navigation items.
Looks like this for me:
What am I doing wrong here?
Many thanks for your help!
Question on the side:
Didn't yet figure out how (or if possible at all) to work with it in interface builder, to e.g. add a custom navigation element at the top when integrating it into another app. Is that possible?

starting from the last question: the Interface Builder is not currently supported. I recommend creating your CalendarController in code. Some features might work with the Interface Builder, although their support is not guaranteed.
The missing link is that the CalendarController is not embedded inside an instance of the UINavigationController. You can do so in your AppDelegate.swift or SceneDelegate.swift file:
import UIKit
import CalendarKit
#UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.makeKeyAndVisible()
let dayViewController = CalendarViewController() // Create a view controller
// Now create a NavigationController with CalendarController embedded inside
let navigationController = UINavigationController(rootViewController: dayViewController)
window?.rootViewController = navigationController
return true
}
}
Let me know, if this helps you integrate the CalendarKit. Also, I'd appreciate having a reproducible test project, so that I could investigate the problem myself.

Related

Problem Using a Switch to Set A TimeInterval

I'm have a hard time creating a user setting options. I would like the user to customize the frequency of the timer to receive the local notifications. I'm using a switch on the SystemSettingsVC to for the user to select and set the user default and I'm using the user default setting in my MainVC for the TimerInterval. My app runs but the time doesnt change. I know that the switch is working because I'm also testing the background color change.
Here is my code for my SystemSettingsVC:
...
import UIKit
import SwiftUI
import CoreData
class SettingsViewController: UIViewController {
#IBOutlet weak var timeSelection: UISegmentedControl!
let userDefaults = UserDefaults.standard
let TIME_KEY = "TIME_KEY"
let ONE_HOUR_KEY = 60.0
let THREE_HOUR_KEY = 120.0
let SIX_HOUR_KEY = 300.0
override func viewDidLoad() {
super.viewDidLoad()
updateTime()
}
func updateTime() {
let time = userDefaults.object(forKey: "TIME_KEY")
if(time as? Double == ONE_HOUR_KEY) {
timeSelection.selectedSegmentIndex = 0
let userDefaults = UserDefaults.standard
userDefaults.set(60.0, forKey: "TIME_KEY")
view.backgroundColor = UIColor.white
save()
}
else if(time as? Double == THREE_HOUR_KEY) {
timeSelection.selectedSegmentIndex = 1
let userDefaults = UserDefaults.standard
userDefaults.set(120.0, forKey: "TIME_KEY")
view.backgroundColor = UIColor.gray
save()
}
else if(time as? Double == SIX_HOUR_KEY) {
timeSelection.selectedSegmentIndex = 2
let userDefaults = UserDefaults.standard
userDefaults.set(300.0, forKey: "TIME_KEY")
view.backgroundColor = UIColor.darkGray
save()
}
}
func save() {
if let savedData = try? NSKeyedArchiver.archivedData(withRootObject: clock, requiringSecureCoding: false){
let defaults = UserDefaults.standard
defaults.set(savedData, forKey: "TIME_KEY")
}
}
#IBAction func selectTimeOfQuotes(_ sender: Any) {
switch timeSelection.selectedSegmentIndex
{
case 0:
userDefaults.set(60.0, forKey: "TIME_KEY")
save()
case 1:
userDefaults.set(120.0, forKey: "TIME_KEY")
save()
case 2:
userDefaults.set(300.0, forKey: "TIME_KEY")
save()
default:
userDefaults.set(60.0, forKey: "TIME_KEY")
save()
}
updateTime()
}
}
...
Here is the code for my view controller to where I call the user defaults, I placed let userDefaults = UserDefaults.standard in my ViewDidLoad :
'''Code''' ```
func configureAlerts() {
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications()
center.removeAllPendingNotificationRequests()
let listQuotes = quotes
let i = 1
let content = UNMutableNotificationContent()
content.title = “Inspire”
content.body = listQuotes[i].shareMessage
content.sound = UNNotificationSound.default
let alertDate = Date().byAdding(days: i)
var alertComponents = Calendar.current.dateComponents([.day, .month, .year], from: alertDate)
alertComponents.hour = 8
let userDefaults = UserDefaults.standard
typealias NSTimeInterval = Double
let thisTime:TimeInterval = userDefaults.double(forKey: "TIME_KEY")
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: thisTime, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)
center.add(request) { error in
if let error = error {
print(error.localizedDescription)
}
}
You are not showing how your Models are connected so we can't tell where the miscommunication is happening or maybe that is the issue. They are not connected.
But at a simple glance you are not rescheduling the notifications. selectTimeOfQuotes, save or updateTime do not call configureAlerts.
Something to note you have a lot of repeating code and hardcoded values that could be the source of the confusion.
BTW 120 is 2 hours not 3 idk if that is on purpose but it highlights my next point.
When you change a value you only want to do it in 1 place; if possible; so centralizing the models will help you avoid having to change things in multiple places.
For the options for your picker an enum can hold everything.
enum NotificationInterval: Double, CaseIterable, Codable{
case ONE_HOUR_KEY = 3660 //TimeInterval == seconds
case THREE_HOUR_KEY = 10800 //TimeInterval == seconds
case SIX_HOUR_KEY = 21600 //TimeInterval == seconds
func label() -> String{
var result = ""
switch self {
case .ONE_HOUR_KEY:
result = "1 hour"
case .THREE_HOUR_KEY:
result = "3 hours"
case .SIX_HOUR_KEY:
result = "6 hours"
}
return result
}
func color() -> UIColor{
var result = UIColor.label
switch self {
case .ONE_HOUR_KEY:
result = UIColor.white
case .THREE_HOUR_KEY:
result = UIColor.gray
case .SIX_HOUR_KEY:
result = UIColor.darkGray
}
return result
}
///Key for storage of user selected interval
static var userDefaultKey: String{
"TIME_KEY"
}
///Saves value to store using the `userDefaultKey`
func saveToStore(){
var mgr = UserDefaultManager()
mgr.intervalTime = self
}
///Gets value from store using the `userDefaultKey`
static func getFromStore() -> NotificationInterval{
let raw = UserDefaultManager().intervalTime
return raw
}
///Gets the index for the object in the `allCases` array
func getAllCasesIndex() -> Int?{
NotificationInterval.allCases.firstIndex(where: {
self == $0
})
}
///Gets the index for the `userDefaultKey` stored object in the `allCases` array
static func getStoredIndex() -> Int?{
NotificationInterval.getFromStore().getAllCasesIndex()
}
}
Then since you have at least 2 unrelated classes that use the value store in user defaults you can centralize that work too
///This stores and retreives userdefaults to a predetermined store
struct UserDefaultManager{
//Having a single location for this will simplify UserDefault storage
//A use case would be switching to an App Group store when you decide to support watch in the future or if you want to add Widgets
private let store = UserDefaults.standard
///User selected interval for the notifications
var intervalTime: NotificationInterval{
get{
getObject(forKey: NotificationInterval.userDefaultKey, type: NotificationInterval.self) ?? NotificationInterval.ONE_HOUR_KEY
}
set{
save(newValue, forKey: NotificationInterval.userDefaultKey)
}
}
///Saves any Codable to UserDefaults
func save<T: Codable>(_ object: T, forKey: String){
let encoder = JSONEncoder()
do{
let encoded = try encoder.encode(object)
store.set(encoded, forKey: forKey)
}catch{
print(error)
}
}
//Gets any Codable from UserDefaults
func getObject<T: Codable>(forKey: String, type: T.Type) -> T?{
guard let saved = store.object(forKey: forKey) as? Data else {
return nil
}
let decoder = JSONDecoder()
do{
let loaded = try decoder.decode(T.self, from: saved)
return loaded
}catch{
print(error)
return nil
}
}
}
Then your SettingsViewController will look like this
class SettingsViewController: UIViewController {
///Programatic use of IBOutlet
var timeSelection: UISegmentedControl!
private let quoteManager = QuoteManager()
override func viewDidLoad() {
super.viewDidLoad()
//Create control PS I dont have a storyboard setup but you can replace this with your IBOutlet and IBAction
timeSelection = UISegmentedControl(items: NotificationInterval.allCases.map({
$0.label()
}))
timeSelection.addTarget(self, action: #selector(selectTimeOfQuotes), for: .allEvents)
//Set the initial value from storage
timeSelection.selectedSegmentIndex = NotificationInterval.getStoredIndex() ?? 0
self.view.addSubview(timeSelection)
timeSelection.translatesAutoresizingMaskIntoConstraints = false
timeSelection.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
timeSelection.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
//End of programatic setup
//Set the color from storage
view.backgroundColor = NotificationInterval.getFromStore().color()
}
///Programatic use of IBAction
#objc
func selectTimeOfQuotes() {
//Identify the selected interval
let interval = NotificationInterval.allCases[timeSelection.selectedSegmentIndex]
//Save it
interval.saveToStore()
//Change the color
view.backgroundColor = interval.color()
//Change the notification
quoteManager.rescheduleQuotes()
}
}
As the last line of code shows once all the work is done you should reschedule the quotes.
I created a mini-QuoteManager since you do not show this connection. This manager can be used by any View Controller to get the quotes and maybe even reschedule when the quotes change by calling the provided method.
//Adapt this to your use case this is just a sample
///Liason for quote Storege
struct QuoteManager{
var listQuotes = ["one", "two", "three"]
private let notificationManager = NotificationManager.shared
private let userDefaultsManager = UserDefaultManager()
///Reschedules quotes
func rescheduleQuotes(count: Int = 10){
let title = "Inspire"
notificationManager.deleteNotifications()
print(#function)
for n in 1..<count+1{
print(n)
let newDate = userDefaultsManager.intervalTime.rawValue*Double(n)
//Idenfier must be unique so I added the n
notificationManager.scheduleUNTimeIntervalNotificationTrigger(title: title, body: listQuotes.randomElement()!, timeInterval: newDate, identifier: "com.yourCompany.AppName.\(title)_\(n.description)")
}
}
}
The QuoteManager calls the NotificationManager. I created a small version below.
class NotificationManager: NSObject, UNUserNotificationCenterDelegate{
//Singleton is requierd because of delegate
static let shared: NotificationManager = NotificationManager()
let notificationCenter = UNUserNotificationCenter.current()
private override init(){
super.init()
//This assigns the delegate
notificationCenter.delegate = self
requestAuthorization()
}
func scheduleUNTimeIntervalNotificationTrigger(title: String, body: String, timeInterval: TimeInterval, identifier: String, repeats: Bool = false){
print(#function)
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: repeats)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if error != nil {
print(error!)
}
self.printNotifications()
}
}
func requestAuthorization() {
print(#function)
notificationCenter.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Access Granted!")
} else {
print("Access Not Granted")
}
}
}
func deleteNotifications(){
print(#function)
notificationCenter.removeAllPendingNotificationRequests()
notificationCenter.removeAllDeliveredNotifications()
}
///Prints to console schduled notifications
func printNotifications(){
print(#function)
notificationCenter.getPendingNotificationRequests { request in
print("UNTimeIntervalNotificationTrigger Pending Notification")
for req in request{
if req.trigger is UNTimeIntervalNotificationTrigger{
print((req.trigger as! UNTimeIntervalNotificationTrigger).nextTriggerDate()?.description ?? "invalid next trigger date")
print(req.content.body)
}
}
print("UNCalendarNotificationTrigger Pending Notification")
for req in request{
if req.trigger is UNCalendarNotificationTrigger{
print((req.trigger as! UNCalendarNotificationTrigger).nextTriggerDate()?.description ?? "invalid next trigger date")
}
}
}
}
//MARK: UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.banner)
}
}
It might seem like a lot but if you focus on the SettingsViewController you will see how much simpler the whole thing becomes.
All this is working code. Just copy and paste into a .swift file.
You might have to change the UISegmentedControl since I created it programmatically but if you put the SettingsViewController in a blank storyboard it should work as is.

Swift and #objc methods: How do I transform a method so that it can be represented by #objc?

As Swift is my first programming language and also seeing that I have no Objective C experience...
I'm having difficulty understanding #objc in relation to methods.
How do I use the #objc syntax to conform to my methods?
Is there another way to select a method without using the #selector syntax?
Here is the code that I'm having difficulty with(mainly the #objc attempt at the startGame method):
import UIKit
#objc class ViewController: UITableViewController {
var allWords = [String]()
var usedWords = [String]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .add, target: self, action:
#selector(promptForAnswer))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "New
Word", style: .plain, target: self, action: #selector(startGame))
if let startWordsURL = Bundle.main.url(forResource: "start",
withExtension: "txt") {
if let startWords = try? String(contentsOf: startWordsURL) {
allWords = startWords.components(separatedBy: "\n")
}
}
if allWords.isEmpty {
allWords = ["silkworm"]
}
#objc func startGame() {
title = allWords.randomElement()
usedWords.removeAll(keepingCapacity: true)
tableView.reloadData()
{
startGame()
}
A few observations:
You do not need #objc in your view controller declaration.
The two action/selector methods should bear #objc qualifier.
I would suggest that you give these two methods descriptive names that clearly indicate that they are called when the user taps on a particular button, e.g.:
#objc func didTapNewWord(_ sender: UIBarButtonItem) {
...
}
#objc func didTapAdd(_ sender: UIBarButtonItem) {
...
}
Note, I also added a parameter to these methods. That makes it entirely unambiguous that they are button handlers. You do not need to do that, but now you can glance at the code and immediately grok what the method is for.
Obviously, you will change the code that adds these target actions accordingly:
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(didTapAdd(_:)))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "New Word",
style: .plain,
target: self,
action: #selector(didTapNewWord(_:)))
Be careful with the placement of braces. Swift allows you to declare functions inside functions. So make sure that these selector methods are instance methods of the view controller, and not, for example, private functions declared inside another function (i.e. viewDidLoad).
If you start to lose track of the braces, you can select all the code in this file and press control+i (or in Xcode menus, “Editor” » “Structure” » “Re-Indent”). If you have missing braces somewhere, the re-indentation of the code will make this jump out at you.
So pulling that together, you get something like:
// ViewController.swift
import UIKit
class ViewController: UITableViewController {
var allWords = [String]()
var usedWords = [String]()
override func viewDidLoad() {
super.viewDidLoad()
configureButtons()
fetchData()
}
}
// MARK: - Actions
extension ViewController {
#objc func didTapNewWord(_ sender: UIBarButtonItem) {
startGame()
}
#objc func didTapAdd(_ sender: UIBarButtonItem) {
...
}
}
// MARK: - UITableViewDataSource
extension ViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
...
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
}
}
// MARK: - Private utility methods
private extension ViewController {
func configureButtons() {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(didTapAdd(_:)))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "New Word",
style: .plain,
target: self,
action: #selector(didTapNewWord(_:)))
}
func fetchData() {
guard
let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt"),
let startWords = try? String(contentsOf: startWordsURL).components(separatedBy: "\n"),
!startWords.isEmpty
else {
allWords = ["silkworm"]
return
}
allWords = startWords.filter { !$0.isEmpty }
}
func startGame() {
title = allWords.randomElement()
usedWords.removeAll(keepingCapacity: true)
tableView.reloadData()
}
}
A few final observations on my code sample (not directly related to your question, but just to explain why structured it like I did):
I like to put methods into extensions, so that they are in logical groups. This makes it easier to follow what is going on at a glance. You can also collapse/expand these extensions so that while you are editing, you can focus on the relevant code.
The MARK comments just puts nice section headers in the Xcode jump bar, again, making it easier to jump about in one’s code.
I personally don't put anything in the action methods except a call to some method with the “business logic”. This separates the “view” code (the handling of the button) from the business logic. Some day, you may start using view models or presenter objects, so embracing this separation of responsibilities now will make that eventual transition easier. It will also make it easier to write unit tests when you get around to that (e.g. you write unit tests for the "start game" logic, not not the tapping of a button).
I think you have syntax error in the #objc method. It should be:
#objc
func functionName() {
}
for you it will be:
#objc
func startGame() {
title = allWords.randomElement()
usedWords.removeAll(keepingCapacity: true)
tableView.reloadData()
}

Swift: Unable to assign function return value to UILabel

I have a situation where a string returned from a function call is being assigned to a UILabel text. However, the UILabel is carrying an empty value. If I were to assign a static string viz. "this is testing" to the UILabel directly it works. Within the function, I can print the return value
import Foundation
import Firebase
import UIKit
class checkLocation{
var items = [addedItems]()
func getLocationOfItem(textFieldText: (String)) -> String{
let itemLet = addedItems()
var location = ""
Database.database().reference().child("item").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
//itemLet.setValuesForKeys(dictionary)
itemLet.itemName = dictionary["itemName"] as? String
itemLet.itemLocation = dictionary["itemLocation"] as? String
itemLet.itemImageUrl = dictionary["itemImageUrl"] as? String
itemLet.itemTS = dictionary["itemTS"] as? String
itemLet.id = dictionary["id"] as? String
if(textFieldText == itemLet.itemName){
location = itemLet.itemLocation!
print(location)
}
}
}, withCancel: nil)
return location
}
}
Calling program
import UIKit
import Firebase
class checkLocationViewController: ViewController {
#IBOutlet weak var itemNameInLctn: UITextField!
#IBOutlet weak var itemLocationLbl: UILabel!
var items = [addedItems]()
var strLocation = "";
override func viewDidLoad() {
super.viewDidLoad()
refItems = Database.database().reference().child("item")
}
#IBAction func getLocation(_ sender: UIButton) {
self.strLocation = checkLocation().getLocationOfItem(textFieldText: itemNameInLctn.text!)
itemLocationLbl.text = strLocation
//itemLocationLbl.text = strLocation
//print(itemNameInLctn.text)
}
}
Any help?
The func getLocationOfItem(textFieldText: (String)) -> String is correctly returning location that has the initial value of "“.
The issue that you are facing is that, you are calling an an async task from firebase within a sync function call.
You can refactor the method call to return you the required string asynchronously be making the following changes:
func getLocationOfItem(textFieldText: String, completion: #escaping (_ itemLocation: String?) -> Void){
let itemLet = addedItems()
Database.database().reference().child("item").observe(.childAdded, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {
return completion(nil)
}
itemLet.itemName = dictionary["itemName"] as? String
itemLet.itemLocation = dictionary["itemLocation"] as? String
itemLet.itemImageUrl = dictionary["itemImageUrl"] as? String
itemLet.itemTS = dictionary["itemTS"] as? String
itemLet.id = dictionary["id"] as? String
if(textFieldText == itemLet.itemName){
completion(itemLet.itemLocation)
} else {
completion(nil)
}
}, withCancel: nil)
}
/// Usage
#IBAction func getLocation(_ sender: UIButton) {
guard let itemNameInLocation = itemNameInLctn.text else { return }
getLocationOfItem(textFieldText: itemNameInLocation) { [weak self] (itemLocation) in
self?.strLocation = itemLocation
self?.itemLocationLbl.text = itemLocation
}
}
Note:
Please be advised that the completion handler will be called every time that a value is added under the item path in your firebase database.
I would highly recommend refactoring further in this case to use the observeSingleEventthat firebase provides.
Please see link below for documentation about said method:
https://firebase.google.com/docs/database/ios/read-and-write#read_data_once
If this was your intention then its the best choice.

Change UIButton's state from a different View Controller - Swift 4.2

I have gameCenterButton in VC1. Its purpose is to take the user to Game Center's Leaderboards where they can see High Scores. If the user decides to authenticate with Game Center, then I want to change gameCenterButton's state (un-grey and enable). In my GameKitHelper class I have these:
func authenticateLocalPlayer() {
GKLocalPlayer.local.authenticateHandler =
{ (viewController, error) in
self.gameCenterEnabled = false
if viewController != nil {
self.authenticationViewController = viewController
NotificationCenter.default.post(name: NSNotification.Name(
GameKitHelper.PresentAuthenticationViewController),
object: self)
} else if GKLocalPlayer.local.isAuthenticated {
self.gameCenterEnabled = true
}
}
}
extension GameKitHelper: GKGameCenterControllerDelegate {
func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismiss(animated: true, completion: nil)
}
}
In VC1 I have this:
#IBOutlet weak var gameCenterButton: UIButton!
#IBAction func gameCenter(_ sender: UIButton) {
GameKitHelper.sharedInstance.showGKGameCenterViewController(viewController: self)
}
I'm thinking that inside of extension GameKitHelper I can do ...
if gameCenterEnabled == true {
gameCenterButton.isEnabled = true // How do I allow for this?
gameCenterButton.alpha = 1 // How do I allow for this?
How do I allow gameCenterButton state to change outside of it's class. Is there something I need to do in AppDelegate?
Put var gameCenterEnabled = false outside (above) of your GameKitHelper class, thus making it "global". You will likely be prompted to remove the self. in self.gameCenterEnabled = false and in self.gameCenterEnabled = true. Do so.
Now, you can reference gameCenterEnabled in VC1's class and change gameCenterButton's state like this:
// code to determine gameCenterButton's state based on gameCenterEnabled's status
if gameCenterEnabled == false {
self.gameCenterButton.isEnabled = false
self.gameCenterButton.alpha = 0.37
} else {
self.gameCenterButton.isEnabled = true
self.gameCenterButton.alpha = 1
}

how to change dock icon using setContentView to display one big character in mac os x

I want to change the dock icon of an app into one big character like an "A" or "B" for example using swift or objective C
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var dockView: NSView!
#IBOutlet weak var dockText: NSTextField!
let appDockTile = NSApplication.sharedApplication().dockTile
func prepareDock(){
appDockTile.contentView = dockView
appDockTile.display()
}
func changeText(){
dockText.stringValue = "B"
appDockTile.display()
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
prepareDock()
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
#IBAction func btnChangeText(sender: AnyObject) {
changeText()
}
}
my two cents for OSX swift 4.x:
(make it flash..)
...
self.HeartBeatTimer = Timer.scheduledTimer(withTimeInterval: DELTA_T, repeats: true, block: { (t: Timer) in
let name = colored ? "heartbeat" : "heartbeat_red"
let image = NSImage(named: name)
let appDockTile = NSApplication.shared.dockTile
appDockTile.contentView = NSImageView(image: image!)
appDockTile.display()
}