'Tried to save an object with a new, unsaved child.' swift parse - parse-platform

This is my code :
userEmployer.signUpInBackgroundWithBlock { (success, error) -> Void in
if error != nil {
let errorString = error?.userInfo["error"] as! String
} else {
var queryRole = PFRole.query()
queryRole?.whereKey("name", equalTo: "Employer")
queryRole?.getFirstObjectInBackgroundWithBlock({ (roleObject, error) -> Void in
if error == nil{
var roleToAddUser = roleObject as! PFRole
roleToAddUser.users.addObject(PFUser.currentUser()!)
roleToAddUser.saveInBackground()
}// end of it
})// end of query
}//end of else
}//end of signup
It's really weird because I have the same template of code for registering a different role and it works properly. It keeps throwing
'Tried to save an object with a new, unsaved child.'
I don't understand why it's throwing an error.
First throw call stack:
(
0 CoreFoundation 0x0000000106cddf45 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000106755deb objc_exception_throw + 48
2 CoreFoundation 0x0000000106cdde7d +[NSException raise:format:] + 205
3 post 0x0000000104ec93e2 -[PFPointerObjectEncoder encodeParseObject:] + 108
4 post 0x0000000104ec8874 -[PFEncoder encodeObject:] + 113
5 post 0x0000000104e97e3f __129+[PFRESTQueryCommand findCommandParametersWithOrder:conditions:selectedKeys:includedKeys:limit:skip:extraOptions:tracingEnabled:]_block_invoke97 + 1808
6 CoreFoundation 0x0000000106c4acb5 __65-[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:]_block_invoke + 85
7 CoreFoundation 0x0000000106c4abbd -[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:] + 237
8 post 0x0000000104e9764d +[PFRESTQueryCommand findCommandParametersWithOrder:conditions:selectedKeys:includedKeys:limit:skip:extraOptions:tracingEnabled:] + 911
9 post 0x0000000104e9727c +[PFRESTQueryCommand findCommandParametersForQueryState:] + 296
10 post 0x0000000104e96d2f +[PFRESTQueryCommand findCommandForQueryState:withSessionToken:] + 79
11 post 0x0000000104ea8c89 __78-[PFQueryController findObjectsAsyncForQueryState:withCancellationToken:user:]_block_invoke + 106
12 post 0x0000000104e4dd0e __37+[BFTask taskFromExecutor:withBlock:]_block_invoke + 78
13 post 0x0000000104e4f470 __55-[BFTask continueWithExecutor:block:cancellationToken:]_block_invoke_2 + 112
14 libdispatch.dylib 0x0000000108c18e5d _dispatch_call_block_and_release + 12
15 libdispatch.dylib 0x0000000108c3949b _dispatch_client_callout + 8
16 libdispatch.dylib 0x0000000108c21bef _dispatch_root_queue_drain + 1829
17 libdispatch.dylib 0x0000000108c214c5 _dispatch_worker_thread3 + 111
18 libsystem_pthread.dylib 0x0000000108f81a9d _pthread_wqthread + 729
19 libsystem_pthread.dylib 0x0000000108f7f3dd start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
added info: When I tap the register button it goes to the tableviewcontroller, I tried removing the segue and it registered the user. seems like the error is inside my tableviewconller. this is the code inside.
//creating a pointer
var userPointer = PFUser.objectWithoutDataWithObjectId(PFUser.currentUser()?.objectId)
query.whereKey("postedBy", equalTo: userPointer)
query.orderByDescending("createdAt")
if PFUser.currentUser() != nil {//added1
let objects = query.findObjects()
for object in (objects as? [PFObject])!{
//print(object.objectId)
self.dataSource.append(object)
self.createdByDate.append((object.objectForKey("closingDate") as? NSDate)!)
print(dataSource)
print(createdByDate)
}
let itemArr:PFObject = self.dataSource[indexPath.row] as! PFObject
cell?.companyPostLabel.text = (PFUser.currentUser()?.objectForKey("companyName")!.capitalizedString)! as String
cell?.occupationPostLabel.text = itemArr["occupation"]!.capitalizedString as! String
let companyImage: PFFile?
companyImage = PFUser.currentUser()?.objectForKey("profileImageEmployer") as! PFFile
companyImage?.getDataInBackgroundWithBlock({ (data, error) -> Void in
if error == nil{
cell?.companyLogoImage.image = UIImage(data: data!)
}
})
} else {
print("user not found")
}
let dateArr = createdByDate[indexPath.row]
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd' : 'hh':'mm'"
var strDate = dateFormatter.stringFromDate(dateArr)
cell?.closingDateLabel .text = strDate
edit 2 : This line is throwing the error
let query = PFQuery(className: "JobPost")
//creating a pointer
var userPointer = PFUser.objectWithoutDataWithObjectId(PFUser.currentUser()?.objectId)
query.whereKey("postedBy", equalTo: userPointer)
let objects = query.findObjects()
return (objects?.count)!

Make sure your currentUser is saved first. You can check with it's objectId.
if ([PFUser currentUser].objectId == nil)
[[PFUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
// Perform queryRole
}];
else
// Perform queryRole directly

Related

How to retrieve data from VCard using swift

I'm working on QR code scanning. Using the following swift code, the data in the QR code is getting printed in the console.
import UIKit
import AVFoundation
class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate
{
let session = AVCaptureSession()
#IBOutlet weak var square: UIImageView!
var video = AVCaptureVideoPreviewLayer()
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
if metadataObjects != nil && metadataObjects.count != 0
{
if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject
{
if object.type == AVMetadataObjectTypeQRCode
{
print(object.stringValue)
let alert = UIAlertController(title: "QR Code", message: object.stringValue, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okey", style: .default, handler: nil))
/* alert.addAction(UIAlertAction(title: "Copy", style: .default, handler: { (nil) in
UIPasteboard.general.string = object.stringValue
}))
*/
present(alert, animated: true, completion: nil)
if metadataObjects.count > 0
{
print("-------------------------------------------------")
self.session.stopRunning()
}
}
}
}
}
#IBAction func startButton(_ sender: Any)
{
// Creating session
// let session = AVCaptureSession()
// Define capture device
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
session.addInput(input)
} catch {
print("Error")
}
let output = AVCaptureMetadataOutput()
session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
video = AVCaptureVideoPreviewLayer(session: session)
video.frame = view.layer.bounds
view.layer.addSublayer(video)
self.view.bringSubview(toFront: square)
session.startRunning()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
OUTPUT:
BEGIN:VCARD
VERSION:2.1
FN:John Peter
N:Peter;John
TITLE:Admin
TEL;CELL:+91 431 524 2345
TEL;WORK;VOICE:+91 436 542 8374
EMAIL;WORK;INTERNET:John#ommail.in
URL:www.facebook.com
ADR;WORK:;;423 ofce sales Center;Newark;DE;3243;USA
ORG:xxx Private limited
END:VCARD
Now what I want is, how to retrieve the data in the VCard format specifically, like getting first name, last name, email id, mobile number, etc. A similar question to this is asked before, but it was in objective-c. I don't know how to do this swift 3. Thanks in advance.
Here's a sample code from Playground I used. It's not the best, but You'll get the idea:
import UIKit
import Contacts
var str = "BEGIN:VCARD \n" +
"VERSION:2.1 \n" +
"FN:John Peter \n" +
"N:Peter;John \n" +
"TITLE:Admin \n" +
"TEL;CELL:+91 431 524 2345 \n" +
"TEL;WORK;VOICE:+91 436 542 8374 \n" +
"EMAIL;WORK;INTERNET:John#ommail.in \n" +
"URL:www.facebook.com \n" +
"ADR;WORK:;;423 ofce sales Center;Newark;DE;3243;USA \n" +
"ORG:xxx Private limited \n" +
"END:VCARD"
if let data = str.data(using: .utf8) {
let contacts = try CNContactVCardSerialization.contacts(with: data)
let contact = contacts.first
print("\(String(describing: contact?.familyName))")
}
The output from CNContactVCardSerialization.contacts(with: data) is an array of CNContact (reference).
Here you can check Updated answer for swift 4 of Mateusz Szlosek
var str = "BEGIN:VCARD \n" +
"VERSION:2.1 \n" +
"FN:John Peter \n" +
"N:Peter;John \n" +
"TITLE:Admin \n" +
"TEL;CELL:+91 431 524 2345 \n" +
"TEL;WORK;VOICE:+91 436 542 8374 \n" +
"EMAIL;WORK;INTERNET:John#ommail.in \n" +
"URL:www.facebook.com \n" +
"ADR;WORK:;;423 ofce sales Center;Newark;DE;3243;USA \n" +
"ORG:xxx Private limited \n" +
"END:VCARD"
func fectchContact(){
if let data = str.data(using: .utf8) {
do{
let contacts = try CNContactVCardSerialization.contacts(with: data)
let contact = contacts.first
print("\(String(describing: contact?.familyName))")
}
catch{
// Error Handling
print(error.localizedDescription)
}
}
}

[PFUserAuthenticationController registerAuthenticationProvider:]: unrecognized selector sent to instance 0x7f96c1fa6090

Getting this error in the logs:
2016-03-18 18:53:54.915 Tinder[715:229250] -[PFUserAuthenticationController registerAuthenticationProvider:]: unrecognized selector sent to instance 0x7f96c1fa6090
2016-03-18 18:53:54.919 Tinder[715:229250] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PFUserAuthenticationController registerAuthenticationProvider:]: unrecognized selector sent to instance 0x7f96c1fa6090'
*** First throw call stack:
(
0 CoreFoundation 0x0000000102e2ae65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000104f0fdeb objc_exception_throw + 48
2 CoreFoundation 0x0000000102e3348d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x0000000102d8090a ___forwarding___ + 970
4 CoreFoundation 0x0000000102d804b8 _CF_forwarding_prep_0 + 120
5 Tinder 0x000000010249506a +[PFFacebookUtils initializeFacebookWithApplicationLaunchOptions:] + 225
6 Tinder 0x00000001023b3ccd _TFC6Tinder11AppDelegate11applicationfS0_FTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVSs10DictionaryCSo8NSObjectPSs9AnyObject____Sb + 541
7 Tinder 0x00000001023b4a53 _TToFC6Tinder11AppDelegate11applicationfS0_FTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVSs10DictionaryCSo8NSObjectPSs9AnyObject____Sb + 179
8 UIKit 0x00000001039e31f1 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 272
9 UIKit 0x00000001039e4397 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3415
10 UIKit 0x00000001039eacc6 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1760
11 UIKit 0x00000001039e7e7b -[UIApplication workspaceDidEndTransaction:] + 188
12 FrontBoardServices 0x000000010657e754 -[FBSSerialQueue _performNext] + 192
13 FrontBoardServices 0x000000010657eac2 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
14 CoreFoundation 0x0000000102d56a31 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
15 CoreFoundation 0x0000000102d4c95c __CFRunLoopDoSources0 + 556
16 CoreFoundation 0x0000000102d4be13 __CFRunLoopRun + 867
17 CoreFoundation 0x0000000102d4b828 CFRunLoopRunSpecific + 488
18 UIKit 0x00000001039e77cd -[UIApplication _run] + 402
19 UIKit 0x00000001039ec610 UIApplicationMain + 171
20 Tinder 0x00000001023b57ad main + 109
21 libdyld.dylib 0x0000000105a5a92d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Also getting an error in my code:
Thread 1: signal SIGABRT
but I don't yet have any outlets in my code.
My code in AppDelegate.swift (personal info replaced by "xxx"):
import UIKit
import Parse
import Bolts
// If you want to use any of the UI components, uncomment this line
// import ParseUI
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Enable storing and querying data from Local Datastore.
// Remove this line if you don't want to use Local Datastore features or want to use cachePolicy.
Parse.enableLocalDatastore()
let parseConfiguration = ParseClientConfiguration(block: { (ParseMutableClientConfiguration) -> Void in
ParseMutableClientConfiguration.applicationId = "xxx"
ParseMutableClientConfiguration.clientKey = "xxx"
ParseMutableClientConfiguration.server = "https://yourapp.herokuapp.com/parse"
})
Parse.initializeWithConfiguration(parseConfiguration)
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
PFUser.enableAutomaticUser()
let defaultACL = PFACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.publicReadAccess = true
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var noPushPayload = false;
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil;
}
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let userNotificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
let types: UIRemoteNotificationType = [UIRemoteNotificationType.Badge, UIRemoteNotificationType.Alert, UIRemoteNotificationType.Sound]
application.registerForRemoteNotificationTypes(types)
}
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
//--------------------------------------
// MARK: Push Notifications
//--------------------------------------
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
// PFPush.subscribeToChannelInBackground("") { (succeeded: Bool, error: NSError?) in
// if succeeded {
// print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.");
// } else {
// print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %#.", error)
// }
// }
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
func application(application: UIApplication,
openURL url: NSURL,
sourceApplication: String?,
annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
}
I managed to fix this error doing the following:
First I deployed the official version of Parse Server (instead of Rob's version). Open this link and click 'Deploy to Heroku', follow the steps.
https://github.com/ParsePlatform/parse-server-example
After that I downloaded the Parse Frameworks (including Facebook framework) from the link below and replaced all current frameworks in my project with these frameworks downloaded.
https://parse.com/downloads/ios/parse-library/latest
Other than that just follow the class steps (adding code to AppDelegate, Info.pslist e etc.
Any problems, let me know.
Check this link : Parse - Facebook SDK Exception
I think the problem is in this line of code:
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
I see that you are using latest Facebook and Parse version. But are you sure the latest versions are referenced? (maybe in podspecs, or podfile). Try the old good command to delete Derived Data (cmd + shift + k and cmd + shift + alt + k)
This kind of error are due to a nil object referencing a method class. Check if this is happening also.

querying an object with a pointer - parse, swift2

I have 2 classes, I have an Activity Class and JobPost class, in my Activity class there is an object called "postedJob" which is a pointer(JobPost), it stores the objectID of every job posted.
What I am trying to achieve is to query the postedJob from activity, but my code below form parse is throwing an error.
let jobPostObject = PFObject(className: "JobPost")
let query = PFQuery(className: "Activity")
query.whereKey("postedJob", equalTo: jobPostObject)
let objects = query.findObjects()
print(objects)
I dont understand why it's returning this error below
'Tried to save an object with a new, unsaved child.'
*** First throw call stack:
(
0 CoreFoundation 0x0000000108213f45 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000107c8bdeb objc_exception_throw + 48
2 CoreFoundation 0x0000000108213e7d +[NSException raise:format:] + 205
3 post 0x00000001063c5e92 -[PFPointerObjectEncoder encodeParseObject:] + 108
4 post 0x00000001063c5324 -[PFEncoder encodeObject:] + 113
5 post 0x00000001063948ef __129+[PFRESTQueryCommand findCommandParametersWithOrder:conditions:selectedKeys:includedKeys:limit:skip:extraOptions:tracingEnabled:]_block_invoke97 + 1808
6 CoreFoundation 0x0000000108180cb5 __65-[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:]_block_invoke + 85
7 CoreFoundation 0x0000000108180bbd -[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:] + 237
8 post 0x00000001063940fd +[PFRESTQueryCommand findCommandParametersWithOrder:conditions:selectedKeys:includedKeys:limit:skip:extraOptions:tracingEnabled:] + 911
9 post 0x0000000106393d2c +[PFRESTQueryCommand findCommandParametersForQueryState:] + 296
10 post 0x00000001063937df +[PFRESTQueryCommand findCommandForQueryState:withSessionToken:] + 79
11 post 0x00000001063a5739 __78-[PFQueryController findObjectsAsyncForQueryState:withCancellationToken:user:]_block_invoke + 106
12 post 0x000000010634a7be __37+[BFTask taskFromExecutor:withBlock:]_block_invoke + 78
13 post 0x000000010634bf20 __55-[BFTask continueWithExecutor:block:cancellationToken:]_block_invoke_2 + 112
14 libdispatch.dylib 0x000000010a2f1e5d _dispatch_call_block_and_release + 12
15 libdispatch.dylib 0x000000010a31249b _dispatch_client_callout + 8
16 libdispatch.dylib 0x000000010a2fabef _dispatch_root_queue_drain + 1829
17 libdispatch.dylib 0x000000010a2fa4c5 _dispatch_worker_thread3 + 111
18 libsystem_pthread.dylib 0x000000010a65a4f2 _pthread_wqthread + 1129
19 libsystem_pthread.dylib 0x000000010a658375 start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Edit 1 :
Import UIKit
class ActivityEmployerVC: UITableViewController {
var num = 0
var postJob: String?
var dataSource: [PFObject] = []
//MARK: - PULL TO REFRESH FUNCTION
func refresh(sender:AnyObject) {
// Updating your data here...
self.fetchDataFromParse()
self.refreshControl?.endRefreshing()
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = UIColor(netHex: 0x003366)
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
// Do any additional setup after loading the view.
self.refreshControl?.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
//self.refreshControl?.backgroundColor = UIColor(netHex: 0x003366)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
fetchDataFromParse()
}
//MARK: - TABLE VIEW
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let query = PFQuery(className: "Activity")
let userPointer = PFUser.objectWithoutDataWithObjectId(PFUser.currentUser()?.objectId)
query.whereKey("fromUser", equalTo: userPointer)
let objects = query.findObjects()
self.num = (objects?.count)!
print(num)
return num
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cells"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier , forIndexPath: indexPath)
if dataSource.isEmpty{
fetchDataFromParse()
print("No Post")
} else {
if num == 0{
cell.textLabel?.text = "Start posting a job!"
} else {
//MARK: - TABLEVIEW TITLE CELL
let itemArr:PFObject = self.dataSource[indexPath.row]
postJob = itemArr["type"] as? String
if postJob == "jobPost"{
let jobPostObject = PFObject(className: "JobPost")
let query = PFQuery(className: "Activity")
query.whereKey("postedJob", equalTo: jobPostObject)
let objects = query.findObjects()
print(objects)
cell.textLabel?.text = "You posted a job - \(postJob!)"
}
//MARK: - TABLEVIEW DATE CELL
let createdDate = itemArr.createdAt
let form = NSDateComponentsFormatter()
form.maximumUnitCount = 2
form.unitsStyle = .Abbreviated // or .Full, whatever you prefer
let d = form.stringFromTimeInterval(NSDate.timeIntervalSinceReferenceDate() - createdDate!.timeIntervalSinceReferenceDate)
cell.detailTextLabel?.text = "\(d!) ago"
}//end of if num
}//end of datasource.isempty
return cell
}
//MARK: - DATA FETCHING FUNCTIONS
func fetchDataFromParse() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
//MARK: - CLEARING ARRAYS
self.dataSource.removeAll()
// MARK: - JOB POST QUERY
if PFUser.currentUser()?.objectId == nil{
PFUser.currentUser()?.saveInBackgroundWithBlock({ (success, error) -> Void in
let query = PFQuery(className: "Activity")
//creating a pointer
let userPointer = PFUser.objectWithoutDataWithObjectId(PFUser.currentUser()?.objectId)
query.whereKey("fromUser", equalTo: userPointer)
query.orderByDescending("createdAt")
let objects = query.findObjects()
for object in (objects as? [PFObject])!{
//print(object.objectId)
self.dataSource.append(object)
}//end of for loop
})//end of saveInBackground
} else {
let query = PFQuery(className: "Activity")
//creating a pointer
let userPointer = PFUser.objectWithoutDataWithObjectId(PFUser.currentUser()?.objectId)
query.whereKey("fromUser", equalTo: userPointer)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock({ (objs, error) -> Void in
if error == nil {
for obj in (objs as? [PFObject])!{
//print(object.objectId)
self.dataSource.append(obj)
self.tableView.reloadData()
}//for loop
}//end of error == nil
})// end of findobjectsinbackground
print("query executed")
}//end of PFUser objectID == nil else clause
})
}
}
EDIT 2:
This is happening because jobPostObject is not a complete object, it's just an empty, unsaved JobPost.
The query itself doesn't make a lot of sense:
You first create a new JobPost
let jobPostObject = PFObject(className: "JobPost")
Then you are trying to find an Activity associated to this JobPost:
query.whereKey("postedJob", equalTo: jobPostObject)
Since jobPostObject is brand new, has no data, and more importantly, has never been saved to parse, how could this request return anything?
That's being said this error:
Tried to save an object with a new, unsaved child
means that you are trying to use an object that is dirty in a query. A dirty object is an object that is new OR is an existing object that has been modified, but that hasn't been saved in the database.
Try to add
query.includeKey("postedJob")
after all your
let query = PFQuery(className: "Activity")
then you can replace the jobPostObject part:
let jobPostObject = PFObject(className: "JobPost")
let query = PFQuery(className: "Activity")
query.whereKey("postedJob", equalTo: jobPostObject)
let objects = query.findObjects()
print(objects)
by something like
let jobPostObject = itemArr["postedJob"] as? PFObject

EXC_BAD_ACCESS on device ONLY

So after updating xCode to version 7.1 this morning, my project suddenly crashes and throws "EXC_BAD_ACCESS (CODE = 1)" anytime I access any part of an object in a submodule but ONLY when I build on an iOS device. In simulator, I can't reproduce the issue. I've checked for zombie objects in instruments and the app just crashes without producing any warning in instruments like it would when a zombie is found. I've cloned a new version of my repo and re-added the submodule thinking maybe it had something to do with xCode itself but the issue still persists. I decided I would try to access the object in appDelegate and even there, I get the same result. Here is where the issue was originally presented:
As you can see, there is absolutely no information as to what's causing it. I move up the stack trace and everything is in assembly. Abstract User is part of a submodule but has never presented any problems until the last update. Here is the stack trace:
thread #1: tid = 0x14d13, 0x00000001011f5ad8 libswiftCore.dylibswift_initStructMetadata_UniversalStrategy + 56, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x91)
frame #0: 0x00000001011f5ad8 libswiftCore.dylibswift_initStructMetadata_UniversalStrategy + 56
frame #1: 0x0000000101162d14 libswiftCore.dylib___lldb_unnamed_function201$$libswiftCore.dylib + 84
frame #2: 0x00000001011f712c libswiftCore.dylib(anonymous namespace)::GenericCacheEntry* llvm::function_ref<(anonymous namespace)::GenericCacheEntry* ()>::callback_fn(long) + 36
frame #3: 0x00000001011f6fdc libswiftCore.dylibswift::MetadataCache<(anonymous namespace)::GenericCacheEntry>::addMetadataEntry(swift::EntryRef<(anonymous namespace)::GenericCacheEntry>, ConcurrentList<swift::MetadataCache<(anonymous namespace)::GenericCacheEntry>::EntryPair>&, llvm::function_ref<(anonymous namespace)::GenericCacheEntry* ()>) + 156
frame #4: 0x00000001011f3c50 libswiftCore.dylibswift_getGenericMetadata + 416
frame #5: 0x00000001011f3ccc libswiftCore.dylibswift_getGenericMetadata2 + 24
frame #6: 0x00000001010b1538 libswiftCore.dylibSwift._NativeDictionaryStorage.maybeGet (Swift._NativeDictionaryStorage)(A) -> Swift.Optional + 76
frame #7: 0x000000010109f4e8 libswiftCore.dylibSwift._VariantDictionaryStorage.maybeGet <A, B where A: Swift.Hashable> (Swift._VariantDictionaryStorage<A, B>)(A) -> Swift.Optional<B> + 92
frame #8: 0x000000010109f440 libswiftCore.dylibSwift.Dictionary.subscript.getter : (A) -> Swift.Optional + 168
frame #9: 0x0000000100e3d2ec ServiceKitServiceKit.ServiceModel.init (dictionary=<unavailable>, self=<unavailable>)(dictionary : Swift.Dictionary<Swift.String, Swift.AnyObject>) -> ServiceKit.ServiceModel + 316 at ServiceModel.swift:88
frame #10: 0x0000000100e1e438 ServiceKitServiceKit.AbstractUser.init (dictionary=, self=)(dictionary : Swift.Dictionary) -> ServiceKit.AbstractUser + 180 at User.swift:36
frame #11: 0x0000000100e205fc ServiceKitServiceKit.User.init (dictionary=<unavailable>, self=<unavailable>)(dictionary : Swift.Dictionary<Swift.String, Swift.AnyObject>) -> ServiceKit.User + 344 at User.swift:744
frame #12: 0x0000000100e26f48 ServiceKitServiceKit.ConsumerUser.init (dictionary=, self=)(dictionary : Swift.Dictionary) -> ServiceKit.ConsumerUser + 264 at User.swift:351
frame #13: 0x0000000100e26e34 ServiceKit`ServiceKit.ConsumerUser.__allocating_init (dictionary=, $metatype=)(dictionary : Swift.Dictionary) -> ServiceKit.ConsumerUser + 88 at User.swift:0
frame #14: 0x000000010027910c Service.comService_com.SignInViewController.signUserIn (sender=0x0000000158576b70, self=0x000000015865a760)(Service_com.MKButton) -> () + 1416 at SignInViewController.swift:62
frame #15: 0x0000000100279310 Service.com#objc Service_com.SignInViewController.signUserIn (Service_com.SignInViewController)(Service_com.MKButton) -> () + 68 at SignInViewController.swift:0
frame #16: 0x0000000189403cfc UIKit-[UIApplication sendAction:to:from:forEvent:] + 100
frame #17: 0x0000000189403c78 UIKit-[UIControl sendAction:to:forEvent:] + 80
frame #18: 0x00000001893eb930 UIKit-[UIControl _sendActionsForEvents:withEvent:] + 416
frame #19: 0x0000000189403590 UIKit-[UIControl touchesEnded:withEvent:] + 572
frame #20: 0x00000001894031c0 UIKit-[UIWindow _sendTouchesForEvent:] + 804
frame #21: 0x00000001893fbcdc UIKit-[UIWindow sendEvent:] + 784
frame #22: 0x00000001893cc4a4 UIKit-[UIApplication sendEvent:] + 248
frame #23: 0x00000001893ca76c UIKit_UIApplicationHandleEventQueue + 5528
frame #24: 0x0000000183df0544 CoreFoundation__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
frame #25: 0x0000000183deffd8 CoreFoundation__CFRunLoopDoSources0 + 540
frame #26: 0x0000000183dedcd8 CoreFoundation__CFRunLoopRun + 724
frame #27: 0x0000000183d1cca0 CoreFoundationCFRunLoopRunSpecific + 384
frame #28: 0x000000018ef58088 GraphicsServicesGSEventRunModal + 180
frame #29: 0x0000000189434ffc UIKitUIApplicationMain + 204
frame #30: 0x000000010029d09c Service.commain + 136 at AppDelegate.swift:45
frame #31: 0x000000019923a8b8 libdyld.dylibstart + 4
I've tried everything I can think of and followed numerous tutorials and debugging Bad Access errors and nothing helps. I almost feel like it's an Xcode issue but I have no idea. Here is the AbstractUser class if it helps:
public class AbstractUser: ServiceModel {
/// Date of last login
private(set) var lastLogin = NSDate()
/// Password (please, don't use this field stupidly...)
private(set) var password = String.empty
public struct SerializationKeys {
public static let lastLogin = "last_login"
public static let password = "password"
}
// MARK: - Copyable
public required init(source: Copyable) {
super.init(source: source)
let u = source as! AbstractUser
lastLogin = u.lastLogin
password = u.password
}
// MARK: - JSONSerializable
public required init(dictionary: [String : AnyObject]) {
super.init(dictionary: dictionary)
lastLogin = lastLogin <|? dictionary[SerializationKeys.lastLogin]
password = password <|? dictionary[SerializationKeys.password]
}
public override func toDictionary() -> [String : AnyObject] {
var dictionary = super.toDictionary()
dictionary[SerializationKeys.lastLogin] = lastLogin.toString()
dictionary[SerializationKeys.password] = password
return dictionary
}
// MARK: - ModelType
public override func updateObject(newVersion: ModelType) {
super.updateObject(newVersion)
let u = newVersion as! AbstractUser
lastLogin = u.lastLogin
password = u.password
}
// MARK: - NSCoding
#objc public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
lastLogin = lastLogin <|? aDecoder.decodeObjectForKey(SerializationKeys.lastLogin)
password = password <|? aDecoder.decodeObjectForKey(SerializationKeys.password)
}
#objc public override func encodeWithCoder(aCoder: NSCoder) {
super.encodeWithCoder(aCoder)
aCoder.encodeObject(lastLogin, forKey: SerializationKeys.lastLogin)
aCoder.encodeObject(password, forKey: SerializationKeys.password)
}
}
Also the User object is a subclass of AbstractUser and isn't the cause of the problem. It will produce the same error however just putting print(keys) after "let keys = ..." will cause the error just the same. The issue seems to be when I try and access any property or method on any class within that submodule.

Xcode 6.0.1 segmentation fault at compile time with Swift project

I've a segmentation fault when I try to compile my Swift project.
Here is a simplified version of my code which causes the error:
enum PluginType
{
case PluginC
case PluginD
}
class Plugin
{
var pluginType : PluginType
var setter : Void -> Void
var unsetter : Void -> Void
init(pluginType : PluginType, setter : Void -> Void, unsetter : Void -> Void)
{
self.pluginType = pluginType
self.setter = setter
self.unsetter = unsetter
}
}
#objc protocol BProtocol
{
func getPlugins() -> [Plugin]
}
class B : BProtocol
{
var a : AProtocol?
func getPlugins() -> [Plugin]
{
return [Plugin(pluginType : .PluginC, setter : a!.setPluginC, unsetter : a!.unsetPluginC),
Plugin(pluginType : .PluginD, setter : a!.setPluginD, unsetter: a!.unsetPluginD)]
}
}
#objc protocol AProtocol
{
func setPluginC()
func unsetPluginC()
func setPluginD()
func unsetPluginD()
}
class A : AProtocol
{
var b : BProtocol?
func setPluginC()
{
}
func unsetPluginC()
{
}
func setPluginD()
{
}
func unsetPluginD()
{
}
}
The problems come from this method:
func getPlugins() -> [Plugin]
{
return [Plugin(pluginType : .PluginC, setter : a!.setPluginC, unsetter : a!.unsetPluginC),
Plugin(pluginType : .PluginD, setter : a!.setPluginD, unsetter: a!.unsetPluginD)]
}
The problem is caused by the setter and unsetter that I initialize.
Here's the error on Xcode:
0 swift 0x000000010456a028
llvm::sys::PrintStackTrace(__sFILE*) + 40 1 swift
0x000000010456a514 SignalHandler(int) + 452 2
libsystem_platform.dylib 0x00007fff9596f5aa _sigtramp + 26 3
libsystem_platform.dylib 0x000007f83527198b _sigtramp + 2677023739 4
swift 0x00000001049290df
swift::AbstractStorageDecl::hasObjCGetterAndSetter() const + 31 5
swift 0x0000000104929205
swift::AbstractStorageDecl::requiresObjCGetterAndSetter() const + 69 6
swift 0x00000001039ff3f4
swift::Lowering::SILGenFunction::emitGetAccessor(swift::SILLocation,
swift::AbstractStorageDecl*, llvm::ArrayRef,
swift::Lowering::RValueSource&&, bool, swift::Lowering::RValue&&,
swift::Lowering::SGFContext) + 68 7 swift
0x0000000103a15ca4
swift::Lowering::SILGenFunction::emitRValueForPropertyLoad(swift::SILLocation,
swift::Lowering::ManagedValue, bool, swift::VarDecl*,
llvm::ArrayRef, bool, swift::Type,
swift::Lowering::SGFContext) + 1284 8 swift
0x0000000103a2a012 swift::ASTVisitor<(anonymous
namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void,
void, void, swift::Lowering::SGFContext>::visit(swift::Expr*,
swift::Lowering::SGFContext) + 28402 9 swift
0x0000000103a2b6ed
swift::Lowering::SILGenFunction::emitRValueAsSingleValue(swift::Expr*,
swift::Lowering::SGFContext) + 45 10 swift
0x00000001039f3720
swift::Lowering::RValueSource::getAsSingleValue(swift::Lowering::SILGenFunction&,
swift::Lowering::SGFContext) && + 176 11 swift
0x0000000103a44154
swift::Lowering::RValueSource::forwardInto(swift::Lowering::SILGenFunction&,
swift::Lowering::AbstractionPattern, swift::Lowering::Initialization*,
swift::Lowering::TypeLowering const&) && + 260 12 swift
0x0000000103a4400e
swift::Lowering::RValueSource::materialize(swift::Lowering::SILGenFunction&,
swift::Lowering::AbstractionPattern, swift::SILType) && + 334 13 swift
0x0000000103a340fc
swift::Lowering::SILGenFunction::emitInjectOptionalValueInto(swift::SILLocation,
swift::Lowering::RValueSource&&, swift::SILValue,
swift::Lowering::TypeLowering const&) + 268 14 swift
0x0000000103a2b1fb swift::ASTVisitor<(anonymous
namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void,
void, void, swift::Lowering::SGFContext>::visit(swift::Expr*,
swift::Lowering::SGFContext) + 32987 15 swift
0x0000000103a2a325 swift::ASTVisitor<(anonymous
namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void,
void, void, swift::Lowering::SGFContext>::visit(swift::Expr*,
swift::Lowering::SGFContext) + 29189 16 swift
0x0000000103a2b63f
swift::Lowering::SILGenFunction::emitIgnoredExpr(swift::Expr*) + 191
17 swift 0x0000000103a483f9
swift::Lowering::SILGenFunction::visitBraceStmt(swift::BraceStmt*) +
297 18 swift 0x0000000103a4b2d4
swift::ASTVisitor::visit(swift::Stmt*) + 148 19 swift
0x0000000103a188c3
swift::Lowering::SILGenFunction::emitFunction(swift::FuncDecl*) + 243
20 swift 0x00000001039f8646
swift::Lowering::SILGenModule::emitFunction(swift::FuncDecl*) + 230 21
swift 0x0000000103a12763
swift::ASTVisitor::visit(swift::Decl*) + 355 22 swift
0x0000000103a1112b SILGenType::emitType() + 203 23 swift
0x0000000103a0c0fe
swift::Lowering::SILGenModule::visitNominalTypeDecl(swift::NominalTypeDecl*)
+ 30 24 swift 0x00000001039fa5cb swift::Lowering::SILGenModule::emitSourceFile(swift::SourceFile*,
unsigned int) + 411 25 swift 0x00000001039fa88f
swift::SILModule::constructSIL(swift::Module*, swift::SourceFile*,
swift::Optional) + 335 26 swift
0x00000001039fa9d8 swift::performSILGeneration(swift::SourceFile&,
swift::Optional) + 72 27 swift
0x00000001038dfda9 frontend_main(llvm::ArrayRef, char
const*, void*) + 3353 28 swift 0x00000001038dd94d
main + 1677 29 libdyld.dylib 0x00007fff99b5c5fd start + 1
30 libdyld.dylib 0x000000000000015a start + 1716140894
I'm looking for a workaround to avoid the "Segmentation Fault" with the compiler.
Any suggestions?
Thanks !
Finally, I found a workaround:
func getPlugins() -> [Plugin]
{
return [Plugin(pluginType : .PluginC, setter : { a!.setPluginC() }, unsetter : { a!.unsetPluginC() }),
Plugin(pluginType : .PluginD, setter : { a!.setPluginD() }, unsetter: { a!.unsetPluginD() })]
}
This successfully works with Xcode 6.1

Resources