I'm trying to read/write data in extra class file which is public. (StoreData.swift)
My function :
func FetchName (NameforDate: String) -> NSString
{
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
}
At line where is "(UIApplication.sharedApplication()." I get the error:
StoreData.swift:115:49: 'sharedApplication()' is unavailable: Use view
controller based solutions where appropriate instead.
I created App and Today Extension.
To share data between App and Today Widget, following Apple guidelines, you have to create an App Group under target's capabilities tab and link it to both App and Widget.
To access your shared defaults:
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:YOUR_APP_GROUP_ID];
It works exactly like [NSUserDefaults standardUserDefaults] so you can store a minimal part of your data but it's all you can do.
EDIT:
Here you can find Swift doc for Suite Defaults:
https://developer.apple.com/Library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html#//apple_ref/occ/instm/NSUserDefaults/initWithSuiteName:
EDIT 2:
Use a Singleton to access your Core Data instead, you can find an easy tutorial here:
http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/
If you need a managed object context you can create your own within your extension.Your AppDelegate will not be available to you. I would suggest moving out that from your app delegate to a class you can share between both. You will still be able to listen for core data updates so they don't need to share contexts/persistent store coordinates.
EDIT:
I'd like to point out that extensions are essentially a different sandbox. Therefore if you create a shared class the instances will not be the same shared between App and Extension. Therefore making the persistent store coordinator and contexts different.
Your issue:
StoreData.swift:115:49: 'sharedApplication()' is unavailable: Use view controller based solutions where appropriate instead.
Is because -[UIApplication sharedApplication]
is not available to extensions. Your extension does not run as part of your application, so there is no application context for an extension to message.
This is clearly explained in the App Extension Programming Guide section on Understanding How an App Extension Works:
Because of its focused role in the system, an app extension is ineligible to participate in certain activities. An app extension cannot:
• Access a sharedApplication object, and so cannot use any of the methods on that object