Parse.com Swift getFirstObjectInBackground - ios

Can any one give an example of how use getFirstObjectInBackground and get the first Object returned into a PFObject in Swift?
let weatherObject:PFObject = query.getFirstObjectInBackground() as! PFObject
Gives a warning Cast from 'BFTask' to unrelated type 'PFObject' always fails is the warning / error I get in xcode.
TIA.

That variety of get returns a BFTask from the bolts framework, which is kind of like a JS promise for the iOS sdks. Your code casts the return from getFirstObjectInBackground to a PFObject, which it isn't, as if the method synchronously returns the object you're trying to fetch, which it doesn't.
The fix is either to treat the BFTask return value like a BFTask and assign it a completion block, or -- easier I think -- use the block variety of the get method (e.g. from the iOS guide):
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil {
println("The getFirstObject request failed.")
} else {
// The find succeeded.
println("Successfully retrieved the object.")
}
}
If your situation really calls for handling the bolts framework directly, a decent doc for it can be found on its github page.

Related

Accessing QBCOCustomObject retrieved from QBRequest inaccessible outside of QBRequest

I am trying to access whatever record was returned from my QBRequest and send it to a separate function (in this case, I'm trying to set whatever I got from the request, convert its contents to strings, and then display in cells). However, I am unable to do this by direct referencing outside of the QBRequest nor setting the object to outside variable.
var posts = [QBCOCustomObject]()
func queryForPost(city: String) -> [QBCOCustomObject] {
let requestParameters = NSMutableDictionary();
[requestParameters.setObject(city, forKey: "Location")];
QBRequest.objectsWithClassName("UserFeed", extendedRequest: requestParameters, successBlock: { (response: QBResponse, record, page) in
print(record![0].fields!.allValues[0])
print(record![1].fields!.allValues[0])
//the two above prints return the desired values
self.posts = record!
}, errorBlock: {(response: QBResponse) in
// Handle error here
NSLog("error QBRequest - objectsWithClassName")
})
print(self.posts.count, "POSTS.COUNT") //can't access posts or record - this returns 0, and THEN returns whatever print functions are inside the QBRequest.
print(self.posts, "POSTS")
return self.posts
}
"print(self.posts.count, "POSTS.COUNT")" returns 0, and THEN returns whatever print functions are inside the QBRequest. Seems as if the QBRequest is performing after going through the whole function. Very confused and not sure how to fix this...
Been struggling with this for a while now :( If anybody could provide some guidance I would very much appreciate it.
Thank you in advance!
Lance

NSInvalidArgumentException when trying to retrieve images

I am getting an error using a "properly working" code in another place:
[Error]: Caught "NSInvalidArgumentException" with reason "*** -[_NSPlaceholderData
initWithContentsOfFile:options:error:]: nil file argument"
I declared an array of arrays group:[[AnyObject]]
In my CellForRowAtIndexPath method in my UITableView I am starting the following query based on an array which is an element of group => group[indexPath.row].
I can get the necessary data without a problem, but when I try to use my getDataInBackgroundWithBlock() method, it throws the error above.
var memberPhotoImages:[UIImage] = [UIImage]()
let buttonImageQuery = PFUser.query()
buttonImageQuery?.whereKey("objectId", containedIn: group[indexPath.row])
buttonImageQuery?.findObjectsInBackgroundWithBlock({ (results, error) -> Void in
if error != nil {
print(error)
} else {
self.memberPhotosFiles.removeAll()
if let results = results {
for result in results {
let buttonPicture = result["firstImage"] as! PFFile
self.memberPhotosFiles.append(buttonPicture)
buttonPicture.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error != nil {
//...
} else {
if let data = imageData {
print("success!")
}}}}}}})
return cell
}
Any ideas how to solve this? tried a lot of typecasting so far, but it must be something else.
edit: It prints "Success!", but also the error msg.
I had to guess from the error, it looks like you're trying to access a file that doesn't exist on the device -[_NSPlaceholderData initWithContentsOfFile:options:error:]: nil file argument The issue could be that you're accessing something from a place where the simulator can get to it (possibly inside the iOS Simulator's files, which are in Application Support,) but the device cannot. Check your code for any hard-coded paths that might lead to a place on your computer rather than accessing the device's filesystem.
It show that your file argument is nil. Most of such cases are due to different file path between simulator and device. Check your code about loading file and compare the path between simulator and device.

Why does the "objects: [PFObject]?" parameter of Parse's findObjectsInBackgroundWithBlock function return nil?

This is for an existing class on Parse called "HellsKitchen" and I have tried others, but always receive nil on objects.
let query = PFQuery(className: "HellsKitchen")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
print("got em: \(objects)")
} else {
print("error: \(error!.userInfo)")
}
}
All of the other posts about this refer to the block closure when they had objects as [AnyObject]? but it has since changed sometime in late 2015 and I no longer need to cast it as PFObject as all the answers say.
I have tried adding App Transport Security Settings > Allow Arbitrary Loads = YES to my Info.plist to no avail.
I get no error from the block either. It passes into the if statement because error == nil and prints "got em: nil".
How can I get my objects?

PFQuery found a nonexistent object - Swift

I'm trying to query a nonexistent object like this code bellow, but always "Mike" is found. What could be wrong? Everything is working great (Save, Delete, Update and Query without error recognition).
var query = PFQuery(className:"Restaurant")
query.whereKey("clientname", equalTo:"Mike")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if (error == nil) {
print ("Found")
}
else {
print ("Not Found")
}
}
Try checking (debugging) what "objects" actually is. I think you will see that it is an empty array, meaning it did NOT find Mike.
An empty array of results is not a query error. The query succeeds, but finds no objects. So not getting an error does not mean "Found". It just means there was no error.

HKErrorDomain (HealthKit Error Domain) Constant in Xamarin

I am writing some error handling for when my HealthKit client requests permission to data in Xamarin iOS. I make the request like so:
public HKClient()
{
var HealthKitStore = new HKHealthStore();
HealthKitStore.RequestAuthorizationToShare (dataTypesToWrite, dataTypesToRead, OnHealthPermissionsCompleted);
}
void OnHealthPermissionsCompleted (bool success, NSError error)
{
//Parse error.Domain and error.Code herere
}
In my OnHealthPermissionsCompleted, I want to parse the NSError in order to debug why our request failed. The first thing to do is check error.Domain to make sure it is a HealthKit error and then compare error.Code to the constants in the HKErrorCode enum. The problem is, I cannot find any constant for what should be in error.Domain for HealthKit related errors. The Apple documentation says there should be a constant called "HKErrorDomain" for me to compare to, however it is not there in Xamarin.
https://developer.apple.com/library/prerelease/watchos/documentation/HealthKit/Reference/HealthKit_Constants/index.html#//apple_ref/doc/constant_group/Health_Kit_Error_Domain
https://developer.xamarin.com/api/namespace/HealthKit/
If I force an error and then check it in the debugger, I do see that error.Domain = "com.apple.healthkit". I could just compare to that string,
void OnHealthPermissionsCompleted (bool success, NSError error)
{
if(!success && error.Domain == "com.apple.healthkit")
{
//continue parsing...
}
}
but putting magic strings in these kinds of things makes me feel icky, especially when I know a constant for this exists in native iOS. Am I missing something here or is this my only option?
There is now a bug filed on Xamarin's Bugzilla to surface this constant:
https://bugzilla.xamarin.com/show_bug.cgi?id=34140

Resources