As Parse crash report is depreciating, we are moving to Google Analytics.
I follow the guide to and receive view tracking and exception reports successfully.
here is how I setup the GA
// Configure tracker from GoogleService-Info.plist.
var configureError:NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError)")
// Optional: configure GAI options.
let gai = GAI.sharedInstance()
gai.trackerWithTrackingId("UA-XXXXXX-1")
gai.trackUncaughtExceptions = true // report uncaught exceptions
gai.dispatchInterval = 1
gai.defaultTracker.allowIDFACollection = true
#if DEBUG
gai.logger.logLevel = GAILogLevel.Verbose // remove before app release
#endif
And I tried to make a crash by (in AppDelegate.swift didFinishLaunchingWithOptions ):
delay(20.0) { () -> () in
let _ = [String]()[10];
}
And I can't get any crash report from GA dashboard.
I've tried to move this line to an IBAction, but failed.
My testing steps:
debug on device ->(20s)-> crash
debug on device 2nd time ->(20s)-> crash
run the app without debugging ->(20s)-> crash
run the app without debugging ->(20s)-> crash
It turns out that Google Analytics only supports reporting of uncaught Objective-C exceptions. It does not report Swift throws. The following creates a Swift throw (and is not reported by GA):
let crashArray:Array = [0]
crashArray[1]
The following does create an Objective-C exception and is reported by GA:
let array = NSArray()
let _ = array.objectAtIndex(99)
Some useful information here...
How should I use NSSetUncaughtExceptionHandler in Swift
We can force an Objective-C exception from within Swift by using the following command (i.e. from within a catch).
let error = NSError(domain: "Some error.", code: 0, userInfo: nil)
NSException.raise("Exception", format:"Error: %#", arguments:getVaList([error ?? "nil"]))
There is not a way I can find to automatically capture all throws and relay them as an Objective-C exception.
Related
I have the following taskGroup, using the async/await concurrency in Swift 5.5, where I iterate over meters, fetching onboardingMeter from Core Data. This works ok in around 4 out of 5 times, but then crashes the iOS app. I am testing this with deleting the app from the iOS device, and run the onboarding from the start. Sometimes I can run this with no problems 4 or 5 or 6 times in a row, then it suddenly crashes with the following error:
2021-09-05 09:11:01.095537+0200 Curro[12328:1169419] [error] error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
2021-09-05 09:11:01.095954+0200 Curro[12328:1169419] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet addObject:]: attempt to insert nil'
*** First throw call stack:
(0x1857b105c 0x19dc63f64 0x1858ba538 0x1858c5df8 0x1857c68bc 0x18ce313d8 0x18cd13314 0x18cd140cc 0x105616700 0x105626a90 0x185769ce4 0x185723ebc 0x1857373c8 0x1a0edd38c 0x1880dae9c 0x187e58864 0x18d36da2c 0x18d29ab70 0x18d27bf2c 0x1048bba04 0x1048bbab0 0x10551da24)
libc++abi: terminating with uncaught exception of type NSException
This is the code where it fails, the let onboardingMeter = await OnboardingMeter.fromMeterDict is never returned, I don't see the second print statement when it fails.
Is this an error in the Swift beta, or have I made any mistake here? I will try again when a new iOS 15 beta arrives, and when the official release of iOS 15 comes out.
await withTaskGroup(of: OnboardingMeter.self) { group in
for (number, codableAddress) in meters {
group.addTask {
print("The following statement sometimes fails to return an onboarding meter, resulting in a crash")
let onboardingMeter = await OnboardingMeter.fromMeterDict(number, address: codableAddress, in: moc)
print("onboardingMeter:", onboardingMeter)
return onboardingMeter
}
}
for await meter in group {
onboardingMeters.append(meter)
}
}
The OnboardingMeter.fromMeterDict function:
extension OnboardingMeter {
static func fromMeterDict(_ number: String, address: CodableAddress, in moc: NSManagedObjectContext) async -> OnboardingMeter {
let me: OnboardingMeter = await moc.findOrCreateInstance(of: self, predicate: NSPredicate(format: "number == \(number)"))
let address = await Address.createOrUpdate(from: address, in: moc)
await moc.perform {
me.address = address
me.number = number
}
return me
}
}
and findOrCreateInstance:
func findOrCreateInstance<T: NSManagedObject>(of type: T.Type, predicate: NSPredicate?) async -> T {
if let found = await self.findFirstInstance(of: type, predicate: predicate) {
return found
} else {
return T(context: self)
}
}
Although I'd need to see more code to confirm this, I believe that you're returning a managed object that is already registered to a managed object context. It is only valid to refer to such registered objects within the closure of a perform call. If you need to refer to a managed object between different execution contexts, either make use of the object ID and refetch as needed, or make use of the dictionary representation option of the fetch request:
let request: NSFetchRequest = ...
request.resultType = NSManagedObjectIDResultType // or NSDictionaryResultType
return request.execute()
I'd strongly encourage you to watch this video from WWDC. At the minute 10:39 they're talking exactly about this.
I'm trying to create a USDZ object with the tutorial from Apple
Creating 3D Objects from Photographs. I'm using the new PhotogrammetrySession within this sample project: Photogrammetry Command-Line App.
That's the code:
let inputFolderUrl = URL(fileURLWithPath: "/tmp/MyInputImages/")
let url = URL(fileURLWithPath: "MyObject.usdz")
var request = PhotogrammetrySession.Request.modelFile(url: url,
detail: .full)
guard let session = try PhotogrammetrySession(input: inputFolderUrl) else {
return
}
I'm getting the following error:
2021-06-12 21:53:56.968490+0200 HelloPhotogrammetry[15294:190841] ERROR cv3dapi.pg: Internal codes (1): 4011
2021-06-12 21:53:56.972113+0200 HelloPhotogrammetry[15294:190841] [Photogrammetry] No SfM map found in native output!
2021-06-12 21:53:56.972909+0200 HelloPhotogrammetry[15294:190841] [Photogrammetry] Got error in completion: reconstructionFailed(RealityFoundation.PhotogrammetrySession.Request.modelFile(url: OutputAR.usdz -- file:///Users/jonasdeichelmann/Library/Developer/Xcode/DerivedData/HelloPhotogrammetry-ghttmmgcrrhywqeebbrstrvxoikh/Build/Products/Debug/, detail: RealityFoundation.PhotogrammetrySession.Request.Detail.medium, geometry: nil), "Reconstruction failed!")
Request modelFile(url: OutputAR.usdz -- file:///Users/jonasdeichelmann/Library/Developer/Xcode/DerivedData/HelloPhotogrammetry-ghttmmgcrrhywqeebbrstrvxoikh/Build/Products/Debug/, detail: RealityFoundation.PhotogrammetrySession.Request.Detail.medium, geometry: nil) had an error: reconstructionFailed("Reconstruction failed!")
Processing is complete!
I'm using an M1 iMac with macOS Monterey 12.0 Beta (21A5248p) and Xcode 13.0 beta (13A5154h).
tl;dr: Try another set of images, probably there is something wrong with your set of images.
I've had it work successfully except in one instance, and I received the same error that you are getting. I think for some reason it didn't like the set of photos I took for that particular object. You could try taking just a few photos of another simple object and try again and see if that is the problem with your first run.
I am attempting to integrate with Plaid, their documentation is a link confusing to follow and their support team informed me they are working on it. I also reached out to them to see if they could help me with my current integration but they informed me they are not able to look at my code because every integration is different.
Per the Plaid documentation I added my ngrok url to the redirect uri section in the dashboard (This works with the Plaid Link demo app: https://github.com/plaid/plaid-link-ios).
Also I added allow arbitrary load to the info plist.
I was able to get their Plaid Link-demo app up and running but when I try to place this code in my project I get the following error:
Thread 12: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
// MARK: Start Plaid Link using a Link token
// For details please see https://plaid.com/docs/#create-link-token
func presentPlaidLinkUsingLinkToken() {
#warning("Replace <#GENERATED_LINK_TOKEN#> below with your link_token")
// In your production application replace the hardcoded linkToken below with code that fetches an link_token
// from your backend server which in turn retrieves it securely from Plaid, for details please refer to
// https://plaid.com/docs/#create-link-token
let linkToken = "TOKEN HERE"
// <!-- SMARTDOWN_PRESENT_LINKTOKEN -->
// With custom configuration using a link_token
var linkConfiguration = LinkTokenConfiguration(token: linkToken) { success in
print("public-token: \(success.publicToken) metadata: \(success.metadata)")
}
linkConfiguration.onExit = { exit in
if let error = exit.error {
print("exit with \(error)\n\(exit.metadata)")
} else {
print("exit with \(exit.metadata)")
}
}
let result = Plaid.create(linkConfiguration)
switch result {
case .failure(let error):
print("Unable to create Plaid handler due to: \(error)")
case .success(let handler):
// UI Update code here
handler.open(presentUsing: .viewController(self))
self.linkHandler = handler
}
// <!-- SMARTDOWN_PRESENT_LINKTOKEN -->
}
#IBAction func refreshButtonAction(_ sender: Any) {
// UI Update code here
self.presentPlaidLinkUsingLinkToken()
}
I tried to place the self.presentPlaidLinkUsingLinkToken() into the following snippet:
DispatchQueue.main.async {
self.presentPlaidLinkUsingLinkToken()
}
Also per the Plaid documentation I added the following method within my App delegate swift file:
// MARK: Continue Plaid Link for iOS to complete an OAuth authentication flow
// <!-- SMARTDOWN_OAUTH_SUPPORT -->
func application(_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: #escaping ([UIUserActivityRestoring]?) -> Void
) -> Bool {
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let webpageURL = userActivity.webpageURL else {
return false
}
// Check that the userActivity.webpageURL is the oauthRedirectUri
// configured in the Plaid dashboard.
guard let linkOAuthHandler = window?.rootViewController as? LinkOAuthHandling,
let handler = linkOAuthHandler.linkHandler,
webpageURL.host == linkOAuthHandler.oauthRedirectUri?.host &&
webpageURL.path == linkOAuthHandler.oauthRedirectUri?.path
else {
return false
}
// Continue the Link flow
if let error = handler.continueFrom(redirectUri: webpageURL) {
print("Unable to continue from redirect due to: \(error)")
}
return true
}
// <!-- SMARTDOWN_OAUTH_SUPPORT -->
But the same error occurs. Any suggestions will be appreciated.
In case anyone is having issues with this, I was able to figure it out. It is something incorrect in their cocoapod. Once, I downloaded and dragged the LinkKit Framework everything worked as expected. Also Plaid does not use their own cocoapod in their demo project, they do the manual install. Maybe they are working on this issue.
It's hard to tell without seeing the code in your application calling presentPlaidUsingLinkToken(), but your application is crashing on Thread 12. UIKit is not multi-threaded, so if you are presenting a view controller on a background thread you can expect crashes.
I see you tried a DispatchQueue.main.async, however I suspect you may have another threading issue going on.
Just putting this out there since this is one of few results for this issue: My issue was that I wasn't retaining the Handler object. As a result, the Plaid UI would never appear and no events would fire, leaving me with an endless spinner. Simply maintaining the reference in the class did the trick (as shown in the sample project and mentioned in passing in the documentation).
Kona Farry's solution above works. From Plaid docs:
Create a Handler - A Handler is a one-time use object used to open a Link session. The Handler must be retained for the duration of the Plaid SDK flow.
I'm trying to transcribe local audio files in my app.
Short files recognised fine, but if audio is more than about 15 min it is not. Console immediately shows this error:
2020-01-17 12:57:07.528986+0300 App[2816:791131] [Utility]
+[AFAggregator logDictationFailedWithError:] Error Domain=kAFAssistantErrorDomain Code=1107 "(null)"
This is my code:
let localRecognitionRequest = SFSpeechURLRecognitionRequest(url: fileUrl)
localRecognitionRequest.shouldReportPartialResults = false
if speechRecognizer.supportsOnDeviceRecognition {
localRecognitionRequest.requiresOnDeviceRecognition = true
}
recognitionTask = speechRecognizer.recognitionTask(with: localRecognitionRequest, delegate: self)
And when there is an error, only one delegate method fires:
func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishSuccessfully successfully: Bool) { }
with successfully = false
I have Xcode 11.3.1
Trying only on device - iPhone XS (iOS 13.3)
Have anyone faced this problem?
I was also seeing error code 1107 and as strange as this sounds, a Simulator reset fixed it for me.
While the simulator is selected:
Go to the top Menu
Select Device
Click on Erase All Content and Settings...
(Optional) Kill XCode and relaunch
This did the trick.
After upgrading to xCode6.1, I can't compile my project which is ok last time. I have never changed anything in this file. Please help me !!!
AppDelegate.swift:75:29:
errorWithDomain(_:code:userInfo:)' is unavailable: use object construction 'NSError(domain:code:userInfo:)
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PassNote.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
Try using this command in Xcode:
cmd + shift + k
Ah, i see. I am also developing in Swift and they changed some of the standart implementations.
All you need to do is change the function into what Xcode is saying.. :) I had like 90 changes in my project.
So you need to change it to this:
NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
I had this error when running my code in the new Xcode 6.3 Beta. This is part of the CoreData code that is generated, when you first create your app.
*********************************Before*******************************************
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error (error), (error!.userInfo)")
abort()
********************************After*********************************************
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
Swift 4
if this error is showing you in core data just delete/uninstall your app from simulator or phone(if you are running in phone) Click shift + cmd + H for go to Home and long press on app icon and now clean and built your app.
Clean - shift + cmd + k
Built - cmd + B
Run it.
This error shows because of you copied your project's folder from one computer and transfer it to another.
Reset content and settings on iOS Simulator worked for me.