Search code examples
iosswiftbackground-process

Pass a variable from foreground to background in Swift


I am developing an iOS application where I want to record the time when a user presses a particular button and keep it. Later I will use this time record in background. Is there a nice way of doing that without invoking NSUserDefaults or CoreData or whatever other database?

I am very new to iOS development. I think this is very likely to be a naive question. But I'm just curious. Please don't laugh at me haha.

Edit: This is indeed a very naive question haha.


Solution

  • A simple way to make sure your data is available everywhere in your app and only persists for each app session would be to use a singleton. Something like this.

    // Create a class to store the data
    class SessionData : NSObject {
    
        // Create a shared instance of your class
        static let sharedInstance = SessionData()
    
        // Create a variable to store the date object
        var timeStore:NSDate?
    }
    

    This will mean that anywhere in your app you can get and set this data as below.

    // Get
    if let time = SessionData.sharedInstance.timeStore {
        println(time)
    }
    
    // Set
    SessionData.sharedInstance.timeStore = NSDate()
    

    It is worth mentioning that despite the above being a valid method, You may be able to avoid doing this by re-thinking your app structure and passing data between classes instead. You should have a look at Delegation.

    Also as @CouchDeveloper mentions in their comment below, you may want to included a dispatch queue to prevent crashes or locks in the situation where two or more classes try to read and or write data at the same time.