Can't instantiate a Realm - ios

Since last night, I haven't been able to save a transaction to Realm (only trying the default realm). Either the following code fails and executes the else block,
guard let realm = try? Realm() else { return }
or the transaction write block fails, printing an error out to the console:
Error occured when attemting to saving transaction. details: Error Domain=io.realm Code=1 "mmap() failed: Cannot allocate memory" UserInfo=0x16d17de0 {Error Code=1, NSLocalizedDescription=mmap() failed: Cannot allocate memory}
I'm pretty lost as to how to go about fixing this, I've got 3.2GB left on the device so there's plenty hard disk space left

Related

How does transactions in firestore error out?

I'm trying to produce an error in transaction and my question is when does transaction produces error ? I tried inserting random non existent collection and document, go offline, still it doesn't catch any error.
In what conditions does transaction error out ?
var db = Firestore.firestore()
let ref = db.collection("foo").document("bar")
db.runTransaction({ transaction, errorPointer -> Any? in
var document: DocumentSnapshot
do {
try document = transaction.getDocument(ref)
} catch let fetchError as NSError {
// no Error here even if ref doesn't exist or I go offline
errorPointer?.pointee = fetchError
return nil
}
return nil
}) { _, error in
if let error = error {
print("Transcation Completion Error: \(error)")
} else {
print("Transaction Succeeded!")
}
}
If you just want to test error handling then just throw your own error from within the transaction. The transaction closure has two arguments, the transaction object and an error pointer. Assign the error pointer an NSError and handle it in the completion block.
errorPointer?.pointee = NSError(domain: "yourDomain", code: 0, userInfo: nil)
Beyond this, a transaction could fail for a number of reasons, such as performing a read operation after a write operation, a network error, exceeding the allotted data-usage limit, or too many failed attempts at retrying the transaction (because the underlying documents were modified outside the transaction). Further reading at link below.
https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure
According to Firebase documentation, a transaction can fail following the next options:
After the write operations, the transaction contains read operations.
Before any write operations, read operations must always occur first.
The transaction read a document that had been changed outside of it.
In this instance, the transaction is restarted automatically. A
certain number of times the transaction is retried.
The transaction's request size exceeds the 10 MiB limit.
The size of a transaction is determined by the size of the documents
and index items that it modifies. This contains the size of the
target document and the sizes of the index items eliminated due to
the operation.
When a transaction fails, it generates an error and does not write any data to the database. You don't have to roll back the transaction because Cloud Firestore does it for you.
Also, I would like to suggest you to check the NSError for Swift, here is a Github Repository that provides information of NSError, as well as this documentation that also describes the NSError of how to handle failed transactions and give appropriate error messages to the user as a feedback.

Error: "connection to service named com.apple.MapKit.SnapshotService" when starting MKMapSnapshotter

I try to create a snapshot of my map view to display later so I don't have another map view wasting memory.
Most of the time it works just fine, but recently I tried creating a snapshot of Paris and got the Error: "connection to service named com.apple.MapKit.SnapshotService".
I know it looks like a cut a part but no, it seems this is the whole error description.
Full Error:
Error Domain=MKErrorDomain Code=1 "(null)" UserInfo=. {NSUnderlyingError=0x284562610 {Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.MapKit.SnapshotService" UserInfo={NSDebugDescription=connection to service named com.apple.MapKit.SnapshotService}}}
I've tried multiple times, but it seems when taking a snapshot of Paris it just won't ever work out as it does for other cities. I've really got no clue where I could start solving the problem as I didn't find any information on the origin of my error.
EDIT: The behaviour actually does appear seemingly random in other cities too.
In viewDidLoad I initialize my options object like so:
snapShotOptions.size = mapView.frame.size
snapShotOptions.scale = UIScreen.main.scale
snapShotOptions.showsBuildings = false
When the user now decides to go on, I initialize & start the snapshotter and handle data accordingly, before that I also set the region for the snapshot:
snapShotOptions.region = mapView.region
snapShotter = MKMapSnapshotter(options: snapShotOptions)
// Take a snapshot.
snapShotter.start { (snapshot, error) -> Void in
if error == nil {
completionHandler(snapshot?.image ?? UIImage())
} else {
print(error!)
}
}
I hope someone can help me out here or at least give me a clue as to what the error actually means!
Recently, I encountered the same phenomenon.
In my case, it happens when I take a snapshot in a situation where a memory warning is occurring.
If this issue has already been resolved, I would be grateful if you could provide information.

CoreData Error: Invalid generation token: this persistent store coordinator does not have any of the referenced stores

I'm unable to repro this error but my crash reporter indicates that it's fairly frequent among my users (iOS 12):
Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={Reason=Invalid generation token: this persistent store coordinator does not have any of the referenced stores}: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang_Fall2018/swiftlang_Fall2018-1000.11.42/src/swift/stdlib/public/core/ErrorType.swift, line 184
Crashing line example:
let result = try! self.syncContext.fetch(request)
I would like to decipher error message. Does Invalid generation token refers to NSQueryGenerationToken? Is the error part of conflict resolution process?

How to solve Core Data error in AppDelegate?

I created an application with Core Data. In the AppDelegate I have this code:
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Teste")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
I'd like to remove the fatalError and know how the typical reasons for an error can occurs that they talk about?
So you can remove or comment out the fatalError("Unresolved error \(error), \(error.userInfo)") line of code. If you read the first line in the comments "Replace this implementation with code to handle the error appropriately", it tells us that we are meant to use our own implementation, the fatalError() method is for your development purposes to be notified in debug that something went awry.
Typically caused by a misconfiguration of your project, or heaven forbid a failure to migrate between versions. In these situations you would hopefully have caught and fixed these issues before your project goes live, but if the error occurred because the device has run out of storage space or a permissions issue it would be best just to observe this error and whenever it occurs inform the user through an alert.

Failure to save data to HealthKit (Cocoa error 4097)

I'm currently having difficulty saving data to health kit and I'm unsure what the problem is. I have health kit enabled and have granted read and write permissions on my testing device when the app runs (everything looks OK and I'm able to query the health kit database without error). I'm using Swift.
The code I'm using to save is:
hksaver.healthStore!.saveObjects(samples, withCompletion: {
(success: Bool , error: NSError!) -> Void in
if success { ... } else {
println("Failed to save. Error: \(error)")
}
samples is an array of HKQuantity Samples. It is created by appending 'dataSample' as defined below:
let dataPoint = HKQuantity(unit: units, doubleValue: measurement.dataPoint)
let dataSample = HKQuantitySample(type: quantityType,
quantity: dataPoint, startDate: measurement.startDate,
endDate: measurement.endDate, metadata: metadata)
There are no errors when constructing this, so I believe that all the values are appropriate.
When I run, I'm getting the following error:
Failed to save. Error: Error Domain=NSCocoaErrorDomain Code=4097 "The
operation couldn’t be completed. (Cocoa error 4097.)" (connection to
service named com.apple.healthd.server) UserInfo=0x17047a0c0
{NSDebugDescription=connection to service named
com.apple.healthd.server}
I'm trying to write ~100,000 values to HealthKit though I haven't been able to find any limits (the same error occurred when I was trying to write ~50,000 values). I've tried to write this in chunks, but after around 5 calls to health kit it starts failing (I'm assuming there is a limit to prevent continuous calls although I haven't seen anything in any documentation I've looked at).
I've tried searching under the error code, under the entire error, and under everything I could think of to explain the problem. The only results I've returned deal with HomeKit and tend to be that it is not activated. However under the capabilities tab I have HealthKit turned on and everything is check marked so I don't think that is the problem.
Any thoughts would be appreciated!

Resources