简体   繁体   中英

creation of realm file in App-Group Folder does not work under WatchOS (WatchKit Extension)

The following code works under iOS-8.x / Swift-1.2 / WatchKit-1.0

    // create Realm_DB-File in shared App-Groups Folder
    let directory: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(AppConstants.APP_GROUP_IDENTIFIER_KEY)!
    let realmPath = directory.path!.stringByAppendingPathComponent(AppConstants.REALM_FILENAME_KEY)
    playerRealm = Realm.init(path: realmPath)

But it doesn't work under iOS-9.0.1 / Swift-2.0 / WatchOS-2.0

The two error messages are:

1.) 'stringByAppendingPatchComponent' is unavailable: Use URLByAppendingPathComponent on NSURL instead

2.) Call can throw, but it is not marked with 'try' and the error is not handled

在此处输入图片说明

Any help appreciated !

To fix your first issue, you need to cast:

directory.path as NSString

since the path is returning as a String , which in Swift doesn't offer the stringByAppendingPathComponent method.

Second, Swift 2.0 has new error handling, so methods that can throw an error are labeled throws . These methods then require you to add try before the call. See Apple's docs on this: Swift Error Handling

To disable the error handling if you know that the path is guaranteed to work you can simple write:

playerRealm = try! Realm(path: realmPath)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM