parse object not found iOS 10 - swift

After updating to iOS 10 I would always get this object not found error whenever I try to update a PFObject on the parse heroku server. I have been researching and have tried out what many people have suggested turning on keychain sharing on capabilities. But, still no sign of working.
Some codes I'm using:
let publishQuery = PFQuery(className: "allPosts")
publishQuery.whereKey("objectId", equalTo: objectIdToPublish)
publishQuery.findObjectsInBackground { (objects, error) -> Void in
if let objects = objects {
for object in objects {
publishQuery.getObjectInBackground(withId: object.objectId!, block: { (objectToPublish, error) -> Void in
if error == nil {
let postAcl = PFACL(user: PFUser.current()!)
postAcl.getPublicReadAccess = true
postAcl.getPublicWriteAccess = true
objectToPublish!.acl = postAcl
objectToPublish!["isItPublished"] = true
objectToPublish?.saveInBackground(block: { (success, error) -> Void in
if error == nil {
self.publishedOrNot[((cellIndexPath as NSIndexPath?)?.row)!] = true
self.myTableView.reloadData()
} else {
self.displayAlert("Sth's wrong", message: "Please try again")
print(error)
}
})
}
})
}
}
}
This is the error I'm getting printed in the logs :
2016-10-22 19:10:39.740 Pufff[609:9898] [Error]: Object not found. (Code: 101, Version: 1.13.0)
Optional(Error Domain=Parse Code=101 "Object not found." UserInfo={code=101,
error=Object not found., temporary=0, NSLocalizedDescription=Object not found.})

Related

Why does Firestore think it retrieved a document when one doesn't exist?

I'm using swift(UI) with firebase and Google SignIn. So far sign in has been great but when I come to using a new user the code below fails - no fatal errors just doesn't add a new user document to Firestore because it seems to think it has retrieved a document which it couldn't because one with the specified ID don't exist.
My guess is the mistake is in the section:
if let error = error as NSError? {
print("Error getting document: \(error.localizedDescription)")
self.setFirestoreUser()
}
the full function:
func fetchUser(documentId: String) {
let docRef = Firestore.firestore().collection("users").document(documentId)
print("User id: \(documentId) ( via fetchUser )")
docRef.getDocument { document, error in
if let error = error as NSError? {
print("Error getting document: \(error.localizedDescription)")
self.setFirestoreUser()
}
else {
if let document = document {
do {
print("Working on coding to User.self")
self.appUser = try document.data(as: User.self)
self.fetchSites()
}
catch {
print("func - fetchUser() error: \(error)")
}
}
}
}
}
The argument 'documentId' is passed on from the google sign process
followup func to create the new Firestore document for this new user:
func setFirestoreUser() {
let googleUser = GIDSignIn.sharedInstance.currentUser
let db = Firestore.firestore()
self.appUser.emailAddress = googleUser?.profile?.email ?? "Unknown"
self.appUser.userGivenName = googleUser?.profile?.givenName ?? ""
self.appUser.userFirstName = googleUser?.profile?.name ?? ""
self.appUser.userProfileURL = googleUser?.profile!.imageURL(withDimension: 100)!.absoluteString ?? ""
do {
try db.collection("users").document(googleUser?.userID ?? "UnknownID").setData(from: self.appUser)
self.fetchUser(documentId: googleUser?.userID ?? "")
} catch {
print(error)
}
}
Calling getDocument on a reference to a non-existing document is not an error (as far as I know), and will return a DocumentSnapshot. To detect whether the document exists, check the exists property on the snapshot instead of (only) checking for errors.
if let document = document {
if !document.exists {
...

How to fetch object id from parse Ios

Code
let number=UserDefaults.standard.object(forKey: "phone")
let s=PFQuery(className: "Customer")
s.whereKey("phonenumber", equalTo:number!)
s.getFirstObjectInBackground(block: { (gameScore: PFObject?, error: Error?) in
if let error = error {
//The query returned an error
print(error.localizedDescription)
} else {
//The object has been retrieved
print(gameScore?.objectId)
}
})
I need to fetch object id in a row where it matches my phone number, How do I do that?
I made mistake while calling the query , query needs only Int but iam sending Any data type
let number=UserDefaults.standard.object(forKey: "phone") as? String
let Stringtonumber=Int(number!)
let s=PFQuery(className: "Customer")
s.whereKey("phonenumber", equalTo:Stringtonumber)
s.getFirstObjectInBackground(block: { (gameScore: PFObject?, error: Error?) in
if let error = error {
//The query returned an error
print(error.localizedDescription)
} else {
//The object has been retrieved
print(gameScore?.objectId)
}
})

How to use the when function in Promisekit loop

I have an array of appointments and I'm trying to grab all of the photos for these appointments from our windows azure blob storage. First, I want to get the list of blobs with the associated appointmentId so I can download and store them properly afterwards.
I'm using PromiseKit but I'm not at all sure about how to use PromiseKit in a loop:
for appointment in appointments {
// Get blobs
}
Here's my code so far. Any help is greatly appreciated!
func getBlobsPromise(appointmentId: Int32) -> Promise<[BlobDownload]> {
return Promise { seal in
var error: NSError?
var blobDownloads = [BlobDownload]()
container = AZSCloudBlobContainer(url: URL(string: containerURL)!, error: &error)
if ((error) != nil) {
print("Error in creating blob container object. Error code = %ld, error domain = %#, error userinfo = %#", error!.code, error!.domain, error!.userInfo)
seal.reject(error!)
}
let prefix: String = "AppointmentFiles/\(appointmentId)"
container?.listBlobsSegmented(with: nil, prefix: prefix, useFlatBlobListing: true, blobListingDetails: AZSBlobListingDetails(), maxResults: 150) { (error : Error?, results : AZSBlobResultSegment?) -> Void in
if error != nil {
seal.reject(error!)
}
for blob in results!.blobs!
{
let blobInfo = blob as! AZSCloudBlob
if blobInfo.blobName.lowercased().contains("jpg") || blobInfo.blobName.lowercased().contains("jpeg") {
let blobDownload: BlobDownload = BlobDownload(appointmentId: Int(jobId), blob: blobInfo)
blobDownloads.append(blobDownload)
}
}
seal.fulfill(blobDownloads)
}
}
}
That returns the blobs as expected but I want to get all of the blobs for all of the appointments before proceeding. Here's what I tried (among other things):
func getBlobsForAllJobs(appointmentIds: [Int32]) -> Promise<[BlobDownload]> {
return Promise { seal in
let count = appointmentIds.count - 1
let promises = (0..<count).map { index -> Promise<[BlobDownload]> in
return getBlobsPromise(agencyCode: agencyCode, appointmentId: appointmentIds[index])
}
when(fulfilled: promises).then({ blobDownloads in
seal.fulfill(blobDownloads)
})
}
}
EDIT 1
I solved this using a DispatchGroup and completion handler. Here's the code in case someone is interested. If there are alternate (better) ways of doing this I'd love to hear them. I'm a c# guy just getting into Swift.
func getBlobsToDownload(appointmentIds: [Int32], completion: #escaping ([BlobDownload]) -> Void) {
var myBlobsToDownload = [BlobDownload]()
let myGroup = DispatchGroup()
for apptId in appointmentIds {
myGroup.enter()
getBlobs(appointmentId: apptId) { (blobDownloads) in
print("Finished request \(apptId)")
print("Blobs fetched from apptId \(apptId) is \(blobDownloads.count)")
for blobDownload in blobDownloads {
myBlobsToDownload.append(blobDownload)
}
myGroup.leave()
}
}
myGroup.notify(queue: .main) {
print("Finished all requests.")
completion(myBlobsToDownload)
}
}

Why is my code not saving data to the Kinvey Backend?

I have a viewController that has three textfields (name, email & seats) and a Date picker. Below there is a button that is connected as an outlet to send a reservation to the backend where it should be registered. I tried several things already but for some reason the data is not saved. I am connected to the backend because i can see the Api calls and data storage in Bytes.... Could you please check my code?
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
self.sendReservation.addTarget(self, action: "sendBooking:", forControlEvents: .TouchUpInside)
let reservation = Booking()
reservation.name = userName.text
reservation.email = userEmail.text
reservation.seats = userSeat.text
reservation.date = NSDate(timeIntervalSince1970: 1352149171) //sample date
func sendBooking (sender: UIButton) {
KCSUser.loginWithUsername("admin", password: "leden1234",
withCompletionBlock: { (user: KCSUser!, errorOrNil: NSError!, result: KCSUserActionResult) -> Void in
if errorOrNil == nil {
let store = KCSAppdataStore.storeWithOptions([
KCSStoreKeyCollectionName : "userReservation",
KCSStoreKeyCollectionTemplateClass : Booking.self
])
store.saveObject(
reservation,
withCompletionBlock: { (objectsOrNil: [AnyObject]!, errorOrNil: NSError!) -> Void in
if errorOrNil != nil {
//save failed
NSLog("Save failed, with error: %#", errorOrNil.localizedFailureReason!)
} else {
//save was successful
NSLog("Successfully saved event (id='%#').", (objectsOrNil[0] as! NSObject).kinveyObjectId())
}
},
withProgressBlock: nil
) } else {
NSLog("User was not registered: %#", errorOrNil.localizedFailureReason!)
}
})
}
}
}
All Kinvey requests must be made using an authorized user, if a user doesn't exist, an automatic user generation facility exists.
Make sure you are an active user i.e. you have logged in before making any Kinvey calls. I have tried your code and it worked fine. Try following implementation :
KCSUser.loginWithUsername(
"kinvey",
password: "12345",
withCompletionBlock: { (user: KCSUser!, errorOrNil: NSError!, result: KCSUserActionResult) -> Void in
if errorOrNil == nil {
//the log-in was successful and the user is now the active user and credentials saved
// Put your code to save the object here
} else {
//there was an error with the update save
}
}
)
For more details,check http://devcenter.kinvey.com/ios/guides/users#.
If above information doesn't help, let me know what error you are getting in "errorOrNil.localizedFailureReason".
try to use this its work with me fine
KCSUser.userWithUsername(Username_user.text!, password: Password.text!, fieldsAndValues: [KCSUserAttributeEmail : Email.text!,
KCSUserAttributeGivenname : UserName.text! ,KCSUserAttributeSurname : SureName.text!],
withCompletionBlock: { (user: KCSUser!, errorOrNil: NSError!, result: KCSUserActionResult) -> Void in
if errorOrNil == nil {
}else{
}
})

Retrieving parse.com data in Swift

I've been able to save successfully to Parse via Swift, but am having trouble retrieving data (and all of the tutorials on retrieving seem to be for Obj-C).
Here's my code (with Id's redacted).
Parse.setApplicationId("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", clientKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
var query = PFQuery(className: "EventObject")
query.getObjectInBackgroundWithId(objectId: String!) {
(event: PFObject!, error: NSError!) -> Void in
if error == nil {
println(event)
} else {
println(error)
}
}
I have 4 records in this class right now, but if I want to pull the data for all of them, how do I get the Object using the ID if I'm not sure what the IDs are? I'm assuming I can access them sequentially as an array, but I'm not quite clear how to do that, and am confused, as the only command I know to retrieve appears to require knowing the ID.
Thanks for any help!
The official parse documentation explains how to make queries - there is sample code in swift.
In your case you have to use findObjectsInBackgroundWithBlock:
var query = PFQuery(className:"EventObject")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
// Do something
}
} else {
println(error)
}
}
which, if successful, provides to the closure an array of objects matching the query - since there's no filter set in the query, it just returns all records.
Swift 2.1 Update
func fetchFromParse() {
let query = PFQuery(className:"Your_Class_Name")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
for object in objects! {
// Do something
}
} else {
print(error)
}
}
}
Here is the code for fetch objects in Swift3.0.
let query = PFQuery(className: "Your_Class_Name")
query.findObjectsInBackground { (objects, error) in
if error == nil {
}
else {
}
}
Retrive Data from parse: swift 3
let adventureObject = PFQuery(className: "ClassName")
adventureObject.addAscendingOrder("objectId")
var objectID: String = String()
adventureObject.findObjectsInBackground(block: { (Success, error) in
})