I use App Groups Capability to share a SQLite DB between two Apps.
Now i want to migrate to Swift from Objective-C.
To obtain the path of DB, in Objective-C i've
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSURL *groupContainerURL = [fileMgr containerURLForSecurityApplicationGroupIdentifier:@"<APP_GROUPS_ID>"];
NSString *groupContainerString = [groupContainerURL path];
NSString *sharedDB = [groupContainerString stringByAppendingPathComponent:dbFilename];
const char *dbPath = [sharedDB UTF8String];
and it works.
In Swift i've tried this way
let groupContainerURL = fileMgr!.containerURL(forSecurityApplicationGroupIdentifier: "<APP_GROUPS_ID>")
let groupContainerString = groupContainerURL.path
pathToDatabase = groupContainerString.appending(databaseFileName)
and i've declared also
let databaseFileName = "<DB_NAME>"
var pathToDatabase: String!
var fileMgr : FileManager!
But i've this error, about Optional Value
fatal error: unexpectedly found nil while unwrapping an Optional value
2017-07-24 11:25:09.086974 CatchTheData[7941:4022839] fatal error: unexpectedly found nil while unwrapping an Optional value
at the start.
Where i wrong?
Runtime exception
: unexpectedly found nil while unwrapping an Optional value
, occurs:
unwrap an optional
that contains nil
OR implicitly unwrapped optional
without assigning a value to it.In the following lines:
var pathToDatabase: String!
var fileMgr : FileManager!
make sure you have assigned value to pathToDatabase
and fileMgr
before using them. Since these 2 variables are implicitly unwrapped optionals
, so in case you use them without assigning values, it will result in runtime exception
similar to unexpectedly found nil while unwrapping an Optional value.
let groupContainerURL = fileMgr!.containerURL(forSecurityApplicationGroupIdentifier: "<APP_GROUPS_ID>")
In the above line of code, you are using fileMgr!
. First of all no need to unwrap it. It is implicitly unwrapped
. Just make sure fileMgr
has value so that the app won't crash.