2017-07-24 30 views
2

我使用應用程序組能夠在兩個應用程序之間共享SQLite數據庫。iOS/Swift - 使用應用程序組訪問共享數據庫

現在我想從Objective-C遷移到Swift。

獲得DB的路徑,在Objective-C,我

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]; 

和它的作品。

在斯威夫特我已經嘗試過這種方式

let groupContainerURL = fileMgr!.containerURL(forSecurityApplicationGroupIdentifier: "<APP_GROUPS_ID>") 

let groupContainerString = groupContainerURL.path 

pathToDatabase = groupContainerString.appending(databaseFileName) 

而且我也宣告

let databaseFileName = "<DB_NAME>" 

var pathToDatabase: String! 

var fileMgr : FileManager! 

但我這個錯誤,有關可選值

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 

在開始。

我在哪裏錯了?

回答

2

Runtime exceptionunexpectedly found nil while unwrapping an Optional value,發生:

    當你 unwrap an optional包含 nil OR
  1. 當您使用implicitly unwrapped optional沒有給它分配一個值

在下面幾行:

var pathToDatabase: String! 
var fileMgr : FileManager! 

確保你使用它們之前已經分配價值pathToDatabasefileMgr。由於這2個變量是implicitly unwrapped optionals,所以如果你使用它們沒有分配值,它會導致runtime exception類似unexpectedly found nil while unwrapping an Optional value.

let groupContainerURL = fileMgr!.containerURL(forSecurityApplicationGroupIdentifier: "<APP_GROUPS_ID>") 

在上面的代碼行,您使用的fileMgr!。首先不需要解開它。這是implicitly unwrapped。只要確保fileMgr有價值,這樣應用程序就不會崩潰。

0
let databaseFileName = "<DB_NAME>" 

var pathToDatabase: String! 

var fileMgr : FileManager? //Your code crashes coz you hv declared fileMgr as non-optional but you hv'nt initialized it. 

let AppGroupContainerUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "<APP_GROUPS_ID>") 
if let groupContainerURL = AppGroupContainerUrl{ 
    let groupContainerString = groupContainerURL.path 
    pathToDatabase = groupContainerString.appending(databaseFileName) 
} 
相關問題