Swift Realm issue in iOS 14+ - swift

------LE: We ended up removing the encryption of the database because with realm team suggestions it got worse - all we could do was to remove the database and loose all stored info. Now we encrypt in keychain only the fields we need.------
I have an app released in store and after updating their iOS version to 14+, users started to complain about info not being populated from database. Not all users with iOS 14+ have this issue, it appears randomly on some devices.
The issue goes away for awhile if they reinstall the app or after they update it to another version, but after using it for a few minutes it happens again.
My database uses encryption as documented here.
The store version of my app uses Realm 5.4.8, but I tested their last version (10.0.0) and the issue is still present.
I checked this issue but it's not the case for me, I don't have a shared app group container or a share extension.
Here's how the initialisation of realm looks like:
override init() {
super.init()
do {
guard let config = getMigrationAndEncryptionConfiguration() else {
realmConfigured = try Realm()
return
}
realmConfigured = try Realm(configuration: config)
} catch let error as NSError {
// this is where I got the error:
//"Encrypted interprocess sharing is currently unsupported.DB has been opened by pid: 4848. Current pid is 5806."
}
}
func getMigrationAndEncryptionConfiguration() -> Realm.Configuration? {
let currentSchemaVersion: UInt64 = 19
if Keychain.getData(for: .realmEncryptionKey) == nil {
var key = Data(count: 64)
_ = key.withUnsafeMutableBytes { bytes in
SecRandomCopyBytes(kSecRandomDefault, 64, bytes)
}
Keychain.save(data: key, for: .realmEncryptionKey)
}
guard let key = Keychain.getData(for: .realmEncryptionKey) else {
return nil
}
let fileUrl = Realm.Configuration().fileURL!.deletingLastPathComponent()
.appendingPathComponent("Explorer.realm")
var config = Realm.Configuration(fileURL: fileUrl,
encryptionKey: key,
schemaVersion: currentSchemaVersion, migrationBlock: { (migration, oldVersion) in
if oldVersion != currentSchemaVersion {
print("we need migration!")
}
})
return config
}
I had another question opened for the same issue on SO, but it was closed because I didn't have enough details. After another release of my app with more logs, I could find the error that appears at initialisation of realm:
"Encrypted interprocess sharing is currently unsupported.DB has been opened by pid: 4848. Current pid is 5806. "
This appears after the app goes to background, it gets terminated (crash or closed by the system/user) and when the users opens it again, realm fails to init.
I read all about encrypted realm not being supported in app groups or in a share extension, but I didn't implement any of that in my app, is there any other reason why this error happens?
I also removed Firebase Performance from my app because I read that this module could generate issues on realm database, but it didn't help.
I opened an issue on realm github page, but I got no answer yet.
Does anyone have any idea how to fix this or why is this happening?
Thank you.

Related

Firebase realtime database query doesn't get new data until app reinstalled

In my app on sign up I'm checking if username is already taken.
I install the app, go to sign up, check if the username is free and everything works fine. If username is taken it tells me that.
But then when I created the account and trying to create another one with the same username, for some reason this username cant be found in database, even tho it's there.
Here is the code I use:
func singleObserveUser(withUsername username: String, completion: #escaping (UserModel) -> Void, onError: #escaping (String) -> Void) {
let queryUsername = username.lowercased().trimmingCharacters(in: .whitespaces)
usersRef.queryOrdered(byChild: Constants.UserData.UsernameLowercased).queryEqual(toValue: queryUsername).observeSingleEvent(of: .value) { (snapshot) in
if let _ = snapshot.value as? NSNull {
onError("No userdata found")
} else {
if let dict = snapshot.value as? [String: Any] {
let user = UserModel.transformDataToUser(dict: dict, id: snapshot.key)
completion(user)
} else {
onError("No userdata found")
}
}
}
}
If I restart app - everything is still the same.
If I delete app and install it again - everything works fine.
Seams like Firebase save some data on phone.
Thank you for your help!
If you have disk persistence enabled (the default on iOS and Android), the client stores data it has recently seen to allow it faster lookup later, and observeSingleEvent(of returns the value from that cache indeed.
If you want to ensure you have the latest value from the server, use getData instead as shown in the documentation on getting data once. Also check out Firebase Offline Capabilities and addListenerForSingleValueEvent for a longer explanation of the behavior.

Got an error when dragging files using NSEvent. (macOS)

I wanna drag files to my window and then perform actions.
I tried to use snippets below provided in this answer to distinguish whether you're dragging a file or a window.
// In my window controller
class MyWindowController: NSWindowController {
init() {
// Some initialization steps below are omitted
let win = NSWindow(...)
super.init(window: win)
let contentView = DropView(frame: win.frame)
win.contentView?.addSubview(contentView)
registerGlobalMouseEvent()
}
func registerGlobalMouseEvent() {
self.window?.acceptsMouseMovedEvents = true
NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDragged, handler: { [self] event in
// Codes below will cause errors
let pasteBoard = NSPasteboard(name: .drag)
guard let fileNames = pasteBoard.propertyList(forType: .init(rawValue: "NSFilenamesPboardType")) as? NSArray else { return }
let changeCount = pasteBoard.changeCount
if fileNames.count > 0 && lastChangeCount != changeCount {
lastChangeCount = changeCount
// My actions when dragging
}
})
}
}
Then I ran my codes and started dragging, I got three errors:
[sandbox] Failed to get a sandbox extension
[Framework] Failed to issue sandbox extension for /Users/roy/Downloads/test.txt with error 1
[default] Failed to issue sandbox token for URL: 'file:///Users/roy/Downloads/test.txt' with error: 'Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted" UserInfo={NSLocalizedDescription=Cannot issue a sandbox extension for file "/Users/roy/Downloads/test.txt": Operation not permitted}'
 
But when I just do
NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDragged, handler: { [self] event in
// My actions
})
, then everything went fine.
 
The first error seems harmless since it didn't prevent my app from running.
The second and the third ones are deadly and directly caused my app to crash.
I wonder if there are any problems in his code? Any useful thoughts would be great! :)
 
You need to know about Bookmarks and Security Scoped URLs when working with sandbox . A dragged URL gives your app process permission just once to read or read/write a “user selected file” depending on how you configure entitlements.
You can save a bookmark (blob of data) to keep access over subsequent sessions as long as the file isn’t updated by another process at which point the bookmark becomes stale and you will need to encourage the user to select the file again.
Handing a URL to another process across an XPC boundary like sharing requires that you own the file so may involve a copy to your sandbox cache.
e.g:
let dragurl = url_of_dragged_file //at this point you have at-least read access
let cachepath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
let cachedir = URL(fileURLWithPath: cachepath)
let cacheurl = cachedir
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension(dragurl.pathExtension)
try FileManager.default.copyItem(at: dragurl, to: cacheurl)
At this point you have a copy in your local sandbox cache that can be handed off to a share sheet.
So I finally got a solution for this. :)
It appears that it indeed have something to do with the snippets I mentioned above, and here's the correction:
NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDragged, handler: { [self] event in
let pasteboard = NSPasteboard(name: .drag)
let changeCount = pasteboard.changeCount
if lastChangeCount != changeCount {
lastChangeCount = changeCount
if pasteboard.canReadObject(forClasses: [NSURL.self], options: [:]) {
/// actions
}
}
})
In this way, I got no errors and my codes run perfectly!

CloudKit - "Invalid bundle ID for container"

I've just create a project in Xcode 9 beta 6 and add this code:
let privateDB = CKContainer.default().privateCloudDatabase
let greatID = CKRecordID(recordName: "GreatPlace")
let place = CKRecord(recordType: "Place", recordID: greatID)
privateDB.save(place) { (record, error) in
if error != nil {
let er = (error as! CKError).errorUserInfo
print("Error: \n")
print("CKErrorDescription: \(er["CKErrorDescription"]!)\n")
print("ContainerID: \(er["ContainerID"]!)\n")
print("NSDebugDescription: \(er["NSDebugDescription"]!)\n")
print("NSUnderlyingError: \(er["NSUnderlyingError"]!)\n")
print("NSLocalizedDescription: \(er["NSLocalizedDescription"]!)\n")
print("ServerErrorDescription: \(er["ServerErrorDescription"]!)\n")
}
if record != nil {
print("record: \(record!)")
}
}
and add this capabilities:
and when I run the code I receive this error message:
What I am doing wrong ?
There was a bug causing some associations to be missed. That bug has been fixed and we automatically fixed the container/app associations that were broken during that time.
If for some reason you still need to redo an association you can either use the Capabilities pane in Xcode or use developer.apple.com -> Certificates, Identifiers & Profiles -> App IDs -> pick the ID -> Edit -> Edit under iCloud -> check the box for the container to disassociate, save, then re-associate.
If you're still stuck please email cloudkit[at]apple.com
My friend and I are having the same issue. We made 2 different projects and both of them had the same error message "Invalid bundle ID for container" which is CKError case 10 .
We are calling our fetch function to get the default "Users" record in the viewDidLoad.
func fetchWorkoutCompleted(completion: #escaping (Error?) -> Void = { _ in }) {
cloudKitManager.fetchRecord(ofType: "Users", sortDescriptors: nil) { (records, error) in
if let error = error {
print(error.localizedDescription)
completion(error)
return
}
guard let records = records else { completion(nil); return }
completion(nil)
}
}
Using Xamarin.IOS, I had to select manual provisioning rather than automatic provisioning in the info.plist file.
Had the same issue. what worked for me was changing the iCloud group name.
Before it was something like this: iCloud.com.companyName.appName.randomString
After changing to: iCloud.com.companyName.randomString it started working and synchronising.
If after adding the new container it's red press the refresh button(from under the groups) and try a clean install on your phone and it should work
Thanks to Dave Browning, this is based on his answer.
Following worked for me:
Check the container id
Check the container id used for initialisation of CKContainer
Note: If you are using NSPersistentCloudKitContainer we wouldn't be using the container id directly would be picked automatically from the entitlements file.
Try to disable and enable iCloud on the App ID
Disable and Enable iCloud on App ID
Go to https://developer.apple.com and sign in
Select Certificates, Identifiers & Profiles
Select Identifiers (App IDs)
Edit App ID for the app
Uncheck iCloud
Save
Check iCloud
Quit Xcode and Clear DerivedData
Run app

CloudKit Error: Change Token Expired, Reset Needed

Swift 3.1, Xcode 8.3.3
I keep getting an error from CloudKit and I don't know what to do about it.
I'm tracking notifications from CloudKit like this:
let operation = CKFetchNotificationChangesOperation(previousServerChangeToken: previousChangeToken)
//Hold the notification IDs we processed so we can tell CloudKit to never send them to us again
var notificationIDs = [CKNotificationID]()
operation.notificationChangedBlock = { [weak self] notification in
guard let notification = notification as? CKQueryNotification else { return }
if let id = notification.notificationID {
notificationIDs.append(id)
}
}
operation.fetchNotificationChangesCompletionBlock = { [weak self] newToken, error in
if let error = error{
print(error) //<-- <!> This is the error <!>
}else{
self?.previousChangeToken = newToken
//All records are in, now save the data locally
let fetchOperation = CKFetchRecordsOperation(recordIDs: recordIDs)
fetchOperation.fetchRecordsCompletionBlock = { [weak self] records, error in
if let e = error {
print("fetchRecordsCompletionBlock Error fetching: \(e)")
}
//Save records to local persistence...
}
self?.privateDB.add(fetchOperation)
//Tell CloudKit we've read the notifications
let operationRead = CKMarkNotificationsReadOperation(notificationIDsToMarkRead: notificationIDs)
self?.container.add(operationRead)
}
}
container.add(operation)
And the error says:
<CKError 0x174241e90: "Change Token Expired" (21/1016); server message
= "Error code: RESET_NEEDED"; uuid = ...; container ID = "...">
The CKServerChangeToken documentation don't mention anything about resetting the token, and the CloudKit dashboard doesn't offer any such option.
Any idea what I'm supposed to do?
This error code is CKErrorCodeChangeTokenExpired, and it's an indication that you need to re-sync your changes.
https://developer.apple.com/documentation/cloudkit/ckerror/2325216-changetokenexpired
This error code gets returned when the change token is too old, or the container has been reset (resetting the container invalidates old change tokens).
The comments related to this error code include:
(Describing the code itself):
The previousServerChangeToken value is too old and the client must re-sync from scratch
(On various fetch operation completion/updated blocks):
If the server returns a CKErrorChangeTokenExpired error, the serverChangeToken used for this record zone when initting this operation was too old and the client should toss its local cache and re-fetch the changes in this record zone starting with a nil serverChangeToken.

Connecting to VPN with Swift 3

I'm trying to connect to a VPN in an iOS app. What I already know is the VPN type (L2TP over IPSec), account name, password and shared secret. The connection works through Mac's Network settings. Although, it seems a little more complicated, when you have to use this info in code.
First, I have imported the necessary library.
import NetworkExtension
Then, I'm trying to load preferences and in case of error, I'm using my own and save them. Looks like this:
NEVPNManager.shared().loadFromPreferences { error in
// config
NEVPNManager.shared().saveToPreferences { error in
if (error == nil) {
do {
try NEVPNManager.shared().connection.startVPNTunnel()
} catch {
print("Couldn't connect")
}
} else {
print("NEVPNManager.saveToPreferencesWithCompletionHandler failed: \(error!.localizedDescription)")
}
}
}
Where you can see the "// config", my data should be passed. I'm not 100% sure, if I'm doing it right.
There's a constant let p = NEVPNProtocolIPSec() where I'm placing my data. It's like p.username = "smth".
The question is: which fields of p should be filled? Where do I put the shared secret?
--- UPDATE ---
I'm always getting the error:
NEVPNManager.saveToPreferencesWithCompletionHandler failed: The operation couldn’t be completed. (NEVPNErrorDomain error 4.)
I can't find anything specific about that.
During the config, fields .sharedSecretReference and .passwordReference require the Data? object. I'm getting it by using keychain.get("passref")?.data(using: .utf8, allowLossyConversion: true) preceded by
let keychain: KeychainSwift! = KeychainSwift()
keychain.set("<my_password>", forKey: "passref")
(class KeychainSwift comes from here)
Where am I making a mistake?