compile error in AppDelegate.swfit when upgraded to Xcode 6.1 - swift

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.

Related

Swift Core Data Migration Crash : syntax error in "SELECT MAX(Z_PK) FROM (null)"

I'm trying out Core Data with a test project and I'm facing some issues with Core Data and migrations. During the lightweight automatic migration, a crash occurs with the following :
[logging] near "null": syntax error in "SELECT MAX(Z_PK) FROM (null)"
[error] error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134110)
CoreData: error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134110)
CoreData: annotation: userInfo:
CoreData: annotation: sourceURL : file:///var/mobile/Containers/Data/Application/D712273A-6E49-4B19-9919-3E55F6A5A37D/Library/Application%20Support/TestApp.sqlite
CoreData: annotation: reason : Cannot migrate store in-place: near "null": syntax error
CoreData: annotation: destinationURL : file:///var/mobile/Containers/Data/Application/D712273A-6E49-4B19-9919-3E55F6A5A37D/Library/Application%20Support/TestApp.sqlite
CoreData: annotation: NSUnderlyingError : Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={reason=near "null": syntax error, NSSQLiteErrorDomain=1, NSUnderlyingException=near "null": syntax error}
CoreData: annotation: storeType: SQLite
CoreData: annotation: configuration: (null)
CoreData: annotation: URL: file:///var/mobile/Containers/Data/Application/D712273A-6E49-4B19-9919-3E55F6A5A37D/Library/Application%20Support/TestApp.sqlite
CoreData: annotation: options:
CoreData: annotation: NSInferMappingModelAutomaticallyOption : 1
CoreData: annotation: NSMigratePersistentStoresAutomaticallyOption : 1
CoreData: annotation: NSPersistentStoreFileProtectionKey : NSFileProtectionComplete
CoreData: annotation: <NSPersistentStoreCoordinator: 0x281cf1500>: Attempting recovery from error encountered during addPersistentStore: Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration."
Here is the code of the PersistenceCointainer used to load database in the SwiftUI App :
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
for _ in 0..<10 {
let newItem = Relation(context: viewContext)
newItem.date = Date()
}
do {
try viewContext.save()
} catch {
// 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.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
var container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "TestApp")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
if let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
let sqliteURL = storeDirectory.appendingPathComponent("TestApp.sqlite")
//Set Protection for Core data sql file
let description = NSPersistentStoreDescription(url: sqliteURL)
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
description.setOption(FileProtectionType.complete as NSObject, forKey: NSPersistentStoreFileProtectionKey)
container.persistentStoreDescriptions = [description]
}
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)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
Here is more about the model I'm trying to change. I have a simple model called "Partner" :
I can show more details of the relations if necessary.
I'm simply adding a new String optional attribute, so I thought lightweight migration would be easy.
I have created a lot of test data to try some features and I'd enjoy avoiding to drop my database ^^ And since it's a test project I'd like to understand where the issue comes from to avoir repeating it.
Can anybody help understand where does this "SELECT MAX(Z_PK) FROM (null)" comes from and how I could fix it ?
Ok so I tried to dig inside the database and didn't find any strange-looking data.
I juste created a Mapping Model from the old to the new Partner Model, and specified that the new field should take the "default" value, and the migrations worked : so I guess I'll never know what was the real reason for this bug :)
My advice for anyone that would face this bug : try creating a Mapping Model (steps 7/8 in this tutorial)

CNContactStore execute fails

I am working out how to use the Contacts framework, however some fairly simple code to create a contact is failing with an unexpected result. This is my code:
let Store = CNContactStore()
Store.requestAccess(for: .contacts, completionHandler:{ success, error in
if success {
let Contact = CNMutableContact()
Contact.givenName = "Dave"
Contact.familyName = "Nottage"
let SaveRequest = CNSaveRequest()
SaveRequest.add(Contact, toContainerWithIdentifier: nil)
do {
try Store.execute(SaveRequest)
print("Success")
}
catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("No access")
}
})
..and this is the result:
2019-02-22 10:30:56.050344+1030 ContactsTest[30329:25254955] [default] Unable to load Info.plist exceptions (eGPUOverrides)
2019-02-22 10:30:57.973724+1030 ContactsTest[30329:25254955] Could not get real path for Address Book lock folder: open() for F_GETPATH failed.
2019-02-22 10:30:57.973954+1030 ContactsTest[30329:25254955] Unable to open file lock: <ABProcessSharedLock: 0x600001752ac0: name=(null), lockFilePath=(null), localLock=<NSRecursiveLock: 0x600002914a80>{recursion count = 0, name = nil}, fileDescriptor=-1> Error Domain=NSPOSIXErrorDomain Code=14 "Bad address" UserInfo={ABFileDescriptor=-1}
The operation couldn’t be completed. (Foundation._GenericObjCError error 0.)
Any ideas on what might be causing this?
Edit: Note also that this is being compiled for macOS 10.14 SDK, and is running on macOS 10.14.3
The answer is to check the Contacts checkbox of App Data in the App Sandbox section in Capabilities and turn on the switch for App Sandbox.
Make sure you added key NSContactsUsageDescription in Info.plist.
Please refer to link.
Important
An iOS app linked on or after iOS 10.0 must include in its Info.plist
file the usage description keys for the types of data it needs to
access or it will crash. To access Contacts data specifically, it must
include NSContactsUsageDescription.

core data lightweight migration in swift 3 not working

i am useing persistentContainer
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:"YiuPai")
let container = NSPersistentContainer(name:"YiuPai")
let storeUrl = self.applicationDocumentsDirectory.appendingPathComponent("YiuPai.sqlite")
print(storeUrl)
let description = NSPersistentStoreDescription(url: storeUrl)
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeUrl)]
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
}()
error i am geting
2017-08-24 16:37:43.912800+0530 YiuPai[1688:496051] [error] error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///var/mobile/Containers/Data/Application/81EC85D8-5C35-4090-8F2E-5229775F2D43/Documents/YiuPai.sqlite options:{
NSInferMappingModelAutomaticallyOption = 1;
NSMigratePersistentStoresAutomaticallyOption = 1;
} ... returned error Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={sourceURL=file:///var/mobile/Containers/Data/Application/81EC85D8-5C35-4090-8F2E-5229775F2D43/Documents/YiuPai.sqlite, reason=Can't copy source store to destination store path, destinationURL=file:///var/mobile/Containers/Data/Application/81EC85D8-5C35-4090-8F2E-5229775F2D43/Documents/.YiuPai.sqlite.migrationdestination_41b5a6b5c6e848c462a8480cd24caef3, NSUnderlyingError=0x170851460 {Error Domain=NSSQLiteErrorDomain Code=5 "(null)" UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/81EC85D8-5C35-4090-8F2E-5229775F2D43/Documents/.YiuPai.sqlite.migrationdestination_41b5a6b5c6e848c462a8480cd24caef3, Source database Path=/var/mobile/Containers/Data/Application/81EC85D8-5C35-4090-8F2E-5229775F2D43/Documents/YiuPai.sqlite, reason=Failed to replace destination database}}} with userInfo dictionary {
NSUnderlyingError = "Error Domain=NSSQLiteErrorDomain Code=5 \"(null)\" UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/81EC85D8-5C35-4090-8F2E-5229775F2D43/Documents/.YiuPai.sqlite.migrationdestination_41b5a6b5c6e848c462a8480cd24caef3, Source database Path=/var/mobile/Containers/Data/Application/81EC85D8-5C35-4090-8F2E-5229775F2D43/Documents/YiuPai.sqlite, reason=Failed to replace destination database}";
destinationURL = "file:///var/mobile/Containers/Data/Application/81EC85D8-5C35-4090-8F2E-5229775F2D43/Documents/.YiuPai.sqlite.migrationdestination_41b5a6b5c6e848c462a8480cd24caef3";
reason = "Can't copy source store to destination store path";
sourceURL = "file:///var/mobile/Containers/Data/Application/81EC85D8-5C35-4090-8F2E-5229775F2D43/Documents/YiuPai.sqlite";
}
How can I resolve this?
I think I had your error. Try settings your storeUrl like this:
let storeUrl = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!.appendingPathComponent("YiuPai.sqlite")

Cannot receive crash reports

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.

How to add more attributes to existing core data entity?

I have a project that is using core data , i need add more attributes(Columns) to existing entity (Column) , if i manually add attribute to data model app crash and it is due to context save which i used to insert data into table previously
Plz help .. Thank you
So my problem was I had no idea where this persistent store coordinator code goes. It turns out it is automatically created in your AppDelegate implementation when you check "Use Core Data" when creating the project.
So, from the second link here, all you need to do for a light-weight migration (adding new attributes and such) is the following:
Select your .xcdatamodeld
From the menu, choose Editor -> Add Model Version
Name the new version anything you wish, select previous version in "Based on model"
In File Inspector of the .xcdatamodeld, choose Model Version -> Current -> your new model version
Select your new model version inside the .xcdatamodeld in Project Navigator, and do the changes to your model
If you changed attribute names or types, create a mapping model, new file -> Core Data -> Mapping Model -> pick source and destination model versions
Update the mapping in the new mapping model
Change your AppDelegate persistent store coordinator code as follows.
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("<data model name>.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
let options = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true]
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options, error: &error) == nil {
coordinator = nil
// Report any error we got.
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()
}
return coordinator
}()
So you only add migration options to the addPersistentStoreWithType call.
If you are only adding attributes to an entity, you can use the automated lightweight migration in Core Data.
Basically all you have to do is pass an NSDictionary instance with the appropriate options when you're adding the persistent store. Here's a code snippet from the end of an accessor method for _persistentStoreCoordinator:
NSNumber *optionYes = [NSNumber numberWithBool:YES];
NSDictionary *options = [NSDictionary dictionaryWithObjects:#[optionYes] forKeys:#[NSMigratePersistentStoresAutomaticallyOption]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
NSLog(#"Error opening persistent store: %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
If your migration is too complex for a lightweight migration, you'll see an error. Otherwise the migration should run and your database will be updated to match your new schema.
Note that if you're doing this for real on a device, you should back up your .sqlite file first, in case something goes wrong in migration.