Swift 1.2 Singleton causes App to not launch - swift

I have created a singleton for my iOS application to access certain things globally. When I launch the application int the simulator or on my iPhone/iPad however, it sticks on the launch screen, and never reaches the appdelegates didFinishLaunchingWithOptions method (I tried to println in it). If I remove the singleton and just leave the methods and variables as global it works perfectly. Which leaves me to believe it's the singleton causing this crash. Here's the code I use. If I comment out the lines currently commented out it works perfectly like this "gameName" anywhere in my code but I know this isn't great practice so if I uncomment them and access the singleton like this "Global.sharedInstance.gameName" is when the app does not launch. I do call this singleton many times throughout the app so I'm not sure if that's the issue.
//class Global {
//
// static let sharedInstance = Global()
//
// private init() {
// println("Global Singleton created");
// }
private var optionsModel = OptionsModel()
private var gamesModel = GamesModel()
private var savesModel = SavesModel()
var device = (UIApplication.sharedApplication().delegate as! AppDelegate).device
var screenWidth = (UIApplication.sharedApplication().delegate as! AppDelegate).window!.bounds.width
var screenHeight = (UIApplication.sharedApplication().delegate as! AppDelegate).window!.bounds.height
var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var PI = CGFloat(M_PI)
var gameIndex = 0
var player: AudioPlayer!
var gameLevel = ""
func loadSong(name: String, loops: Int) {
player = AudioPlayer(name: name, loopCount: loops)
}
func playAduio(fileName: String) {
loadSong("\(fileName)Audio", 0)
player!.play()
}
var gameName: String {
get {
return gamesModel.getName(gameIndex)
}
}
var gameDescription: String {
get {
return gamesModel.getDescription(gameIndex)
}
}
var gameIntervals: NSTimeInterval {
get {
return gamesModel.getIntervals(gameIndex)
}
}
var gameNeedsMic: Bool {
get {
return gamesModel.getMic(gameIndex)
}
}
var gameNeedsSpeech: Bool {
get {
return gamesModel.getSpeech(gameIndex)
}
}
var appLocked: Bool {
get {
return optionsModel.appLocked
}
set {
optionsModel.appLocked = newValue
}
}
var supervisorLoggedIn: Bool {
get {
return optionsModel.supervisorLoggedIn
}
set {
optionsModel.supervisorLoggedIn = newValue
}
}
var themeSongMuted: Bool {
get {
return optionsModel.themeSongMuted
}
set {
optionsModel.themeSongMuted = newValue
}
}
var gameCount: Int {
get {
return optionsModel.gameCount
}
set {
optionsModel.gameCount = newValue
}
}
var gameHighscore: Int {
get {
return savesModel.getHighscore(gameIndex)
}
set {
savesModel.setHighscore(newValue)
}
}
var gameStarCount: Int {
get {
return savesModel.getStarCount(gameIndex)
}
set {
savesModel.setStarCount(newValue)
}
}
//}

Silly me. I fixed it.
The problem was that (this is probably obvious to some of you but singletons are new to me) the singleton loaded before the app delegate loaded and some of the variables in the singleton tried to get information from the app delegate before it was created so it caused this crash. Changed it around so that i didn't load the information until after the app delegate was loaded and it works now.

Related

#ObservedObject not updating after successful network call

I've hit a brick wall in my widget extension. I'm using AlamoFire and ObjectMapper to match the networking we have in the main app. I can tell that my AlamoFire network call is getting triggered and that I'm getting results back, and in the correct, expected format. However, saving the response of that network call to a #Published var doesn't seem to be working. My view and models/structs are below:
struct WidgetEntryView: View {
var entry: ResourceCategoryEntry
#ObservedObject var viewModel = WidgetResourcesView(widgetSize: .medium)
var body: some View {
if UserDefaults.forAppGroup.object(forKey: "sessionToken") as? String == nil {
PleaseLogIn()
} else if viewModel.mediumResources.count < 1 {
ErrorScreen()
} else {
MediumResourcesView(resources: viewModel.mediumResources)
}
}
}
class WidgetResourcesView: ObservableObject {
#Published var resourceGroups: [WidgetResouceGroup] = [WidgetResouceGroup]()
var widgetSize: WidgetSize = .small
var selectedCategory: String?
init(widgetSize: WidgetSize) {
self.widgetSize = widgetSize
self.selectedCategory = UserDefaults.forAppGroup.string(forKey: ResourceCategoryEntry.userDefaultKey)
getResources()
}
func getResources() {
WidgetNetworkService.getResources(widgetSize: self.widgetSize.rawValue, selectedCategory: self.selectedCategory) { resourceGroups in
DispatchQueue.main.async {
self.resourceGroups = resourceGroups
}
} failure: { _ in
print("Error Received")
}
}
var mediumResources: [WidgetResource] {
var resources = [WidgetResource]()
if let featuredResourceGroup = resourceGroups.featuredResourceGroup {
for resource in featuredResourceGroup.resources { resources.append(resource) }
}
if let nonFeaturedResourceGroup = resourceGroups.nonFeaturedResourceGroup {
for resource in nonFeaturedResourceGroup.resources { resources.append(resource) }
}
return resources
}
}
class WidgetResouceGroup: NSObject, Mappable, Identifiable {
var id = UUID()
var widgetCategory: WidgetCategory = .featured
var resources = [WidgetResource]()
required init?(map: Map) {}
func mapping(map: Map) {
id <- map["section"]
widgetCategory <- map["section"]
resources <- map["resources"]
}
}
typealias WidgetResourceGroupCollection = [WidgetResouceGroup]
extension WidgetResourceGroupCollection {
var featuredResourceGroup: WidgetResouceGroup? {
return first(where: {$0.widgetCategory == .featured})
}
var nonFeaturedResourceGroup: WidgetResouceGroup? {
return first(where: {$0.widgetCategory != .featured})
}
}
class WidgetResource: NSObject, Mappable, Identifiable {
enum ResourceType: String {
case text = "text"
case audio = "audio"
case video = "video"
}
var id = 0
var title = ""
var imageInfo: WidgetImageInfo?
var resourceType: ResourceType = .text
required init?(map: Map) {}
func mapping(map: Map) {
id <- map["object_id"]
title <- map["title"]
imageInfo <- map["image_info"]
resourceType <- map["content_type"]
}
}
You can use the objectWillChange - Property in your observable object to specifiy when the observable object should be refreshed.
Apple Dev Doku
Example by Paul Hudson
WidgetEntryView instantiates WidgetResourcesView using the ObservedObject wrapper. This causes a new instance of WidgetResourcesView to be instantiated again on every refresh. Try switching that to StateObject, and the original object will be kept in memory between view updates. I believe this is the only change needed, but I’m away so can’t test it!

Settings as shared Instance

I tried to do this so get my settings saved whenever the App moves to the background or gets killed or whatever.
I want to access and set the property "useLimits" all over my App.
Why is it not working?
Is there a better more elegant way to achieve this?
import UIKit
class Settings: NSObject
{
static let sharedInstance = Settings()
private let kUseLimits = "kUseLimits"
var useLimits = false
override init()
{
super.init()
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(Settings.save),
name: UIApplicationWillResignActiveNotification,
object: nil)
let userdefaults = NSUserDefaults.standardUserDefaults()
self.useLimits = userdefaults.boolForKey(kUseLimits)
}
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
save()
}
func save()
{
let userdefaults = NSUserDefaults.standardUserDefaults()
userdefaults.setBool(self.useLimits, forKey: kUseLimits)
userdefaults.synchronize()
}
func reset()
{
self.useLimits = false
save()
}
}
I think something like this will be good:
class AppSettings {
private struct Keys {
static let useLimits = "AppSttings.useLimits"
}
static var useLimits: Bool {
set {
NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: Keys.useLimits)
}
get {
return NSUserDefaults.standardUserDefaults().boolForKey(Keys.useLimits)
}
}
static func rest() {
useLimits = false
}
}
P.S. Starting from iOS 8 you don't need to call synchronize() in NSUserDefault
P.S.S. NSUserDefaults.standardUserDefaults().boolForKey(Keys.useLimits) will return false if there not such object, if you need specific default value please check on object or use NSUserDefaults.standardUserDefaults().registerDefaults()
P.S.S.S. It wont effect your performance much, so you can read from UD and write there just on on the run, but if you want too performance code, you can do something like this:
private static var _useLimits: Bool?
static var useLimits: Bool {
set {
NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: Keys.useLimits)
_useLimits = newValue
}
get {
if _useLimits == nil {
_useLimits = NSUserDefaults.standardUserDefaults().boolForKey(Keys.useLimits)
}
return _useLimits!
}
}
or more elegant for current value:
private static var _useLimits: Bool = NSUserDefaults.standardUserDefaults().boolForKey(Keys.useLimits)
static var useLimits: Bool {
set {
NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: Keys.useLimits)
_useLimits = newValue
}
get {
return _useLimits
}
}

Swift computed property templates?

Is there a way to template computed properties to avoid repeating the same code over and over? For example, right now I have a class with a block of code that looks like this:
private var _state:State?
private var _maxs:State?
private var _state1s:State?
private var _state10s:State?
var state:State? {
get {
dispatch_semaphore_wait(statephore, DISPATCH_TIME_FOREVER)
let s=_state
dispatch_semaphore_signal(statephore)
return s
}
set {
dispatch_semaphore_wait(statephore, DISPATCH_TIME_FOREVER)
_state=newValue
dispatch_semaphore_signal(statephore)
if newValue != nil {statsTest(newValue!)}
}
}
var maxs:State? {
get {
dispatch_semaphore_wait(maxphore, DISPATCH_TIME_FOREVER)
let m=_maxs
dispatch_semaphore_signal(maxphore)
return m
}
set {
dispatch_semaphore_wait(maxphore, DISPATCH_TIME_FOREVER)
_maxs=newValue
dispatch_semaphore_signal(maxphore)
}
}
var state1s:State? {
get {
dispatch_semaphore_wait(state1sphore, DISPATCH_TIME_FOREVER)
let s=_state1s
dispatch_semaphore_signal(state1sphore)
return s
}
set {
dispatch_semaphore_wait(state1sphore, DISPATCH_TIME_FOREVER)
_state1s=newValue
dispatch_semaphore_signal(state1sphore)
}
}
var state10s:State? {
get {
dispatch_semaphore_wait(state10sphore, DISPATCH_TIME_FOREVER)
let s=_state10s
dispatch_semaphore_signal(state10sphore)
return s
}
set {
dispatch_semaphore_wait(state10sphore, DISPATCH_TIME_FOREVER)
_state10s=newValue
dispatch_semaphore_signal(state10sphore)
}
}
There's an obvious pattern here, and all the repeated code just obfuscates what's happening and has led to errors as I cut/paste/edit/fail. Is there a way I can capture this pattern, and then define my properties with something like:
var state=ProtectedValue(_state,statephore)
?
This looks like a job for generics and inout variables.
func setProtectedValue<T>(inout destination: T, newValue: T, semaphore: SemaphoreType) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
destination = newValue
dispatch_semaphore_signal(semaphore)
}
at the call site:
var state10s:State? {
get {
//...
}
set {
setProtectedValue(&_state10s, newValue, state10sphore)
}
}

Swift. Why singleton lost data?

Why my data is lost in singleton? Please take a look:
class YtDataManager {
static var shared_instance = YtDataManager()
let apiKey = /*...*/
let /*...*/
var channelData = [NSObject:AnyObject]()
var videosArray = [[NSObject:AnyObject]]()
var playlistId: String { return self.channelData["playlistId"] as! String}
var urlStringForRequestChannelDetails: String { return String("https://www.googleapis.com/youtube/v3/channels?part=contentDetails,snippet&forUsername=\(self./*ChannelName*/)&key=\(self.apiKey)") }
var urlStringForRequestChannelVideos: String { return String("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=\(self.playlistId)&key=\(self.apiKey)") }
func fn1() { /*...*/ }
func fn2() { /*...*/ }
// class definition continue...
Look, from one function(fn1) I'm writing data to channelData:
//...
self.channelData["title"] = snippetDict["title"]
self.channelData["playlistId"] = ((firstItemDict["contentDetails"] as! [NSObject:AnyObject])["relatedPlaylists"] as! [NSObject:AnyObject])["uploads"]
//...
and so on... From second function(fn2), I'm reading data:
//...
let targetURL = NSURL(fileURLWithPath: self.urlStringForRequestChannelVideos)
//...
Hence urlStringForRequestChannelVideos is computational property it uses playlistId (look code above).
Here I was surprised about emptiness of channedData from second function(I saw it in Debug mode, also I printed it's count to stdout outside of function). Why????
class YtFeedViewController: UIViewController {
#IBOutlet weak var menuButton:UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
YtDataManager.shared_instance.fn1()
print(YtDataManager.shared_instance.channelData.count) //0
YtDataManager.shared_instance.fn2() //errorness
}
self.navigationItem.title = "YouTube feed"
// Do any additional setup after loading the view.
}

Swift - How to set a singleton to nil

I am writing an app in swift and use a singleton to share a class object, User, across the app.
I want to be able to set this singleton to 'nil' when the user logs out, so that when they log back in the old properties no longer exists (i.e. name, username, etc).
I am hoping there is an easy way to just set the singleton back to nil, instead of having to set each property to nil.
Here is my User class that is used in the app as User.activeUser:
class User: NSObject
{
class var activeUser : User? {
struct Static {
static let instance : User = User()
}
return Static.instance
}
}
How can I change this so that the below code does not give me a warning and actually nils out the singleton object:
User.activeUser = nil
This should work:
private var _SingletonSharedInstance:MyClass! = MyClass()
class MyClass {
let prop = "test"
class var sharedInstance : MyClass {
return _SingletonSharedInstance
}
init () {}
func destroy() {
_SingletonSharedInstance = nil
}
}
But then the references to the object are still kept, so you need to do some additional things to invalidate method calls in the class.
Your activeUser is set up as a read-only computed property. Every time you call User.activeUser it is going to recompute the activeUser for you. In order to set it to nil you'll have to add some logic to determine whether or not a user is logged in outside of the computed property. Something like this would work:
class User: NSObject
{
private struct userStatus { static var isLoggedIn: Bool = true }
class var activeUser : User? {
get {
if userStatus.isLoggedIn {
struct Static {
static let instance : User = User()
}
return Static.instance
} else {
return nil
}
}
set(newUser) {
if newUser != nil {
userStatus.isLoggedIn = true
} else {
userStatus.isLoggedIn = false
}
}
}
}
Here has a solution I used in java, but also works in swift:
class Manager {
private static var manager: Manager?
static func instance() -> Manager {
if Manager.manager == nil {
Manager.manager = Manager()
}
return Manager.manager!
}
func destroy() {
Manager.manager = nil
}
}