App Crashed due to Invalid signature for pointer dequeued from free list in UIImagePickerController - malloc

I am facing problem in UIImagePickerController selection. When I choose source from Photo Library App crashes due to Invalid signature for pointer dequeued from free list. then If I run again it works fine with the same code. I searched on google and found one question related to my query Xcode - My app crash and the error is "Invalid pointer dequeued from free list *** set a breakpoint in malloc_error_break to debug" .
but solution isn't working in my case.
I am using Xcode 8.1 and my deployment Target is 8.0.

As #luke requested for the code for UIImagePickerViewController:
let pickerView = UIImagePickerController()
pickerView.delegate = self
pickerView.allowsEditing = true
pickerView.sourceType = .photoLibrary
let authStatus = PHPhotoLibrary.authorizationStatus() // Get the current authorization state.
// print(authStatus)
if (authStatus == PHAuthorizationStatus.notDetermined) {
// Access has not been determined.
PHPhotoLibrary.requestAuthorization({ (newStatus) in
if (newStatus == PHAuthorizationStatus.authorized) {
self.present(pickerView, animated: true, completion: { _ in })
}
else {
}
})
} else if authStatus == PHAuthorizationStatus.authorized {
print("Access has been granted.")
self.present(pickerView, animated: true, completion: { _ in })
} else if (authStatus == PHAuthorizationStatus.denied) {
print("Access has been denied.")
}
else if (authStatus == PHAuthorizationStatus.restricted) {
print("Restricted access - normally won't happen.")
}
Now when the user picks a particular image:
This method will be called:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//print(info)
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
YOUR_GLOBAL_IMAGE_VIEW?.contentMode = .scaleAspectFit
YOUR_GLOBAL_IMAGE_VIEW?.image = pickedImage
}
}
dismiss(animated: true, completion: nil)
}
Don't forget to import PhotosUI and UIImagePickerControllerDelegate.

Related

NSPersistentClouKitContainer creates CD_CKRecords but does not export values

I am converting existing app from NSPersistentContainer to NSPersistentCloudKitContainer
AppDelegate code:
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name:"GridModel")
// enable history tracking and remote notifications
guard let publicStoreDescription = container.persistentStoreDescriptions.first else {
fatalError("###\(#function): failed to retrieve a persistent store description.")
}
// public
let publicStoreUrl = publicStoreDescription.url!.deletingLastPathComponent().appendingPathComponent("GridModel-public.sqlite")
publicStoreDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
publicStoreDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
let containerIdentifier = publicStoreDescription.cloudKitContainerOptions!.containerIdentifier
let publicStoreOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: containerIdentifier)
if #available(iOS 14.0, *) {
publicStoreOptions.databaseScope = CKDatabaseScope.public
} else {
// Fallback on earlier versions???
}
publicStoreDescription.cloudKitContainerOptions = publicStoreOptions
print(containerIdentifier)
container.loadPersistentStores(completionHandler: { (loadedStoreDescription, error) in
if let loadError = error as NSError? {
fatalError("###\(#function): Failed to load persistent stores:\(loadError)")
} else if let cloudKitContainerOptions = loadedStoreDescription.cloudKitContainerOptions {
if #available(iOS 14.0, *) {
if .public == loadedStoreDescription.cloudKitContainerOptions?.databaseScope {
self._publicPersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
} else if .private == loadedStoreDescription.cloudKitContainerOptions?.databaseScope {
self._privatePersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
} else if .shared == cloudKitContainerOptions.databaseScope {
self._sharedPersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
}
} else {
// Fallback on earlier versions
}
} /*else if appDelegate.testingEnabled {
if loadedStoreDescription.url!.lastPathComponent.hasSuffix("private.sqlite") {
self._privatePersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
} else if loadedStoreDescription.url!.lastPathComponent.hasSuffix("shared.sqlite") {
self._sharedPersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
}
}*/
})
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.viewContext.transactionAuthor = appTransactionAuthorName
// Pin the viewContext to the current generation token, and set it to keep itself up to date with local changes.
container.viewContext.automaticallyMergesChangesFromParent = true
do {
try container.viewContext.setQueryGenerationFrom(.current)
} catch {
fatalError("###\(#function): Failed to pin viewContext to the current generation:\(error)")
}
#if DEBUG
do {
// Use the container to initialize the development schema.
try container.initializeCloudKitSchema(options: [])
} catch {
// Handle any errors.
fatalError("###\(#function): failed to load persistent stores: \(error)")
}
#endif
// Observe Core Data remote change notifications.
NotificationCenter.default.addObserver(self,
selector: #selector(storeRemoteChange(_:)),
name: .NSPersistentStoreRemoteChange,
object: container.persistentStoreCoordinator)
return container
}()
The very first time I run, Creates all the corresponding CD CKRecords in CloudKit public database _defaultZone. All values are copied from Core Data to CloudKit.
When the app is actively running I deleted a Core Data record and added a new record it did not delete it from Cloud Kit. Also when I add a new record in Core Data it did not export and add to Cloud Kit. When the app is actively running any changes I make are not exported and updated in Cloud Kit. What changes should I make to the code?
But when I run the app again then all the previous changes that I made when the app was active are updated. So looks like it does not perform live updates until the app is rerun again.
I get another error on the Debug Console "Custom zones are not allowed in public DB". I am not writing to custom DB. I wonder if this is preventing active updates?
oreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](1983): <NSCloudKitMirroringDelegate: 0x2824d16c0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringExportRequest: 0x280a84780> FDB61E8D-658F-4C77-8615-EF07BAB72BAD' due to error: <CKError 0x28119ba20: "Partial Failure" (2/1011); "Failed to modify some records"; uuid = 6C66A151-DB59-4A1B-B3BD-02CFB9A4139C; container ID = "iCloud.com.greenendpoint.nr2r"; partial errors: {
B-63B7-45D2-BFE0-599972FB6FD7:(com.apple.coredata.cloudkit.zone:defaultOwner) = <CKError 0x2810e44e0: "Server Rejected Request" (15/2027); server message = "Custom zones are not allowed in public DB"; op = 23AFDAC55F70DC8D; uuid = 6C66A151-DB59-4A1B-B3BD-02CFB9A4139C>
Please help!
It worked. I had to delete my app on the test device and restart again. Looks like it recreated the data store and synced with Cloud Kit.

CoreData context not updating and bool always false?

I am trying to update a user record with a boolean value in coredata. The record itself is updating, but I can only see the change between app sessions, not the same session.
Essentially, I am trying to trap the user agreeing or refusing the apps terms of use. A check is performed on the landing screen after login and if the terms have been agreed to, then continue as normal. However, if the terms have not been agreed to then I need to fire a popover allowing them to accept the terms (This happens every time they hit the landing page until they accept)
I am running the check but no matter what the value is in the core data record, it always evaluates as false:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
context.automaticallyMergesChangesFromParent = true
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
fetchRequest.predicate = NSPredicate(format: "email == %#", userEmail)
fetchRequest.returnsObjectsAsFaults = false
do {
userRecord = try context.fetch(User.fetchRequest())
if userRecord[0].acceptedTerms != nil && userRecord[0].acceptedTerms {
print("Terms accepted, move along")
} else {
print("Terms refused, pop dialog")
}
} catch {
print("No user found")
}
When a user accepts the terms, I try to update the core data record. Which does update, however I can only see the update between app sessions. Whilst in the same session, if the user hits the landing screen again, the value is still set to false (Or at least the acceptedTerms field in core data is still a 0) - I have done some searching on this and seen there is automaticallyMergesChangesFromParent and also refreshAllObjects() however neither seem to have any effect.
** Update with save code from AppDelegate **
func updateTermsComplete(userLogin: String, termsPermission: String){
let context = self.persistentContainer.viewContext
context.automaticallyMergesChangesFromParent = true
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
fetchRequest.predicate = NSPredicate(format: "email == %#", userLogin)
fetchRequest.returnsObjectsAsFaults = false
do {
userRecord = try context.fetch(fetchRequest) as! [User]
} catch {
print("No user found")
}
if !userRecord.isEmpty {
print("User already exists")
userRecord[0].setValue(termsPermission, forKey: "acceptedTerms")
do {
try context.save()
print("User updated")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
self.saveContext()
}
context.refreshAllObjects()
}
func saveContext () {
let context = persistentContainer.viewContext
context.automaticallyMergesChangesFromParent = true
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}

FBSDKLoginKit is crashing for unknown reason on iOS11.3 version

#IBAction func didTapLogainAction(_ sender: Any) {
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if (error == nil){
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if fbloginresult.grantedPermissions != nil {
if(fbloginresult.grantedPermissions.contains("email")) {
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
let dict = result as! [String : AnyObject]
FBSDKLoginManager().logOut()
}
})
}
}
}
}
}
}
Facebook login, when i'm press continue from facebook interface, it crashing on my iOS11.3 version. it quitely working good in ios11.4 and iOS11.03 lowers versions.
It got resolved by the Facebook developer team. Meanwhile, we have to use the following snippet for iOS11.3. If older Methods also will work i think.
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
}

How to present a view controller while performing background tasks?

I am using Parse.com and swift
I have an initial view controller that presents the parse.com login.
Once the login is complete and the objects are saved in the background I want to present my navigation controller's root view controller (first controller linked in the storyboard).
How is this done with all the asynchronous calls?
This is what I have but it jumps back to the login screen and doesn't
func signUpViewController(signUpController: PFSignUpViewController!, didSignUpUser user: PFUser!) {
currentUser = user as? User
currentUser!.isManager = false
var query = PFUser.query()
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if objects.count == 1 {
currentUser!.isManager = true
}
currentUser?.saveInBackgroundWithBlock({ (success: Bool, error: NSError!) -> Void in
if success == false || error != nil {
println(error)
} else {
currentCompany = Company()
currentCompany!.companyName = "My Company"
currentCompany!.saveInBackgroundWithBlock({ (success: Bool!, error: NSError!) -> Void in
if success == false {
println(error)
}
})
}
})
}
dismissViewControllerAnimated(true, completion: { () -> Void in
self.performSegueWithIdentifier("jumpFromInitialToMessages", sender: self)
// let vc = MessagesViewController()
// self.navigationController?.presentViewController(vc, animated: true, completion: nil)
})
}
If you want to initiate a UI transition/update inside the completion handler, you should insert a dispatch back to the main queue inside the completion handler closure:
var query = PFUser.query()
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
// do something
// when done, do some UI update, e.g. perform segue to another scene
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("identifier", sender: self)
}
}
This is an example with a simple query, but the idea works with any asynchronously called completion handler closure: Just dispatch the UI update back to the main queue from within the closure.

How to update the value of a boolean variable in swift?

I've spent the past 3 days trying to figure this out. I can easily do what I want to do in Java but as soon as I try to do it in Swift, Xcode gives me a hard time.
In this case, I am trying to retrieve a boolean object from Parse that will tell me whether the user's email has been verified. For some reason, whenever I tell to code to check to see if the object is false, checkEmail is apparently nil. Also worth noting, if I println(checkEmail) right after var checkEmail = User["emailVerified"] as Bool I get the correct boolean value (true or false).
Its looks like as soon as the code leaves the query function, the value for checkEmail is lost.
Any ideas on what I'm doing wrong?
import UIKit
class RegisterEmail: UIViewController {
var checkEmail: Bool?
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {
if identifier == "passEmail" {
var query = PFUser.query()
query.getObjectInBackgroundWithId("vFu93HatwL") {
(User: PFObject!, error: NSError!) -> Void in
if error == nil {
NSLog("%#", User)
} else {
NSLog("%#", error)
}
let checkEmail = User["emailVerified"] as Bool
println(checkEmail) //I get the correct value here
}
println(checkEmail) //The value is lost here
if (checkEmail == false) {
let alert = UIAlertView()
alert.title = "Error"
alert.message = "The email you have provided has not been verified."
alert.addButtonWithTitle("Dismiss")
alert.show()
return false
}
else {
return true
}
}
// by default, transition
return true
}
}
You're not assigning the new value to the object property, you're assigning it to a local variable. Get rid of the let keyword, which declares a new local variable, in:
let checkEmail = User["emailVerified"] as Bool

Resources