Passing Data from Delegate Swift Class to EnvironmentObject in SwiftUI Struct - swift

How do I pass incoming data from a method triggered by a delegate in a Swift class to an EnvironmentObject?
I am aware that for this to work my Swift class needs to be called/initialized from the SwiftUI struct (be a child of the parent SwiftUI struct). However, I initialise my Swift class in the ExtensionDelegate of the Apple Watch app. I would like to see the UI Text element change when the name is updated.
The following code runs on the Apple Watch:
class User: ObservableObject {
#Published var id: UUID?
#Published var name: String?
}
//SwiftUI struct
struct UI: View {
#EnvironmentObject var userEnv: User
var body: some View {
Text(userEnv.name)
}
}
// Swift class
class WatchConnectivityProvider: NSObject, WCSessionDelegate {
static let shared = WatchConnectivityProvider()
private let session: WCSession
init(session: WCSession = .default) {
self.session = session
super.init()
}
func activateSession() {
if WCSession.isSupported() {
session.delegate = self
session.activate()
}
}
//This func gets triggered when data is sent from the iPhone
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: #escaping ([String : Any]) -> Void) {
let list = message["list"]
let jsonDecoder = JSONDecoder()
if let data = try? jsonDecoder.decode(User.self, from: list as! Data) {
// !!! This is where I would like to update the EnvironmentObject userEnv !!!
// What is the best way to do this? Remember, this class has already been initialised within the ExtensionDelegate.
}
}
}
//ExtensionDelegate of Apple Watch app, initialising the WatchConnectivityProvider
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
WatchConnectivityProvider.shared.activateSession()
}
}

Dependency Injection
One of the solutions could be to store the reference to your #EnvironmentObject globally, eg. in some dependency container.
enum Dependencies {
struct Name: Equatable {
let rawValue: String
static let `default` = Name(rawValue: "__default__")
static func == (lhs: Name, rhs: Name) -> Bool { lhs.rawValue == rhs.rawValue }
}
final class Container {
private var dependencies: [(key: Dependencies.Name, value: Any)] = []
static let `default` = Container()
func register(_ dependency: Any, for key: Dependencies.Name = .default) {
dependencies.append((key: key, value: dependency))
}
func resolve<T>(_ key: Dependencies.Name = .default) -> T {
return (dependencies
.filter { (dependencyTuple) -> Bool in
return dependencyTuple.key == key
&& dependencyTuple.value is T
}
.first)?.value as! T
}
}
}
Then you create your object like this:
Dependencies.Container.default.register(User())
And you can access it from anywhere in your code:
let user: User = Dependencies.Container.default.resolve()
user.modify()
A more detailed explanation of Dependency Injection for Swift can be found here.
Singleton
Alternatively you can use standard Singleton pattern to make your User data available globally. A more detailed explanation can be found here.
Final thoughts
Clean Architecture for SwiftUI is a good example (in my opinion at least) of how to write an iOS app in the clean way. It's a little bit complicated, but you can pick up some parts.

Here bad Jumbo code:
class ExtensionDelegate: ObservableObject, NSObject, WCSessionDelegate, WKExtensionDelegate {
var session: WCSession?
#Published var model = Model
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: #escaping ([String : Any]) -> Void) {
print(#function)
var replyValues = Dictionary<String, Any>()
replyValues["status"] = "failed"
// 2442 Bytes
if let data = message["data"] as? Data {
// push that work back to the main thread
DispatchQueue.main.async {
self.model = try? JSONDecoder().decode(Model.self, from: data)
}
if let vm = vm {
replyValues["status"] = "ok"
replyValues["id"] = vm.id.uuidString
}
}
replyHandler(replyValues)
}
...

Related

Switch between making API call, and setting mocked data without an API call in SWIFT

During the development of a swiftUI project, I wish to have option to switch the way data is set, either
Allowing API calls to be made as normal which sets an #Published variable, or
Set the #published variable from mocked file and NOT make the api call.
The reason is that I am limited to the number of api calls per minute.
In my example below I load the mocked data in a model called "Person".
Current solution
Set a global variable to distinguish between the two above mentioned states.
In all places where api calls were be made, I introduce a condition to optionally use mocked data and not make the api call. See .task in MyView
struct GlobalConstants {
static let use_mock_data = true
}
class ViewModel: ObservableObject {
#Published var data: [Person] = []
#MainActor
func fetchData() async {
// ... data is set in this code
}
}
Within Person model, I set a static variable that returns the decoded mock data from a json file. The decode method below is an extension to Bundle (Thanks Paul Hudsen).
extension Person {
static var mockPersons: [Person] {
Bundle.main.decode([Person].self, from: "persons.json")
}
}
struct MyView: View {
#StateObject var vm = PersonViewModel()
var body: some View {
NavigationView {
List {
ForEach(vm.data) { d in
NavigationLink {
OtherView(prop: d.detail)
} label: {
Text(d.name)
}
}
}
.task { // -----condition--------------------- //
if GlobalConstants.use_mock_data {
vm.data = Person.mockPersons
} else {
await vm.fetchData()
}
}
}
}
}
Question
What other approaches can I consider for enabling the two states? Overriding the methods in some way?
I am still on the learning curve to swift and wondering if theres a better way to enable long term maintenance in a clean and predictable way.
As fetching the data belongs to the view model my suggestion is to put the condition into fetchData.
Marking a method as async doesn't require necessarily that the executed code is asynchronous
#MainActor
class ViewModel: ObservableObject {
#Published var people: [Person] = []
func fetchData() async {
if GlobalConstants.use_mock_data {
people = Person.mockPersons
} else {
// people = await callTheAPI()
}
}
}
and replace the task in the view with
.task {
await vm.fetchData()
}
Note: people is a more meaningful name than data 😃
You should use a Service with a protocol, and then create 2 services extending the protocol, one for mock and one for data, here are some examples from one of my apps (using alamofire, but you can modify it to use it with URLSession or anything else) :
import Alamofire
class NetworkManager {
func get<T: Decodable>(url: URLConvertible, parameters: Parameters?,_ completion: #escaping (DataResponse<T, AFError>) -> Void) {
AF.request(url, parameters: parameters)
.responseDecodable(of: T.self) { response in
completion(response)
}
}
}
protocol SearchServicing {
var parameters: Parameters? { get set }
func get(_ completion: #escaping (Result<SearchResponse, AFError>) -> Void)
}
class SearchService: NetworkManager, SearchServicing {
var parameters: Parameters?
func get(_ completion: #escaping (Result<SearchResponse, AFError>) -> Void) {
let url = "YOUR_URL"
get(url: url, parameters: parameters) { response in
completion(response.result)
}
}
}
class SearchMockService: SearchServicing {
var parameters: Parameters?
var getCallCounter = 0
func get(_ completion: #escaping (Result<SearchResponse, AFError>) -> Void) {
getCallCounter += 1
let response = SearchResponse(recipes: [
Recipe.mock,
Recipe.mock,
Recipe.mock,
])
completion(.success(response))
}
}
Then add it in the ViewModel :
#MainActor
class RecipeViewModel: ObservableObject {
...
private var service: SearchServicing
init(service: SearchServicing) {
self.service = service
}
public func fetchData() {
[...]
service.parameters = ["q": ingredients.map { $0.name }.joined(separator: " ")]
service.get { [weak self] result in
switch result {
case .success(let searchResponse):
self?.totalResults = searchResponse.count
self?.results = searchResponse.recipes
case .failure(let error):
dump(error)
self?.error = AppError(error: error)
}
}
}
}
And so it allows me to do :
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView(recipeViewModel: RecipeViewModel(service: SearchMockService()))
}
}
whenever I need to test my view model and
struct MainView: View {
#ObservedResults(RecipeEntity.self) var favorites
#StateObject var recipeViewModel = RecipeViewModel(service: SearchService())
var body: some View {
...
}
}
for non mock datas service
For more informations checkout this video, it helped me to use this structure : How to implement a Mock in Swift!

Does an NSFilePromiseProviderDelegate need to be also an NSView or NSViewController?

I am going through the AppKit tutorial Supporting Drag and Drop Through File Promises. I downloaded the demo app.
I tried to extract the NSFilePromiseProviderDelegate functionality from the ImageCanvasController class (which is an NSViewController) into a separate class. (Please see before & after code snippets below.)
Before my changes, dragging an image from the app canvas out into Finder and Apple Notes worked fine. But after my changes, nothing happens when I drag into Notes, and I get this error when I drag into Finder:
2022-02-26 23:16:52.713742+0100 MemeGenerator[31536:1975798] *** CFMessagePort: dropping corrupt reply Mach message (0b000100)
Is there any undocumented protocol conformance that I need to add to the new class? Or is there some underlying logic for which NSFilePromiseProviderDelegate only works if it's also an NSView or an NSViewController? In all the guides I found online, it is always tied to a view, but I didn't find any warning that it has to be.
Note:
The reason I want to separate the promise-provider functionality from views is, this way I could provide multiple NSDraggingItem objects to beginDraggingSession. For example, when multiple items are selected, and there is a mouseDragged event on one of them, I could start a dragging session including all the selected items.
Code before
class ImageCanvasController: NSViewController, NSFilePromiseProviderDelegate, ImageCanvasDelegate, NSToolbarDelegate {
...
/// Queue used for reading and writing file promises.
private lazy var workQueue: OperationQueue = {
let providerQueue = OperationQueue()
providerQueue.qualityOfService = .userInitiated
return providerQueue
}()
...
func pasteboardWriter(forImageCanvas imageCanvas: ImageCanvas) -> NSPasteboardWriting {
let provider = NSFilePromiseProvider(fileType: kUTTypeJPEG as String, delegate: self)
provider.userInfo = imageCanvas.snapshotItem
return provider
}
// MARK: - NSFilePromiseProviderDelegate
/// - Tag: ProvideFileName
func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
let droppedFileName = NSLocalizedString("DropFileTitle", comment: "")
return droppedFileName + ".jpg"
}
/// - Tag: ProvideOperationQueue
func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue {
return workQueue
}
/// - Tag: PerformFileWriting
func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL, completionHandler: #escaping (Error?) -> Void) {
do {
if let snapshot = filePromiseProvider.userInfo as? ImageCanvas.SnapshotItem {
try snapshot.jpegRepresentation?.write(to: url)
} else {
throw RuntimeError.unavailableSnapshot
}
completionHandler(nil)
} catch let error {
completionHandler(error)
}
}
}
Code after
class CustomFilePromiseProviderDelegate: NSObject, NSFilePromiseProviderDelegate {
/// Queue used for reading and writing file promises.
private lazy var workQueue: OperationQueue = {
let providerQueue = OperationQueue()
providerQueue.qualityOfService = .userInitiated
return providerQueue
}()
/// - Tag: ProvideFileName
func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
let droppedFileName = NSLocalizedString("DropFileTitle", comment: "")
return droppedFileName + ".jpg"
}
/// - Tag: ProvideOperationQueue
func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue {
return workQueue
}
/// - Tag: PerformFileWriting
func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL, completionHandler: #escaping (Error?) -> Void) {
do {
if let snapshot = filePromiseProvider.userInfo as? ImageCanvas.SnapshotItem {
try snapshot.jpegRepresentation?.write(to: url)
} else {
throw RuntimeError.unavailableSnapshot
}
completionHandler(nil)
} catch let error {
completionHandler(error)
}
}
}
class ImageCanvasController: NSViewController, ImageCanvasDelegate, NSToolbarDelegate {
...
func pasteboardWriter(forImageCanvas imageCanvas: ImageCanvas) -> NSPasteboardWriting {
let delegate = CustomFilePromiseProviderDelegate()
let provider = NSFilePromiseProvider(fileType: kUTTypeJPEG as String, delegate: delegate)
provider.userInfo = imageCanvas.snapshotItem
return provider
}
}
Does an NSFilePromiseProviderDelegate need to be also an NSView or NSViewController?
No.
delegate is a local variable and is released at the end of pasteboardWriter(forImageCanvas:). Without a delegate the file promise provider doesn't work. Solution: keep a strong reference to the delegate.
class ImageCanvasController: NSViewController, ImageCanvasDelegate, NSToolbarDelegate {
let delegate = CustomFilePromiseProviderDelegate()
...
func pasteboardWriter(forImageCanvas imageCanvas: ImageCanvas) -> NSPasteboardWriting {
let provider = NSFilePromiseProvider(fileType: kUTTypeJPEG as String, delegate: delegate)
provider.userInfo = imageCanvas.snapshotItem
return provider
}
}

Core Data App Shuts down at launch "Exited Voluntarily"

I started a new project in SwiftUI and CoreData. As soon as I added Transformable to on of the child record in my parent /child data model, the App launches and immediately shuts down. When I try to use Previews, I now get Error Domain=FBProcessExit Code=1 "The process exited voluntarily." UserInfo={BSErrorCodeDescription=voluntary, NSLocalizedFailureReason=The process exited voluntarily.} on all views in the app. Can anyone help me figure out how to debug this?
I am including the model code and the transformer in case this helps:
import Foundation
import CoreData
import UIKit
extension Event {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Event> {
return NSFetchRequest<Event>(entityName: "Event")
}
#NSManaged public var cardFrontImage: UIImage?
#NSManaged public var event: String?
#NSManaged public var recipient: Recipient?
}
extension Event : Identifiable {
}
Tranformer code:
import Foundation
import UIKit
class ImageTransformer: ValueTransformer {
override class func transformedValueClass() -> AnyClass {
return NSData.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
autoreleasepool{
guard let data = value as? Data else {
return nil
}
return UIImage(data: data)
}
}
override func transformedValue(_ value: Any?) -> Any? {
autoreleasepool{
guard let image = value as? UIImage else {
return nil
}
return image.jpegData(compressionQuality: 1.0)
}
}
}
And Where I set the Transformer in the #main
#main
struct HolidayCardApp: App {
#Environment(\.scenePhase) private var scenePhase
let context = PersistentCloudKitContainer.persistentContainer.viewContext
static let doInitialize: Void = {
ValueTransformer.setValueTransformer(ImageTransformer(), forName: NSValueTransformerName("ImageTransformer"))
// register transformers here
}()
static func main() {
HolidayCardApp.doInitialize
}
var body: some Scene {
// CODE
}
}
Solved the issue, by moving the Initialization of the ValueTransformer into my PersistentCloudKit Setup.

MVVM with realm: Passing Realm-results across threads?

Using Xcode-8.2.1, Swift-3.0.2, RealmSwift-2.2.0, iOS-Simulator-10:
I try applying the MVVM pattern (explained by Steve Scott here) using Realm.
Everything works until the moment (inside the VIEW-part - see below) where I try to access a viewmodel-property. It says: Realm accessed from incorrect thread
How could I still make the MVVM-pattern do its job of separating model, view-model and view but, on the same time, get thread-safety with realm ?
Is there a way to make Realm-results (i.e. Results<BalancesDataEntry>) being passed across threads ??
Here is my code:
(the issue happens at the very bottom, inside the View-part)
// REALM-OBJECT:
import Foundation
import RealmSwift
class BalancesDataEntry: Object {
dynamic var category: String = ""
dynamic var index: Int = 0
}
MODEL:
import Foundation
import RealmSwift
class MVVMCBalancesModel: BalancesModel
{
fileprivate var entries = [BalancesDataEntry]()
let realm = try! Realm()
init() {
self.createDataEntries()
}
fileprivate func createDataEntries() {
let myBalance = BalancesDataEntry()
myBalance.index = 0
myBalance.category = "Love"
try! self.realm.write {
self.realm.deleteAll()
self.realm.add(myBalance)
}
}
func getEntries(_ completionHandler: #escaping (_ entries: [BalancesDataEntry]) -> Void)
{
// Simulate Aysnchronous data access
DispatchQueue.global().async {
let realmThread = try! Realm()
let returnArray: [BalancesDataEntry] = Array(realmThread.objects(BalancesDataEntry.self))
completionHandler(returnArray)
}
}
}
VIEW-MODEL:
import Foundation
import RealmSwift
class MVVMCBalancesViewModel: BalancesViewModel
{
weak var viewDelegate: BalancesViewModelViewDelegate?
weak var coordinatorDelegate: BalancesViewModelCoordinatorDelegate?
fileprivate var entries: [BalancesDataEntry]? {
didSet {
viewDelegate?.entriesDidChange(viewModel: self)
}
}
var model: BalancesModel? {
didSet {
entries = nil;
model?.getEntries({ (myEntries) in
self.entries = myEntries
})
}
}
var title: String {
return "My Balances"
}
var numberOfEntries: Int {
if let entries = entries {
return entries.count
}
return 0
}
func entryAtIndex(_ index: Int) -> BalancesDataEntry?
{
if let entries = entries , entries.count > index {
return entries[index]
}
return nil
}
func useEntryAtIndex(_ index: Int)
{
if let entries = entries, let coordinatorDelegate = coordinatorDelegate , index < entries.count {
coordinatorDelegate.balancesViewModelDidSelectData(self, data: entries[index])
}
}
}
VIEW:
import UIKit
class MVVMCBalancesViewController: UIViewController {
#IBOutlet weak var label1Outlet: UILabel!
#IBOutlet weak var label2Outlet: UILabel!
var viewModel: BalancesViewModel? {
willSet {
viewModel?.viewDelegate = nil
}
didSet {
viewModel?.viewDelegate = self
refreshDisplay()
}
}
var isLoaded: Bool = false
func refreshDisplay()
{
if let viewModel = viewModel , isLoaded {
// !!!!!!! HERE IS THE ISSUE: Realm accessed from incorrect thread !!!!
self.label1Outlet.text = viewModel.entryAtIndex(0)?.category
self.label2Outlet.text = viewModel.entryAtIndex(1)?.category
} else {
}
}
override func viewDidLoad()
{
super.viewDidLoad()
isLoaded = true
refreshDisplay();
}
}
extension MVVMCBalancesViewController: BalancesViewModelViewDelegate
{
func entriesDidChange(viewModel: BalancesViewModel)
{
}
}
You can use ThreadSafeReference to pass Realm's thread-confined types (Object, Results, List, LinkingObjects) to a different thread. The documentation's section on Passing Instances Across Threads contains this example of passing a single instance of an Object subclass across threads:
let person = Person(name: "Jane")
try! realm.write {
realm.add(person)
}
let personRef = ThreadSafeReference(to: person)
DispatchQueue(label: "background").async {
let realm = try! Realm()
guard let person = realm.resolve(personRef) else {
return // person was deleted
}
try! realm.write {
person.name = "Jane Doe"
}
}
It can be used similarly for Results.
I have found a workaround (see below): Maybe you have better solutions - please let me know!
Here is my github-code realm_mvvm_c on github
After introducing a new protocol and making (pretty much everything) conform to it, things worked out.
Here is the protocol called DataEntry:
import Foundation
protocol DataEntry: class {
var idx: Int { get set }
var category: String { get set }
}
Now, make everything conform to it, such as
--> the realm object (i.e. class BalancesDataEntry: Object, DataEntry {...)
--> the getEntries return value (i.e. func getEntries(_ completionHandler: #escaping (_ entries: [DataEntry]) -> Void))
--> the View-Model's entries (i.e. fileprivate var entries: [DataEntry]? {..)
--> all the corresponding Model- and View-Model protocols also need the DataEntry datatype (see git-repo for complete picture)
After that, it was enough to change the completion-handler return-array of the MODEL's method getEntries(..) to a newly created object-instance (ie. DataEntryDub) that is keept conform to the DataEntry protocol:
func getEntries(_ completionHandler: #escaping (_ entries: [DataEntry]) -> Void)
{
// Simulate Aysnchronous data access
DispatchQueue.global().async {
let realmThread = try! Realm()
class DataEntryDub: DataEntry {
var idx: Int
var category: String
init(idx: Int, category: String) {
self.idx = idx
self.category = category
}
}
var returnArray = [DataEntry]()
for entry in realmThread.objects(BalancesDataEntry.self) {
returnArray.append(DataEntryDub(idx: entry.idx, category: entry.category))
}
completionHandler(returnArray)
}
}
Here is my github-code realm_mvvm_c on github

Singleton in Swift

I've been trying to implement a singleton to be used as a cache for photos which I uploaded to my iOS app from the web. I've attached three variants in the code below. I tried to get variant 2 working but it is causing a compiler error which I do not understand and would like to get help on what am I doing wrong. Variant 1 does the caching but I do not like the use of a global variable. Variant 3 does not do the actual caching and I believe it is because I am getting a copy in the assignment to var ic = ...., is that correct?
Any feedback and insight will be greatly appreciated.
Thanks,
Zvi
import UIKit
private var imageCache: [String: UIImage?] = [String : UIImage?]()
class ImageCache {
class var imageCache: [String : UIImage?] {
struct Static {
static var instance: [String : UIImage?]?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = [String : UIImage?]()
}
return Static.instance!
}
}
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://images.apple.com/v/iphone-5s/gallery/a/images/download/photo_1.jpg")!)!)
//variant 1 - this code is working
imageCache["photo_1"] = imageView.image
NSLog(imageCache["photo_1"] == nil ? "no good" : "cached")
//variant 2 - causing a compiler error on next line: '#lvalue $T7' is not identical to '(String, UIImage?)'
//ImageCache.imageCache["photo_1"] = imageView.image
//NSLog(ImageCache.imageCache["photo_1"] == nil ? "no good" : "cached")
//variant 3 - not doing the caching
//var ic = ImageCache.imageCache
//ic["photo_1)"] = imageView.image
//NSLog(ImageCache.imageCache["photo_1"] == nil ? "no good" : "cached")
}
}
The standard singleton pattern is:
final class Manager {
static let shared = Manager()
private init() { ... }
func foo() { ... }
}
And you'd use it like so:
Manager.shared.foo()
Credit to appzYourLife for pointing out that one should declare it final to make sure it's not accidentally subclassed as well as the use of the private access modifier for the initializer, to ensure you don't accidentally instantiate another instance. See https://stackoverflow.com/a/38793747/1271826.
So, returning to your image cache question, you would use this singleton pattern:
final class ImageCache {
static let shared = ImageCache()
/// Private image cache.
private var cache = [String: UIImage]()
// Note, this is `private` to avoid subclassing this; singletons shouldn't be subclassed.
private init() { }
/// Subscript operator to retrieve and update cache
subscript(key: String) -> UIImage? {
get {
return cache[key]
}
set (newValue) {
cache[key] = newValue
}
}
}
Then you can:
ImageCache.shared["photo1"] = image
let image2 = ImageCache.shared["photo2"])
Or
let cache = ImageCache.shared
cache["photo1"] = image
let image2 = cache["photo2"]
Having shown a simplistic singleton cache implementation above, we should note that you probably want to (a) make it thread safe by using NSCache; and (b) respond to memory pressure. So, the actual implementation is something like the following in Swift 3:
final class ImageCache: NSCache<AnyObject, UIImage> {
static let shared = ImageCache()
/// Observer for `UIApplicationDidReceiveMemoryWarningNotification`.
private var memoryWarningObserver: NSObjectProtocol!
/// Note, this is `private` to avoid subclassing this; singletons shouldn't be subclassed.
///
/// Add observer to purge cache upon memory pressure.
private override init() {
super.init()
memoryWarningObserver = NotificationCenter.default.addObserver(forName: .UIApplicationDidReceiveMemoryWarning, object: nil, queue: nil) { [weak self] notification in
self?.removeAllObjects()
}
}
/// The singleton will never be deallocated, but as a matter of defensive programming (in case this is
/// later refactored to not be a singleton), let's remove the observer if deallocated.
deinit {
NotificationCenter.default.removeObserver(memoryWarningObserver)
}
/// Subscript operation to retrieve and update
subscript(key: String) -> UIImage? {
get {
return object(forKey: key as AnyObject)
}
set (newValue) {
if let object = newValue {
setObject(object, forKey: key as AnyObject)
} else {
removeObject(forKey: key as AnyObject)
}
}
}
}
And you'd use it as follows:
ImageCache.shared["foo"] = image
And
let image = ImageCache.shared["foo"]
For Swift 2.3 example, see previous revision of this answer.
Swift 3:
class SomeClass
{
static let sharedInstance = SomeClass()
fileprivate override init() {
//This prevents others from using the default '()' initializer
super.init()
}
func sayHello()
{
print("Hello!")
}
}
Invoke some Method:
SomeClass.sharedInstance.sayHello() //--> "Hello"
Invoke some Method by creating a new class instance (fails):
SomeClass().sayHello() //--> 'SomeClass' cannot be constructed it has no accessible initailizers
Swift-5
To create a singleton class:
import UIKit
final class SharedData: NSObject {
static let sharedInstance = SharedData()
private override init() { }
func methodName() { }
}
To access
let sharedClass = SharedClass.sharedInstance
OR
SharedClass.sharedInstance.methodName()
Following are the two different approaches to create your singleton class in swift 2.0
Approach 1) This approach is Objective C implementation over swift.
import UIKit
class SomeManager: NSObject {
class var sharedInstance : SomeManager {
struct managerStruct {
static var onceToken : dispatch_once_t = 0
static var sharedObject : SomeManager? = nil
}
dispatch_once(&managerStruct.onceToken) { () -> Void in
managerStruct.sharedObject = SomeManager()
}
return managerStruct.sharedObject!
}
func someMethod(){
print("Some method call")
}
}
Approach 2) One line Singleton, Don't forget to implement the Private init (restrict usage of only singleton)
import UIKit
class SomeManager: NSObject {
static let sharedInstance = SomeManager()
private override init() {
}
func someMethod(){
print("Some method call")
}
}
Call the Singleton method like :
SomeManager.sharedInstance.someMethod()