As the user defaults are associated with you application not with any file. You can access the user default with any kind of file whether it is in swift or in objective c. I am assuming you are working with single target. Please follow the concept.
I have made a swift project.
I have added an objective c file.
I have also added the bridging header file.
Now i will access the user default values as:
In .h file describe two methods as:
@interface UDF_Objc_Access : NSObject
+(void)set_udf_value_objc:(NSString *)value for:(NSString*)key;
+(NSString *)get_udf_swift_value_for:(NSString*)key;
@end
In .m implementation file give the definition as:
@implementation UDF_Objc_Access
+(void)set_udf_value_objc:(NSString *)value for:(NSString *)key {
[[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
}
+(NSString *)get_udf_swift_value_for:(NSString *)key {
return [[NSUserDefaults standardUserDefaults] stringForKey:key];
}
@end
Now in your Appdelegate.swift do:
/*
key names
swift key = "swift_key"
objective c key = "objc_key"
*/
let swift_key = "swift_key"
let objc_key = "objc_key"
//MARK:- Case 1
/*
Save value from swift file & get it from objective c file
*/
UserDefaults.standard.set("This value is saved from swift class", forKey: swift_key)
UserDefaults.standard.synchronize()
//getting value from objective c class
print(UDF_Objc_Access.get_udf_swift_value_(for: swift_key))
/*
Set value from objective c file & get it with swift
*/
UDF_Objc_Access.set_udf_value_objc("This value is saved from objective c file", for: objc_key)
//print value form swift
print(UserDefaults.standard.value(forKey: objc_key)!)
Note: If you are working with multiple targets then use the app groups.