Products Customers Pricing Docs Help Blog
iOS Guide
Browse All Platforms More Platforms

Getting Started

If you haven't installed the SDK yet, please head over to the QuickStart guide to get our SDK up and running in Xcode. Note that we support iOS 6.0 and higher. You can also check out our iOS API Reference and OSX API Reference for more detailed information about our SDK.

The Parse platform provides a complete backend solution for your mobile application. Our goal is to totally eliminate the need for writing server code or maintaining servers.

On Parse, you create an App for each of your mobile applications. Each App has its own application id and client key that you apply to your SDK install. Your account on Parse can accommodate multiple Apps. This is useful even if you have one application, since you can deploy different versions for test and production.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Objects

The PFObject

Storing data on Parse is built around the ParseObject. Each ParseObject contains key-value pairs of JSON-compatible data. This data is schemaless, which means that you don't need to specify ahead of time what keys exist on each ParseObject. You simply set whatever key-value pairs you want, and our backend will store it.

For example, let's say you're tracking high scores for a game. A single PFObject could contain:

score: 1337, playerName: "Sean Plott", cheatMode: false

Keys must be alphanumeric strings. Values can be strings, numbers, booleans, or even arrays and dictionaries - anything that can be JSON-encoded.

Each ParseObject has a class name that you can use to distinguish different sorts of data. For example, we could call the high score object a GameScore. We recommend that you NameYourClassesLikeThis and nameYourKeysLikeThis, just to keep your code looking pretty.

Saving Objects

Let's say you want to save the GameScore described above to the Parse Cloud. The interface is similar to a NSMutableDictionary, plus the saveInBackground method:

PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"];
gameScore[@"score"] = @1337;
gameScore[@"playerName"] = @"Sean Plott";
gameScore[@"cheatMode"] = @NO;
[gameScore saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
  if (succeeded) {
    // The object has been saved.
  } else {
    // There was a problem, check error.description
  }
}];
var gameScore = PFObject(className:"GameScore")
gameScore["score"] = 1337
gameScore["playerName"] = "Sean Plott"
gameScore["cheatMode"] = false
gameScore.saveInBackgroundWithBlock {
  (success: Bool, error: NSError?) -> Void in
  if (success) {
    // The object has been saved.
  } else {
    // There was a problem, check error.description
  }
}

After this code runs, you will probably be wondering if anything really happened. To make sure the data was saved, you can look at the Data Browser in your app on Parse. You should see something like this:

objectId: "xWMyZ4YEGZ", score: 1337, playerName: "Sean Plott", cheatMode: false,
createdAt:"2011-06-10T18:33:42Z", updatedAt:"2011-06-10T18:33:42Z"

There are two things to note here. You didn't have to configure or set up a new Class called GameScore before running this code. Your Parse app lazily creates this Class for you when it first encounters it.

There are also a few fields you don't need to specify that are provided as a convenience. objectId is a unique identifier for each saved object. createdAt and updatedAt represent the time that each object was created and last modified in the Parse Cloud. Each of these fields is filled in by Parse, so they don't exist on a PFObject until a save operation has completed.

Note: You can use the saveInBackgroundWithBlock or saveInBackgroundWithTarget:selector: methods to provide additional logic which will run after the save completes.

Retrieving Objects

Saving data to the cloud is fun, but it's even more fun to get that data out again. If you have the objectId, you can retrieve the whole PFObject using a PFQuery. This is an asynchronous method, with variations for using either blocks or callback methods:

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query getObjectInBackgroundWithId:@"xWMyZ4YEGZ" block:^(PFObject *gameScore, NSError *error) {
    // Do something with the returned PFObject in the gameScore variable.
    NSLog(@"%@", gameScore);
}];
// The InBackground methods are asynchronous, so any code after this will run
// immediately.  Any code that depends on the query result should be moved
// inside the completion block above.
var query = PFQuery(className:"GameScore")
query.getObjectInBackgroundWithId("xWMyZEGZ") {
  (gameScore: PFObject?, error: NSError?) -> Void in
  if error == nil && gameScore != nil {
    println(gameScore)
  } else {
    println(error)
  }
}

To get the values out of the PFObject, you can use either the objectForKey: method or the [] subscripting operator:

int score = [[gameScore objectForKey:@"score"] intValue];
NSString *playerName = gameScore[@"playerName"];
BOOL cheatMode = [gameScore[@"cheatMode"] boolValue];
let score = gameScore["score"] as Int
let playerName = gameScore["playerName"] as String
let cheatMode = gameScore["cheatMode"] as Bool

The three special values are provided as properties:

NSString *objectId = gameScore.objectId;
NSDate *updatedAt = gameScore.updatedAt;
NSDate *createdAt = gameScore.createdAt;
let objectId = gameScore.objectId
let updatedAt = gameScore.updatedAt
let createdAt = gameScore.createdAt

If you need to refresh an object you already have with the latest data that is in the Parse Cloud, you can call the refresh method like so:

[myObject refresh];
myObject.refresh()

The Local Datastore

Parse also lets you store objects in a local datastore on the device itself. You can use this for data that doesn't need to be saved to the cloud, but this is especially useful for temporarily storing data so that it can be synced later. To enable the datastore, add libsqlite3.dylib and call [Parse enableLocalDatastore] in your AppDelegate application:didFinishLaunchWithOptions: before calling [Parse setApplicationId:clientKey:]. Once the local datastore is enabled, you can store an object by pinning it.

PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"];
gameScore[@"score"] = 1337;
gameScore[@"playerName"] = @"Sean Plott";
gameScore[@"cheatMode"] = @NO;
[gameScore pinInBackground];
let gameScore = PFObject(className:"GameScore")
gameScore["score"] = 1337
gameScore["playerName"] = "Sean Plott"
gameScore["cheatMode"] = false
gameScore.pinInBackground()

As with saving, this recursively stores every object and file that gameScore points to, if it has been fetched from the cloud. Whenever you save changes to the object, or fetch new changes from Parse, the copy in the datastore will be automatically updated, so you don't have to worry about it.

Retrieving Objects from the Local Datastore

Storing an object is only useful if you can get it back out. To get the data for a specific object, you can use a PFQuery just like you would while on the network, but using the fromLocalDatastore method to tell it where to get the data.

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query fromLocalDatastore];
[[query getObjectInBackgroundWithId:@"xWMyZ4YEGZ"] continueWithBlock:^id(BFTask *task) {
  if (task.error) {
    // something went wrong;
    return task;
  }

  // task.result will be your game score
  return task;
}];
let query = PFQuery(className:"GameScore")
query.fromLocalDatastore()
query.getObjectInBackgroundWithId("xWMyZ4YEGZ").continueWithBlock({
  (task: BFTask!) -> AnyObject! in
  if task.error != nil {
      // There was an error.
      return task
  }

  // task.result will be your game score
  return task
})

If you already have an instance of the object, you can instead use the fetchFromLocalDatastoreInBackground method.

PFObject *object = [PFObject objectWithoutDataWithClassName:@"GameScore" objectId:@"xWMyZ4YEGZ"];
[[object fetchFromLocalDatastoreInBackground] continueWithBlock:^id(BFTask *task) {
  if (task.error) {
    // something went wrong
    return task;
  }

  // task.result will be your game score
  return task;
}];
let object = PFObject(withoutDataWithClassName:"GameScore", objectId:"xWMyZ4YEGZ")
object.fetchFromLocalDatastoreInBackground().continueWithBlock({
  (task: BFTask!) -> AnyObject! in
  if task.error != nil {
      // There was an error.
      return task
  }

  // task.result will be your game score
  return task
})

Unpinning Objects

When you are done with the object and no longer need to keep it on the device, you can release it with unpinInBackground.

[gameScore unpinInBackground];
gameScore.unpinInBackground()

Saving Objects Offline

Most save functions execute immediately, and inform your app when the save is complete. If you don't need to know when the save has finished, you can use saveEventually instead. The advantage is that if the user currently doesn't have a network connection, saveEventually will store the update on the device until a network connection is re-established. If your app is closed before the connection is back, Parse will try again the next time the app is opened. All calls to saveEventually (and deleteEventually) are executed in the order they are called, so it is safe to call saveEventually on an object multiple times.

// Create the object.
PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"];
gameScore[@"score"] = @1337;
gameScore[@"playerName"] = @"Sean Plott";
gameScore[@"cheatMode"] = @NO;
[gameScore saveEventually];
var gameScore = PFObject(className:"GameScore")
gameScore["score"] = 1337
gameScore["playerName"] = "Sean Plott"
gameScore["cheatMode"] = false
gameScore.saveEventually()

Updating Objects

Updating an object is simple. Just set some new data on it and call one of the save methods. Assuming you have saved the object and have the objectId, you can retrieve the PFObject using a PFQuery and update its data:

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];

// Retrieve the object by id
[query getObjectInBackgroundWithId:@"xWMyZ4YEGZ"
                             block:^(PFObject *gameScore, NSError *error) {
    // Now let's update it with some new data. In this case, only cheatMode and score
    // will get sent to the cloud. playerName hasn't changed.
    gameScore[@"cheatMode"] = @YES;
    gameScore[@"score"] = @1338;
    [gameScore saveInBackground];
}];
var query = PFQuery(className:"GameScore")
query.getObjectInBackgroundWithId("xWMyZEGZ") {
  (gameScore: PFObject?, error: NSError?) -> Void in
  if error != nil {
    println(error)
  } else if let gameScore = gameScore {
    gameScore["cheatMode"] = true
    gameScore["score"] = 1338
    gameScore.saveInBackground()
  }
}

The client automatically figures out which data has changed so only "dirty" fields will be sent to Parse. You don't need to worry about squashing data that you didn't intend to update.

Counters

The above example contains a common use case. The "score" field is a counter that we'll need to continually update with the player's latest score. Using the above method works but it's cumbersome and can lead to problems if you have multiple clients trying to update the same counter.

To help with storing counter-type data, Parse provides methods that atomically increment (or decrement) any number field. So, the same update can be rewritten as:

[gameScore incrementKey:@"score"];
[gameScore saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
  if (succeeded) {
    // The score key has been incremented
  } else {
    // There was a problem, check error.description
  }
}];
gameScore.incrementKey("score")
gameScore.saveInBackgroundWithBlock {
  (success: Bool, error: NSError?) -> Void in
  if (success) {
    // The score key has been incremented
  } else {
    // There was a problem, check error.description
  }
}

You can also increment by any amount using incrementKey:byAmount:.

Arrays

To help with storing array data, there are three operations that can be used to atomically change an array field:

For example, we can add items to the set-like "skills" field like so:

[gameScore addUniqueObjectsFromArray:@[@"flying", @"kungfu"] forKey:@"skills"];
[gameScore saveInBackground];
gameScore.addUniqueObjectsFromArray(["flying", "kungfu"], forKey:"skills")
gameScore.saveInBackground()

Note that it is not currently possible to atomically add and remove items from an array in the same save. You will have to call save in between every different kind of array operation.

Deleting Objects

To delete an object from the cloud:

[gameScore deleteInBackground];
gameScore.deleteInBackground()

If you want to run a callback when the delete is confirmed, you can use the deleteInBackgroundWithBlock: or deleteInBackgroundWithTarget:selector: methods. If you want to block the calling thread, you can use the delete method.

You can delete a single field from an object with the removeObjectForKey method:

// After this, the playerName field will be empty
[gameScore removeObjectForKey:@"playerName"];

// Saves the field deletion to the Parse Cloud
[gameScore saveInBackground];
// After this, the playerName field will be empty
gameScore.removeObjectForKey("playerName")

// Saves the field deletion to the Parse Cloud
gameScore.saveInBackground()

Relational Data

Objects can have relationships with other objects. To model this behavior, any PFObject can be used as a value in other PFObjects. Internally, the Parse framework will store the referred-to object in just one place, to maintain consistency.

Watch the One-To-Many Relationships tutorial, where you'll learn how to create a one-to-many relationship between two PFObjects in a simple blogging application.

For example, each Comment in a blogging app might correspond to one Post. To create a new Post with a single Comment, you could write:

// Create the post
PFObject *myPost = [PFObject objectWithClassName:@"Post"];
myPost[@"title"] = @"I'm Hungry";
myPost[@"content"] = @"Where should we go for lunch?";

// Create the comment
PFObject *myComment = [PFObject objectWithClassName:@"Comment"];
myComment[@"content"] = @"Let's do Sushirrito.";

// Add a relation between the Post and Comment
myComment[@"parent"] = myPost;

// This will save both myPost and myComment
[myComment saveInBackground];
// Create the post
var myPost = PFObject(className:"Post")
myPost["title"] = "I'm Hungry"
myPost["content"] = "Where should we go for lunch?"

// Create the comment
var myComment = PFObject(className:"Comment")
myComment["content"] = "Let's do Sushirrito."

// Add a relation between the Post and Comment
myComment["parent"] = myPost

// This will save both myPost and myComment
myComment.saveInBackground()

You can also link objects using just their objectIds like so:

// Add a relation between the Post with objectId "1zEcyElZ80" and the comment
myComment[@"parent"] = [PFObject objectWithoutDataWithClassName:@"Post" objectId:@"1zEcyElZ80"];
// Add a relation between the Post with objectId "1zEcyElZ80" and the comment
myComment["parent"] = PFObject(withoutDataWithClassName:"Post", objectId:"1zEcyElZ80")

By default, when fetching an object, related PFObjects are not fetched. These objects' values cannot be retrieved until they have been fetched like so:

PFObject *post = fetchedComment[@"parent"];
[post fetchIfNeededInBackgroundWithBlock:^(PFObject *post, NSError *error) {
  NSString *title = post[@"title"];
  // do something with your title variable
}];
var post = myComment["parent"] as PFObject
post.fetchIfNeededInBackgroundWithBlock {
  (post: PFObject?, error: NSError?) -> Void in
  let title = post?["title"] as? NSString
  // do something with your title variable
}

You can also model a many-to-many relation using the PFRelation object. This works similar to an NSArray of PFObjects, except that you don't need to download all the Objects in a relation at once. This allows PFRelation to scale to many more objects than the NSArray of PFObject approach. For example, a User may have many Posts that they might like. In this case, you can store the set of Posts that a User likes using relationForKey:. In order to add a post to the list, the code would look something like:

PFUser *user = [PFUser currentUser];
PFRelation *relation = [user relationForKey:@"likes"];
[relation addObject:post];
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
  if (succeeded) {
    // The post has been added to the user's likes relation.
  } else {
    // There was a problem, check error.description
  }
}];
var user = PFUser.currentUser()
var relation = user.relationForKey("likes")
relation.addObject(post)
user.saveInBackgroundWithBlock {
  (success: Bool, error: NSError?) -> Void in
  if (success) {
    // The post has been added to the user's likes relation.
  } else {
    // There was a problem, check error.description
  }
}

You can remove a post from the PFRelation with something like:

[relation removeObject:post];
relation.removeObject(post)

By default, the list of objects in this relation are not downloaded. You can get the list of Posts by using calling findObjectsInBackgroundWithBlock: on the PFQuery returned by query. The code would look like:

[[relation query] findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (error) {
     // There was an error
  } else {
    // objects has all the Posts the current user liked.
  }
}];
relation.query().findObjectsInBackgroundWithBlock {
  (objects: [AnyObject]?, error: NSError?) -> Void in
  if let error = error {
    // There was an error
  } else {
    // objects has all the Posts the current user liked.
  }
}

If you want only a subset of the Posts you can add extra constraints to the PFQuery returned by query like this:

PFQuery *query = [relation query];
// Add other query constraints.
var query = relation.query()
// Add other query constraints.

For more details on PFQuery please look at the query portion of this guide. A PFRelation behaves similar to an NSArray of PFObject, so any queries you can do on arrays of objects (other than includeKey:) you can do on PFRelation.

Data Types

So far we've used values with type NSString, NSNumber, and PFObject. Parse also supports NSDate, NSData, and NSNull.

You can nest NSDictionary and NSArray objects to store more structured data within a single PFObject.

Some examples:

NSNumber *number = @42;
NSString *string = [NSString stringWithFormat:@"the number is %@", number];
NSDate *date = [NSDate date];
NSData *data = [@"foo" dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = @[string, number];
NSDictionary *dictionary = @{@"number": number,      @"string": string};
NSNull *null = [NSNull null];
PFObject *pointer = [PFObject objectWithoutDataWithClassName:@"MyClassName" objectId:@"xyz"];

PFObject *bigObject = [PFObject objectWithClassName:@"BigObject"];
bigObject[@"myNumberKey"] = number;
bigObject[@"myStringKey"] = string;
bigObject[@"myDateKey"] = date;
bigObject[@"myBytesKey"] = data; // shows up as 'bytes' in the Data Browser
bigObject[@"myArrayKey"] = array;
bigObject[@"myObjectKey"] = dictionary; // shows up as 'object' in the Data Browser
bigObject[@"myNullKey"] = null;
bigObject[@"myPointerKey"] = pointer; // shows up as Pointer <MyClassName> in the Data Browser
[bigObject saveInBackground];
let number = 42
let string = "the number is \(number)"
let date = NSDate()
let data = "foo".dataUsingEncoding(NSUTF8StringEncoding)
let array = [string, number]
let dictionary = ["number": number, "string": string]
let null = NSNull()
let pointer = PFObject(objectWithoutDataWithClassName:"MyClassName", objectId: "xyz")

var bigObject = PFObject(className:"BigObject")
bigObject["myNumberKey"] = number
bigObject["myStringKey"] = string
bigObject["myDateKey"] = date
bigObject["myBytesKey"] = data // shows up as 'bytes' in the Data Browser
bigObject["myArrayKey"] = array
bigObject["myObjectKey"] = dictionary // shows up as 'object' in the Data Browser
bigObject["myNullKey"] = null
bigObject["myPointerKey"] = pointer // shows up as Pointer <MyClassName> in the Data Browser
bigObject.saveInBackground()

We do not recommend storing large pieces of binary data like images or documents using NSData fields on PFObject. PFObjects should not exceed 128 kilobytes in size. To store more, we recommend you use PFFile. See Files for more details.

For more information about how Parse handles data, check out our Data documentation.

Subclasses

Parse is designed to get you up and running as quickly as possible. You can access all of your data using the PFObject class and access any field with objectForKey: or the [] subscripting operator. In mature codebases, subclasses have many advantages, including terseness, extensibility, and support for autocomplete. Subclassing is completely optional, but can transform this code:

PFObject *shield = [PFObject objectWithClassName:@"Armor"];
shield[@"displayName"] = @"Wooden Shield";
shield[@"fireProof"] = @NO;
shield[@"rupees"] = @50;
var shield = PFObject(className:"Armor")
shield["displayName"] = "Wooden Shield"
shield["fireProof"] = false
shield["rupees"] = 50

Into this:

Armor *shield = [Armor object];
shield.displayName = @"Wooden Shield";
shield.fireProof = NO;
shield.rupees = 50;
var shield = Armor()
shield.displayName = "Wooden Shield"
shield.fireProof = false
shield.rupees = 50

Subclassing PFObject

To create a PFObject subclass:

  1. Declare a subclass which conforms to the PFSubclassing protocol.
  2. Implement the class method parseClassName. This is the string you would pass to initWithClassName: and makes all future class name references unnecessary.
  3. Import PFObject+Subclass in your .m file. This implements all methods in PFSubclassing beyond parseClassName.
  4. Call [YourClass registerSubclass] before Parse setApplicationId:clientKey:.

An easy way to do this is with your class' +load (Obj-C only) or with initialize (both Obj-C and Swift) methods.

Please note that the initialize method is not called until the class receives its first message, meaning that you need to call any instance or class method on your subclass before it will be registered with Parse SDK.

The following code sucessfully declares, implements, and registers the Armor subclass of PFObject:

// Armor.h
@interface Armor : PFObject<PFSubclassing>
+ (NSString *)parseClassName;
@end

// Armor.m
// Import this header to let Armor know that PFObject privately provides most
// of the methods for PFSubclassing.
#import <Parse/PFObject+Subclass.h>

@implementation Armor
+ (void)load {
  [self registerSubclass];
}

+ (NSString *)parseClassName {
  return @"Armor";
}
@end
// Import this header into your Swift bridge header file to
// let Armor know that PFObject privately provides most of
// the methods for PFSubclassing.
#import <Parse/PFObject+Subclass.h>

// Armor.swift

class Armor : PFObject, PFSubclassing {
  override class func initialize() {
    struct Static {
      static var onceToken : dispatch_once_t = 0;
    }
    dispatch_once(&Static.onceToken) {
      self.registerSubclass()
    }
  }

  static func parseClassName() -> String {
    return "Armor"
  }
}

Properties & Methods

Adding custom properties and methods to your PFObject subclass helps encapsulate logic about the class. With PFSubclassing, you can keep all your logic about a subject in one place rather than using separate classes for business logic and storage/transmission logic.

PFObject supports dynamic synthesizers just like NSManagedObject. Declare a property as you normally would, but use @dynamic rather than @synthesize in your .m file. The following example creates a displayName property in the Armor class:

// Armor.h
@interface Armor : PFObject<PFSubclassing>

@property (nonatomic, strong) NSString *displayName;

@end


// Armor.m
@implementation Armor

@dynamic displayName;

@end
// Armor.swift

class Armor : PFObject, PFSubclassing {

  @NSManaged var displayName: String

}

You can access the displayName property using armor.displayName or [armor displayName] and assign to it using armor.displayName = @"Wooden Shield" or [armor setDisplayName:@"Wooden Sword"]. Dynamic properties allow Xcode to provide autocomplete and catch typos.

NSNumber properties can be implemented either as NSNumbers or as their primitive counterparts. Consider the following example:

@property BOOL fireProof;
@property int rupees;
@NSManaged var fireProof: Boolean
@NSManaged var rupees: Int

In this case, game[@"fireProof"] will return an NSNumber which is accessed using boolValue and game[@"rupees"] will return an NSNumber which is accessed using intValue, but the fireProof property is an actual BOOL and the rupees property is an actual int. The dynamic getter will automatically extract the BOOL or int value and the dynamic setter will automatically wrap the value in an NSNumber. You are free to use either format. Primitive property types are easier to use but NSNumber property types support nil values more clearly.

If you need more complicated logic than simple property access, you can declare your own methods as well:

@dynamic iconFile;

- (UIImageView *)iconView {
  PFImageView *view = [[PFImageView alloc] initWithImage:kPlaceholderImage];
  view.file = self.iconFile;
  [view loadInBackground];
  return [view autorelease];
}
@NSManaged var iconFile: PFFile

func iconView() -> UIImageView {
  let view = PFImageView(imageView: PlaceholderImage)
  view.file = iconFile
  view.loadInBackground()
  return view
}

Initializing Subclasses

You should create new objects with the object class method. This constructs an autoreleased instance of your type and correctly handles further subclassing. To create a reference to an existing object, use objectWithoutDataWithObjectId:.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Queries

We've already seen how a PFQuery with getObjectInBackgroundWithId:block: can retrieve a single PFObject from Parse. There are many other ways to retrieve data with PFQuery - you can retrieve many objects at once, put conditions on the objects you wish to retrieve, cache queries automatically to avoid writing that code yourself, and more.

Basic Queries

In many cases, getObjectInBackgroundWithId:block: isn't powerful enough to specify which objects you want to retrieve. The PFQuery offers different ways to retrieve a list of objects rather than just a single object.

The general pattern is to create a PFQuery, put conditions on it, and then retrieve a NSArray of matching PFObjects using either findObjectsInBackgroundWithBlock: or findObjectsInBackgroundWithTarget:selector:. For example, to retrieve scores with a particular playerName, use the whereKey:equalTo: method to constrain the value for a key.

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query whereKey:@"playerName" equalTo:@"Dan Stemkoski"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    // The find succeeded.
    NSLog(@"Successfully retrieved %d scores.", objects.count);
    // Do something with the found objects
    for (PFObject *object in objects) {
        NSLog(@"%@", object.objectId);
    }
  } else {
    // Log details of the failure
    NSLog(@"Error: %@ %@", error, [error userInfo]);
  }
}];
var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
  (objects: [AnyObject]?, error: NSError?) -> Void in

  if error == nil {
    // The find succeeded.
    println("Successfully retrieved \(objects!.count) scores.")
    // Do something with the found objects
    if let objects = objects as? [PFObject] {
      for object in objects {
        println(object.objectId)
      }
    }
  } else {
    // Log details of the failure
    println("Error: \(error!) \(error!.userInfo!)")
  }
}

Both findObjectsInBackgroundWithBlock: and findObjectsInBackgroundWithTarget:selector: work similarly in that they assure the network request is done without blocking, and run the block/callback in the main thread. There is a corresponding findObjects method that blocks the calling thread, if you are already in a background thread:

// Only use this code if you are already running it in a background
// thread, or for testing purposes!

// Using PFQuery
PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query whereKey:@"playerName" equalTo:@"Dan Stemkoski"];
NSArray* scoreArray = [query findObjects];

// Using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"playerName = 'Dan Stemkosk'"];
PFQuery *query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate];
NSArray* scoreArray = [query findObjects];
// Using PFQuery
let query = PFQuery(className: "GameScore")
query.whereKey("playerName", equalTo: "Dan Stemkoski")
let scoreArray = query.findObjects()

// Using NSPredicate
let predicate = NSPredicate(format:"playerName = 'Dan Stemkosk'")
let query = PFQuery(className: "GameScore", predicate: predicate)
let scoreArray = query.findObjects()

Specifying Constraints with NSPredicate

To get the most out of PFQuery we recommend using its methods listed below to add constraints. However, if you prefer using NSPredicate, a subset of the constraints can be specified by providing an NSPredicate when creating your PFQuery.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"playerName = 'Dan Stemkosk'"];
PFQuery *query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate];
let predicate = NSPredicate(format: "playerName = 'Dan Stemkosk'")
var query = PFQuery(className: "GameScore", predicate: predicate)

These features are supported:

The following types of predicates are not supported:

Query Constraints

There are several ways to put constraints on the objects found by a PFQuery. You can filter out objects with a particular key-value pair with whereKey:notEqualTo:

// Using PFQuery
[query whereKey:@"playerName" notEqualTo:@"Michael Yabuti"];

// Using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:   @"playerName != 'Michael Yabuti'"];
PFQuery *query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate];
// Using PFQuery
query.whereKey("playerName", notEqualTo: "Michael Yabuti")

// Using NSPredicate
let predicate = NSPredicate(format:"playerName != 'Michael Yabuti'")
let query = PFQuery(className: "GameScore", predicate: predicate)

You can give multiple constraints, and objects will only be in the results if they match all of the constraints. In other words, it's like an AND of constraints.

// Using PFQuery
[query whereKey:@"playerName" notEqualTo:@"Michael Yabuti"];
[query whereKey:@"playerAge" greaterThan:@18];

// Using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:   @"playerName != 'Michael Yabuti' AND playerAge > 18"];
PFQuery *query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate];
// Using PFQuery
query.whereKey("playerName", notEqualTo: "Michael Yabuti")
query.whereKey("playerAge", greaterThan: 18)

// Using NSPredicate
let predicate = NSPredicate(format:"playerName != 'Michael Yabuti' AND playerAge > 18")
let query = PFQuery(className: "GameScore", predicate: predicate)

You can limit the number of results by setting limit. By default, results are limited to 100, but anything from 1 to 1000 is a valid limit:

query.limit = 10; // limit to at most 10 results
query.limit = 10 // limit to at most 10 results

If you want exactly one result, a more convenient alternative may be to use getFirstObject or getFirstObjectInBackground instead of using findObject.

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query whereKey:@"playerEmail" equalTo:@"dstemkoski@example.com"];
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
  if (!object) {
    NSLog(@"The getFirstObject request failed.");
  } else {
    // The find succeeded.
    NSLog(@"Successfully retrieved the object.");
  }
}];
var query = PFQuery(className: "GameScore")
query.whereKey("playerEmail", equalTo: "dstemkoski@example.com")
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.")
  }
}

You can skip the first results by setting skip. This can be useful for pagination:

query.skip = 10; // skip the first 10 results
query.skip = 10

For sortable types like numbers and strings, you can control the order in which results are returned:

// Sorts the results in ascending order by the score field
[query orderByAscending:@"score"];

// Sorts the results in descending order by the score field
[query orderByDescending:@"score"];
// Sorts the results in ascending order by the score field
query.orderByAscending("score")

// Sorts the results in descending order by the score field
query.orderByDescending("score")

You can add more sort keys to the query as follows:

// Sorts the results in ascending order by the score field if the previous sort keys are equal.
[query addAscendingOrder:@"score"];

// Sorts the results in descending order by the score field if the previous sort keys are equal.
[query addDescendingOrder:@"score"];
// Sorts the results in ascending order by the score field if the previous sort keys are equal.
query.addAscendingOrder("score")

// Sorts the results in descending order by the score field if the previous sort keys are equal.
query.addDescendingOrder("score")

For sortable types, you can also use comparisons in queries:

// Restricts to wins < 50
[query whereKey:@"wins" lessThan:@50];
// Or with NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"wins < 50"];
PFQuery *query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate];

// Restricts to wins <= 50
[query whereKey:@"wins" lessThanOrEqualTo:@50];
// Or with NSPredicate
predicate = [NSPredicate predicateWithFormat:@"wins <= 50"];
query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate]

// Restricts to wins > 50
[query whereKey:@"wins" greaterThan:@50];
// Or with NSPredicate
predicate = [NSPredicate predicateWithFormat:@"wins > 50"];
query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate];

// Restricts to wins >= 50
[query whereKey:@"wins" greaterThanOrEqualTo:@50];
// Or with NSPredicate
predicate = [NSPredicate predicateWithFormat:@"wins >= 50"];
query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate];
// Restricts to wins < 50
query.whereKey("wins", lessThan: 50)
// Or with NSPredicate
let predicate = NSPredicate(format: "wins < 50")
let query = PFQuery(className: "GameScore", predicate: predicate)

// Restricts to wins <= 50
query.whereKey("wins", lessThanOrEqualTo: 50)
// Or with NSPredicate
let predicate = NSPredicate(format: "wins <= 50")
let query = PFQuery(className: "GameScore", predicate: predicate)

// Restricts to wins > 50
query.whereKey("wins", greaterThan: 50)
// Or with NSPredicate
let predicate = NSPredicate(format: "wins > 50")
let query = PFQuery(className: "GameScore", predicate: predicate)

// Restricts to wins >= 50
query.whereKey("wins", greaterThanOrEqualTo: 50)
// Or with NSPredicate
let predicate = NSPredicate(format: "wins >= 50")
let query = PFQuery(className: "GameScore", predicate: predicate)

If you want to retrieve objects matching several different values, you can use whereKey:containedIn:, providing an array of acceptable values. This is often useful to replace multiple queries with a single query. For example, if you want to retrieve scores made by any player in a particular list:

// Finds scores from any of Jonathan, Dario, or Shawn
// Using PFQuery
NSArray *names = @[@"Jonathan Walsh", @"Dario Wunsch", @"Shawn Simon"];
[query whereKey:@"playerName" containedIn:names];

// Using NSPredicate
NSArray *names = @[@"Jonathan Walsh", @"Dario Wunsch", @"Shawn Simon"];
NSPredicate *pred = [NSPredicate predicateWithFormat: @"playerName IN %@", names];
PFQuery *query = [PFQuery queryWithClassName:@"GameScore" predicate:pred];
// Finds scores from any of Jonathan, Dario, or Shawn
// Using PFQuery
let names = ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]
query.whereKey("playerName", containedIn: names)

// Using NSPredicate
let names = ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]
let pred = NSPredicate(format: "playerName IN %@", names)
let query = PFQuery(className: "GameScore", predicate: predicate)

If you want to retrieve objects that do not match any of several values you can use whereKey:notContainedIn:, providing an array of acceptable values. For example, if you want to retrieve scores from players besides those in a list:

// Finds scores from anyone who is neither Jonathan, Dario, nor Shawn
// Using PFQuery
NSArray *names = @[@"Jonathan Walsh", @"Dario Wunsch", @"Shawn Simon"];
[query whereKey:@"playerName" notContainedIn:names];

// Using NSPredicate
NSArray *names = @[@"Jonathan Walsh", @"Dario Wunsch", @"Shawn Simon"];
NSPredicate *pred = [NSPredicate predicateWithFormat: @"NOT (playerName IN %@)", names];
PFQuery *query = [PFQuery queryWithClassName:@"GameScore" predicate:pred];
// Finds scores from anyone who is neither Jonathan, Dario, nor Shawn
// Using PFQuery
let names = ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]
query.whereKey("playerName", notContainedIn: names)

// Using NSPredicate
let names = ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]
let pred = NSPredicate(format: "NOT (playerName IN %@)", names)
let query = PFQuery(className: "GameScore", predicate: predicate)

If you want to retrieve objects that have a particular key set, you can use whereKeyExists. Conversely, if you want to retrieve objects without a particular key set, you can use whereKeyDoesNotExist.

// Finds objects that have the score set
[query whereKeyExists:@"score"];
// Or using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"score IN SELF"];
PFQuery *query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate];

// Finds objects that don't have the score set
[query whereKeyDoesNotExist:@"score"];
// Or using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (score IN SELF)"];
PFQuery *query = [PFQuery queryWithClassName:@"GameScore" predicate:predicate];
// Finds objects that have the score set
query.whereKeyExists("score")
// Or using NSPredicate
let predicate = NSPredicate(format: "score IN SELF")
let query = PFQuery(className: "GameScore", predicate: predicate)

// Finds objects that don't have the score set
query.whereKeyDoesNotExist("score")
// Or using NSPredicate
let predicate = NSPredicate(format: "NOT (score IN SELF)")
let query = PFQuery(className: "GameScore", predicate: predicate)

You can use the whereKey:matchesKey:inQuery: method to get objects where a key matches the value of a key in a set of objects resulting from another query. For example, if you have a class containing sports teams and you store a user's hometown in the user class, you can issue one query to find the list of users whose hometown teams have winning records. The query would look like:

PFQuery *teamQuery = [PFQuery queryWithClassName:@"Team"];
[teamQuery whereKey:@"winPct" greaterThan:@(0.5)];
PFQuery *userQuery = [PFQuery queryForUser];
[userQuery whereKey:@"hometown" matchesKey:@"city" inQuery:teamQuery];
[userQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
    // results will contain users with a hometown team with a winning record
}];
var teamQuery = PFQuery(className:"Team")
teamQuery.whereKey("winPct", greaterThan:0.5)
var userQuery = PFUser.query()
userQuery!.whereKey("hometown", matchesKey:"city", inQuery:teamQuery)
userQuery!.findObjectsInBackgroundWithBlock {
  (results: [AnyObject]?, error: NSError?) -> Void in
  if error == nil {
    // results will contain users with a hometown team with a winning record
  }
}

Conversely, to get objects where a key does not match the value of a key in a set of objects resulting from another query, use whereKey:doesNotMatchKey:inQuery:. For example, to find users whose hometown teams have losing records:

PFQuery *losingUserQuery = [PFQuery queryForUser];
[losingUserQuery whereKey:@"hometown" doesNotMatchKey:@"city" inQuery:teamQuery];
[losingUserQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
    // results will contain users with a hometown team with a losing record
}];
var losingUserQuery = PFUser.query()
losingUserQuery!.whereKey("hometown", doesNotMatchKey:"city", inQuery:teamQuery)
losingUserQuery!.findObjectsInBackgroundWithBlock {
  (results: [AnyObject]?, error: NSError?) -> Void in
  // results will contain users with a hometown team with a losing records
}

You can restrict the fields returned by calling selectKeys: with an NSArray of keys. To retrieve documents that contain only the score and playerName fields (and also special built-in fields such as objectId, createdAt, and updatedAt):

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query selectKeys:@[@"playerName", @"score"]];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
    // objects in results will only contain the playerName and score fields
}];
var query = PFQuery(className:"GameScore")
query.selectKeys(["playerName", "score"])
query.findObjectsInBackgroundWithBlock {
  (objects: [AnyObject]?, error: NSError?) -> Void in
  if error == nil {
    // objects in results will only contain the playerName and score fields
  }
}

The remaining fields can be fetched later by calling one of the fetchIfNeeded variants on the returned objects:

PFObject *object = (PFObject*)results[0];
[object fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
  // all fields of the object will now be available here.
}];
var object = results[0] as PFObject!
object.fetchIfNeededInBackgroundWithBlock {
  (object: PFObject?, error: NSError?) -> Void in
  // all fields of the object will now be available here.
}

Queries on Array Values

For keys with an array type, you can find objects where the key's array value contains 2 by:

// Find objects where the array in arrayKey contains 2.
// Using PFQuery
[query whereKey:@"arrayKey" equalTo:@2];

// Or using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"2 IN arrayKey"];
PFQuery *query = [PFQuery queryWithClassName:@"MyClass" predicate:predicate];
// Find objects where the array in arrayKey contains 2.
// Using PFQuery
query.whereKey("arrayKey", equalTo: 2)

// Or using NSPredicate
let predicate = NSPredicate(format: "2 IN arrayKey")
let query = PFQuery(className: "MyClass", predicate: predicate)

You can also find objects where the key's array value contains each of the values 2, 3, and 4 with the following:

// Find objects where the array in arrayKey contains each of the
// elements 2, 3, and 4.
[query whereKey:@"arrayKey" containsAllObjectsInArray:@[@2, @3, @4]];
// Find objects where the array in arrayKey contains each of the
// elements 2, 3, and 4.
query.whereKey("arrayKey", containsAllObjectsInArray:[2, 3, 4])

Queries on String Values

If you're trying to implement a generic search feature, we recommend taking a look at this blog post: Implementing Scalable Search on a NoSQL Backend.

Use whereKey:hasPrefix: to restrict to string values that start with a particular string. Similar to a MySQL LIKE operator, this is indexed so it is efficient for large datasets:

// Finds barbecue sauces that start with "Big Daddy".
// Using PFQuery
PFQuery *query = [PFQuery queryWithClassName:@"BarbecueSauce"];
[query whereKey:@"name" hasPrefix:@"Big Daddy's"];

// Using NSPredicate
NSPredicate *pred = [NSPredicate predicateWithFormat:@"name BEGINSWITH 'Big Daddy"];
PFQuery *query = [PFQuery queryWithClassName:@"BarbecueSauce" predicate:pred];
// Finds barbecue sauces that start with "Big Daddy".
// Using PFQuery
let query = PFQuery("BarbecueSauce")
query.whereKey("name", hasPrefix: "Big Daddy's")

// Using NSPredicate
let pred = NSPredicate(format: "name BEGINSWITH 'Big Daddy")
let query = PFQuery(className: "BarbecueSauce", predicate: predicate)

The above example will match any BarbecueSauce objects where the value in the "name" String key starts with "Big Daddy's". For example, both "Big Daddy's" and "Big Daddy's BBQ" will match, but "big daddy's" or "BBQ Sauce: Big Daddy's" will not.

Queries that have regular expression constraints are very expensive. Refer to the Performance Guide for more details.

Relational Queries

There are several ways to issue queries for relational data. If you want to retrieve objects where a field matches a particular PFObject, you can use whereKey:equalTo: just like for other data types. For example, if each Comment has a Post object in its post field, you can fetch comments for a particular Post:

// Assume PFObject *myPost was previously created.
// Using PFQuery
PFQuery *query = [PFQuery queryWithClassName:@"Comment"];
[query whereKey:@"post" equalTo:myPost];

[query findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
    // comments now contains the comments for myPost
}];

// Using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"post = %@", myPost];
PFQuery *query = [PFQuery queryWithClassName:@"Comment" predicate:predicate];

[query findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
    // comments now contains the comments for myPost
}];
// Assume PFObject *myPost was previously created.
// Using PFQuery
let query = PFQuery(className: "Comment")
query.whereKey("post", equalTo: myPost)
query.findObjectsInBackgroundWithBlock {
    (comments: [AnyObject]?, error: NSError?) -> Void in
    // comments now contains the comments for myPost
}

// Using NSPredicate
let predicate = NSPredicate(format: "post = %@", myPost)
let query = PFQuery(className: "Comment", predicate: predicate)

query.findObjectsInBackgroundWithBlock {
    (comments: [AnyObject]?, error: NSError?) -> Void in
    // comments now contains the comments for myPost
}

You can also do relational queries by objectId:

// Using PFQuery
[query whereKey:@"post" equalTo:[PFObject objectWithoutDataWithClassName:@"Post" objectId:@"1zEcyElZ80"]];

// Using NSPredicate
[NSPredicate predicateWithFormat:@"post = %@",
    [PFObject objectWithoutDataWithClassName:@"Post" objectId:@"1zEcyElZ80"]];
// Using PFQuery
query.whereKey("post", equalTo: PFObject(withoutDataWithClassName: "Post", objectId: "1zEcyElZ80"))

// Using NSPredicate
NSPredicate(format: "post = %@", PFObject(withoutDataWithClassName: "Post", objectId: "1zEcyElZ80"))

If you want to retrieve objects where a field contains a PFObject that match a different query, you can use whereKey:matchesQuery. Note that the default limit of 100 and maximum limit of 1000 apply to the inner query as well, so with large data sets you may need to construct queries carefully to get the desired behavior. In order to find comments for posts with images, you can do:

// Using PFQuery
PFQuery *innerQuery = [PFQuery queryWithClassName:@"Post"];
[innerQuery whereKeyExists:@"image"];
PFQuery *query = [PFQuery queryWithClassName:@"Comment"];
[query whereKey:@"post" matchesQuery:innerQuery];
[query findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
    // comments now contains the comments for posts with images
}];

// Using NSPredicate
NSPredicate *innerPred = [NSPredicate predicateWithFormat:@"image IN SELF"];
PFQuery *innerQuery = [PFQuery queryWithClassName:@"Post" predicate:innerPred];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"post IN %@", innerQuery];
PFQuery *query = [PFQuery queryWithClassName:@"Comment" predicate:pred];

[query findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
    // comments now contains the comments for posts with images
}];
// Using PFQuery
let innerQuery = PFQuery(className: "Post")
innerQuery.whereKeyExists("image")
let query = PFQuery(className: "Comment")
query.whereKey("post", matchesQuery: innerQuery)
query.findObjectsInBackgroundWithBlock {
    (comments: [AnyObject]?, error: NSError?) -> Void in
    // comments now contains the comments for posts with images
}

// Using NSPredicate
let innerPred = NSPredicate(format: "image IN SELF")
let innerQuery = PFQuery(className: "Post", predicate: innerPred)

let pred = NSPredicate(format: "post IN %@", innerQuery)
let query = PFQuery(className: "Comment", predicate: pred)

query.findObjectsInBackgroundWithBlock {
    (comments: [AnyObject]?, error: NSError?) -> Void in
    // comments now contains the comments for posts with images
}

If you want to retrieve objects where a field contains a PFObject that does not match a different query, you can use whereKey:doesNotMatchQuery. In order to find comments for posts without images, you can do:

// Using PFQuery
PFQuery *innerQuery = [PFQuery queryWithClassName:@"Post"];
[innerQuery whereKeyExists:@"image"];
PFQuery *query = [PFQuery queryWithClassName:@"Comment"];
[query whereKey:@"post" doesNotMatchQuery:innerQuery];
[query findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
    // comments now contains the comments for posts without images
}];

// Using NSPredicate
NSPredicate *innerPred = [NSPredicate predicateWithFormat:@"image IN SELF"];
PFQuery *innerQuery = [PFQuery queryWithClassName:@"Post" predicate:innerPred];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"NOT (post IN %@)", innerQuery];
PFQuery *query = [PFQuery queryWithClassName:@"Comment" predicate:pred];

[query findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
    // comments now contains the comments for posts without images
}];
// Using PFQuery
let innerQuery = PFQuery(className: "Post")
innerQuery.whereKeyExists("image")
let query = PFQuery(className: "Comment")
query.whereKey("post", doesNotMatchQuery: innerQuery)
query.findObjectsInBackgroundWithBlock {
    (comments: [AnyObject]?, error: NSError?) -> Void in
    // comments now contains the comments for posts with images
}

// Using NSPredicate
let innerPred = NSPredicate(format: "image IN SELF")
let innerQuery = PFQuery(className: "Post", predicate: innerPred)

let pred = NSPredicate(format: "NOT (post IN %@)", innerQuery)
let query = PFQuery(className: "Comment", predicate: pred)

query.findObjectsInBackgroundWithBlock {
    (comments: [AnyObject]?, error: NSError?) -> Void in
    // comments now contains the comments for posts with images
}

In some situations, you want to return multiple types of related objects in one query. You can do this with the includeKey: method. For example, let's say you are retrieving the last ten comments, and you want to retrieve their related posts at the same time:

PFQuery *query = [PFQuery queryWithClassName:@"Comment"];

// Retrieve the most recent ones
[query orderByDescending:@"createdAt"];

// Only retrieve the last ten
query.limit = 10;

// Include the post data with each comment
[query includeKey:@"post"];

[query findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
    // Comments now contains the last ten comments, and the "post" field
    // has been populated. For example:
    for (PFObject *comment in comments) {
         // This does not require a network access.
         PFObject *post = comment[@"post"];
         NSLog(@"retrieved related post: %@", post);
    }
}];
var query = PFQuery(className:"Comment")

// Retrieve the most recent ones
query.orderByDescending("createdAt")

// Only retrieve the last ten
query.limit = 10

// Include the post data with each comment
query.includeKey("post")

query.findObjectsInBackgroundWithBlock {
  (comments: [AnyObject]?, error: NSError?) -> Void in

  // Comments now contains the last ten comments, and the "post" field
  // has been populated. For example:
  if let comments = comments as? [PFObject] {
      for comment in comments {
          // This does not require a network access.
          var post = comment["post"] as? PFObject
          println("retrieved related post: \(post)")
      }
  }
}

You can also do multi level includes using dot notation. If you wanted to include the post for a comment and the post's author as well you can do:

[query includeKey:@"post.author"];
query.includeKey("post.author")

You can issue a query with multiple fields included by calling includeKey: multiple times. This functionality also works with PFQuery helpers like getFirstObject and getObjectInBackground

Querying the Local Datastore

If you have enabled the local datastore by calling [Parse enableLocalDatastore] before your call to [Parse setApplicationId:clientKey:], then you can also query against the objects stored locally on the device. To do this, call the fromLocalDatastore method on the query.

[query fromLocalDatastore];
[[query findObjectsInBackground] continueWithBlock:^id(BFTask *task) {
  if (!task.error) {
    // There was an error.
    return task;
  }

  // Results were successfully found from the local datastore.
  return task;
}];
query.fromLocalDatastore()
query.findObjectsInBackground().continueWithBlock({
  (task: BFTask?) -> AnyObject! in
  if let error = task?.error {
      // There was an error.
      return task
  }

  // Results were successfully found from the local datastore.

  return task
})

You can query from the local datastore using exactly the same kinds of queries you use over the network. The results will include every object that matches the query that's been pinned to your device. The query even takes into account any changes you've made to the object that haven't yet been saved to the cloud. For example, if you call deleteEventually, on an object, it will no longer be returned from these queries.

Caching Queries

It's often useful to cache the result of a query on disk. This lets you show data when the user's device is offline, or when the app has just started and network requests have not yet had time to complete. Parse takes care of automatically flushing the cache when it takes up too much space.

The default query behavior doesn't use the cache, but you can enable caching by setting query.cachePolicy. For example, to try the network and then fall back to cached data if the network is not available:

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
query.cachePolicy = kPFCachePolicyNetworkElseCache;
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    // Results were successfully found, looking first on the
    // network and then on disk.
  } else {
    // The network was inaccessible and we have no cached data for
    // this query.
  }
}];
var query = PFQuery(className:"GameScore")
query.cachePolicy = .CacheElseNetwork
query.findObjectsInBackgroundWithBlock {
  (objects: [AnyObject]?, error: NSError?) -> Void in
  if error == nil {
    // Results were successfully found, looking first on the
    // network and then on disk.
  } else {
    // The network was inaccessible and we have no cached data for
    // this query.
  }
}

Parse provides several different cache policies:

If you need to control the cache's behavior, you can use methods provided in PFQuery to interact with the cache. You can do the following operations on the cache:

Query caching also works with PFQuery helpers including getFirstObject and getObjectInBackground.

Counting Objects

Caveat: Count queries are rate limited to a maximum of 160 requests per minute. They can also return inaccurate results for classes with more than 1,000 objects. Thus, it is preferable to architect your application to avoid this sort of count operation (by using counters, for example.)

If you just need to count how many objects match a query, but you do not need to retrieve the objects that match, you can use countObjects instead of findObjects. For example, to count how many games have been played by a particular player:

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query whereKey:@"playername" equalTo:@"Sean Plott"];
[query countObjectsInBackgroundWithBlock:^(int count, NSError *error) {
  if (!error) {
    // The count request succeeded. Log the count
    NSLog(@"Sean has played %d games", count);
  } else {
    // The request failed
  }
}];
var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.countObjectsInBackgroundWithBlock {
  (count: Int, error: NSError?) -> Void in
  if error == nil {
    println("Sean has played \(count) games")
  }
}

If you want to block the calling thread, you can also use the synchronous countObjects method.

Compound Queries

If you want to find objects that match one of several queries, you can use orQueryWithSubqueries: method. For instance, if you want to find players with either have a lot of wins or a few wins, you can do:

PFQuery *lotsOfWins = [PFQuery queryWithClassName:@"Player"];
[lotsOfWins whereKey:@"wins" greaterThan:@150];

PFQuery *fewWins = [PFQuery queryWithClassName:@"Player"];
[fewWins whereKey:@"wins" lessThan:@5];
PFQuery *query = [PFQuery orQueryWithSubqueries:@[fewWins,lotsOfWins]];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
  // results contains players with lots of wins or only a few wins.
}];
var lotsOfWins = PFQuery(className:"Player")
lotsOfWins.whereKey("wins", greaterThan:150)

var fewWins = PFQuery(className:"Player")
fewWins.whereKey("wins", lessThan:5)

var query = PFQuery.orQueryWithSubqueries([lotsOfWins, fewWins])
query.findObjectsInBackgroundWithBlock {
  (results: [AnyObject]?, error: NSError?) -> Void in
  if error == nil {
    // results contains players with lots of wins or only a few wins.
  }
}

You can add additional constraints to the newly created PFQuery that act as an 'and' operator.

Note that we do not, however, support GeoPoint or non-filtering constraints (e.g. nearGeoPoint, withinGeoBox...:, limit, skip, orderBy...:, includeKey:) in the subqueries of the compound query.

Subclass Queries

You can get a query for objects of a particular subclass using the class method query. The following example queries for armors that the user can afford:

PFQuery *query = [Armor query];
[query whereKey:@"rupees" lessThanOrEqualTo:[PFUser currentUser][@"rupees"]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    Armor *firstArmor = [objects firstObject];
    // ...
  }
}];
let query = Armor.query()
query.whereKey("rupees", lessThanOrEqualTo: PFUser.currentUser()["rupees"])
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
  if error == nil {
    if let objects = objects as? [PFObject], firstArmor = objects.first {
      //...
    }
  }
}
Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Users

At the core of many apps, there is a notion of user accounts that lets users access their information in a secure manner. We provide a specialized user class called PFUser that automatically handles much of the functionality required for user account management.

With this class, you'll be able to add user account functionality in your app.

PFUser is a subclass of PFObject and has all the same features, such as flexible schema, automatic persistence, and a key value interface. All the methods that are on PFObject also exist in PFUser. The difference is that PFUser has some special additions specific to user accounts.

Properties

PFUser has several properties that set it apart from PFObject:

We'll go through each of these in detail as we run through the various use cases for users. Keep in mind that if you set username and email through these properties, you do not need to set it using the setObject:forKey: method — this is set for you automatically.

Signing Up

The first thing your app will do is probably ask the user to sign up. The following code illustrates a typical sign up:

- (void)myMethod {
    PFUser *user = [PFUser user];
    user.username = @"my name";
    user.password = @"my pass";
    user.email = @"email@example.com";

    // other fields can be set just like with PFObject
    user[@"phone"] = @"415-392-0202";

    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
      if (!error) {   // Hooray! Let them use the app now.
      } else {   NSString *errorString = [error userInfo][@"error"];   // Show the errorString somewhere and let the user try again.
      }
    }];
}
func myMethod() {
  var user = PFUser()
  user.username = "myUsername"
  user.password = "myPassword"
  user.email = "email@example.com"
  // other fields can be set just like with PFObject
  user["phone"] = "415-392-0202"

  user.signUpInBackgroundWithBlock {
    (succeeded: Bool, error: NSError?) -> Void in
    if let error = error {
      let errorString = error.userInfo?["error"] as? NSString
      // Show the errorString somewhere and let the user try again.
    } else {
      // Hooray! Let them use the app now.
    }
  }
}

This call will asynchronously create a new user in your Parse App. Before it does this, it also checks to make sure that both the username and email are unique. Also, it securely hashes the password in the cloud using bcrypt. We never store passwords in plaintext, nor will we ever transmit passwords back to the client in plaintext.

Note that we used the signUp method, not the save method. New PFUsers should always be created using the signUp method. Subsequent updates to a user can be done by calling save.

The signUp method comes in various flavors, with the ability to pass back errors, and also synchronous versions. As usual, we highly recommend using the asynchronous versions when possible, so as not to block the UI in your app. You can read more about these specific methods in our API docs.

If a signup isn't successful, you should read the error object that is returned. The most likely case is that the username or email has already been taken by another user. You should clearly communicate this to your users, and ask them try a different username.

You are free to use an email address as the username. Simply ask your users to enter their email, but fill it in the username property — PFUser will work as normal. We'll go over how this is handled in the reset password section.

Logging In

Of course, after you allow users to sign up, you need to let them log in to their account in the future. To do this, you can use the class method logInWithUsernameInBackground:password:.

[PFUser logInWithUsernameInBackground:@"myname" password:@"mypass"
  block:^(PFUser *user, NSError *error) {
    if (user) {
      // Do stuff after successful login.
    } else {
      // The login failed. Check error to see why.
    }
}];
PFUser.logInWithUsernameInBackground("myname", password:"mypass") {
  (user: PFUser?, error: NSError?) -> Void in
  if user != nil {
    // Do stuff after successful login.
  } else {
    // The login failed. Check error to see why.
  }
}

Verifying Emails

Enabling email verification in an application's settings allows the application to reserve part of its experience for users with confirmed email addresses. Email verification adds the emailVerified key to the PFUser object. When a PFUser's email is set or modified, emailVerified is set to false. Parse then emails the user a link which will set emailVerified to true.

There are three emailVerified states to consider:

  1. true - the user confirmed his or her email address by clicking on the link Parse emailed them. PFUsers can never have a true value when the user account is first created.
  2. false - at the time the PFUser object was last refreshed, the user had not confirmed his or her email address. If emailVerified is false, consider calling refresh: on the PFUser.
  3. missing - the PFUser was created when email verification was off or the PFUser does not have an email.

Current User

It would be bothersome if the user had to log in every time they open your app. You can avoid this by using the cached currentUser object.

Whenever you use any signup or login methods, the user is cached on disk. You can treat this cache as a session, and automatically assume the user is logged in:

PFUser *currentUser = [PFUser currentUser];
if (currentUser) {
    // do stuff with the user
} else {
    // show the signup or login screen
}
var currentUser = PFUser.currentUser()
if currentUser != nil {
  // Do stuff with the user
} else {
  // Show the signup or login screen
}

You can clear the current user by logging them out:

[PFUser logOut];
PFUser *currentUser = [PFUser currentUser]; // this will now be nil
PFUser.logOut()
var currentUser = PFUser.currentUser() // this will now be nil

Anonymous Users

Being able to associate data and objects with individual users is highly valuable, but sometimes you want to be able to do this without forcing a user to specify a username and password.

An anonymous user is a user that can be created without a username and password but still has all of the same capabilities as any other PFUser. After logging out, an anonymous user is abandoned, and its data is no longer accessible.

You can create an anonymous user using PFAnonymousUtils:

[PFAnonymousUtils logInWithBlock:^(PFUser *user, NSError *error) {
    if (error) {
      NSLog(@"Anonymous login failed.");
    } else {
      NSLog(@"Anonymous user logged in.");
    }
}];
PFAnonymousUtils.logInWithBlock {
  (user: PFUser?, error: NSError?) -> Void in
  if error != nil || user == nil {
    println("Anonymous login failed.")
  } else {
    println("Anonymous user logged in.")
  }
}

You can convert an anonymous user into a regular user by setting the username and password, then calling signUp, or by logging in or linking with a service like Facebook or Twitter. The converted user will retain all of its data. To determine whether the current user is an anonymous user, you can check PFAnonymousUtils isLinkedWithUser:

if ([PFAnonymousUtils isLinkedWithUser:[PFUser currentUser]]) {
    [self enableSignUpButton];
} else {
    [self enableLogOutButton];
}
if PFAnonymousUtils.isLinkedWithUser(PFUser.current()) {
  self.enableSignUpButton()
} else {
  self.enableLogOutButton()
}

Anonymous users can also be automatically created for you without requiring a network request, so that you can begin working with your user immediately when your application starts. When you enable automatic anonymous user creation at application startup, [PFUser currentUser] will never be nil. The user will automatically be created in the cloud the first time the user or any object with a relation to the user is saved. Until that point, the user's object ID will be nil. Enabling automatic user creation makes associating data with your users painless. For example, in your application:didFinishLaunchingWithOptions: function, you might write:

[PFUser enableAutomaticUser];
[[PFUser currentUser] incrementKey:@"RunCount"];
[[PFUser currentUser] saveInBackground];
PFUser.enableAutomaticUser()
PFUser.currentUser().incrementKey("RunCount")
PFUser.currentUser().saveInBackground()

Setting the Current User

If you’ve created your own authentication routines, or otherwise logged in a user on the server side, you can now pass the session token to the client and use the become method. This method will ensure the session token is valid before setting the current user.

[PFUser becomeInBackground:@"session-token-here" block:^(PFUser *user, NSError *error) {
  if (error) {
    // The token could not be validated.
  } else {
    // The current user is now set to user.
  }
}];
PFUser.becomeInBackground("session-token-here", {
  (user: PFUser?, error: NSError?) -> Void in
  if error != nil {
    // The token could not be validated.
  } else {
    // The current user is now set to user.
  }
})

Security For User Objects

The PFUser class is secured by default. Data stored in a PFUser can only be modified by that user. By default, the data can still be read by any client. Thus, some PFUser objects are authenticated and can be modified, whereas others are read-only.

Specifically, you are not able to invoke any of the save or delete methods unless the PFUser was obtained using an authenticated method, like logIn or signUp. This ensures that only the user can alter their own data.

The following illustrates this security policy:

PFUser *user = [PFUser logInWithUsername:@"my_username" password:@"my_password"];
user.username = "my_new_username"; // attempt to change username
[user save]; // This succeeds, since the user was authenticated on the device

// Get the user from a non-authenticated method
PFQuery *query = [PFUser query];
PFUser *userAgain = (PFUser *)[query getObjectWithId:user.objectId];

userAgain.username = "another_username";

// This will throw an exception, since the PFUser is not authenticated
[userAgain save];
var user = PFUser.logInWithUsername("my_username", password:"my_password")
user.username = "my_new_username" // attempt to change username
user.save() // This succeeds, since the user was authenticated on the device

// Get the user from a non-authenticated method
var query = PFUser.query()
var userAgain = query.getObjectWithId(user.objectId) as PFUser

userAgain.username = "another_username"

// This will crash, since the PFUser is not authenticated
userAgain.save()

The PFUser obtained from currentUser will always be authenticated.

If you need to check if a PFUser is authenticated, you can invoke the isAuthenticated method. You do not need to check isAuthenticated with PFUser objects that are obtained via an authenticated method.

Security For Other Objects

The same security model that applies to the PFUser can be applied to other objects. For any object, you can specify which users are allowed to read the object, and which users are allowed to modify an object. To support this type of security, each object has an access control list, implemented by the PFACL class.

The simplest way to use a PFACL is to specify that an object may only be read or written by a single user. To create such an object, there must first be a logged in PFUser. Then, the ACLWithUser method generates a PFACL that limits access to that user. An object's ACL is updated when the object is saved, like any other property. Thus, to create a private note that can only be accessed by the current user:

PFObject *privateNote = [PFObject objectWithClassName:@"Note"];
privateNote[@"content"] = @"This note is private!";
privateNote.ACL = [PFACL ACLWithUser:[PFUser currentUser]];
[privateNote saveInBackground];
var privateNote = PFObject(className:"Note")
privateNote["content"] = "This note is private!"
privateNote.ACL = PFACL.ACLWithUser(PFUser.currentUser())
privateNote.saveInBackground()

This note will then only be accessible to the current user, although it will be accessible to any device where that user is signed in. This functionality is useful for applications where you want to enable access to user data across multiple devices, like a personal todo list.

Permissions can also be granted on a per-user basis. You can add permissions individually to a PFACL using setReadAccess:forUser: and setWriteAccess:forUser:. For example, let's say you have a message that will be sent to a group of several users, where each of them have the rights to read and delete that message:

PFObject *groupMessage = [PFObject objectWithClassName:@"Message"];
PFACL *groupACL = [PFACL ACL];

// userList is an NSArray with the users we are sending this message to.
for (PFUser *user in userList) {
    [groupACL setReadAccess:YES forUser:user];
    [groupACL setWriteAccess:YES forUser:user];
}

groupMessage.ACL = groupACL;
[groupMessage saveInBackground];
var groupMessage = PFObject(className:"Message")
var groupACL = PFACL.ACL()

// userList is an NSArray with the users we are sending this message to.
for (user : PFUser in userList) {
    groupACL.setReadAccess(true, forUser:user)
    groupACL.setWriteAccess(true, forUser:user)
}

groupMessage.ACL = groupACL
groupMessage.saveInBackground()

You can also grant permissions to all users at once using setPublicReadAccess: and setPublicWriteAccess:. This allows patterns like posting comments on a message board. For example, to create a post that can only be edited by its author, but can be read by anyone:

PFObject *publicPost = [PFObject objectWithClassName:@"Post"];
PFACL *postACL = [PFACL ACLWithUser:[PFUser currentUser]];
[postACL setPublicReadAccess:YES];
publicPost.ACL = postACL;
[publicPost saveInBackground];
var publicPost = PFObject(className:"Post")
var postACL = PFACL.ACLWithUser(PFUser.currentUser())
postACL.setPublicReadAccess(true)
publicPost.ACL = postACL
publicPost.saveInBackground()

To help ensure that your users' data is secure by default, you can set a default ACL to be applied to all newly-created PFObjects:

[PFACL setDefaultACL:defaultACL withAccessForCurrentUser:YES];
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)

In the code above, the second parameter to setDefaultACL tells Parse to ensure that the default ACL assigned at the time of object creation allows read and write access to the current user at that time. Without this setting, you would need to reset the defaultACL every time a user logs in or out so that the current user would be granted access appropriately. With this setting, you can ignore changes to the current user until you explicitly need to grant different kinds of access.

Default ACLs make it easy to create apps that follow common access patterns. An application like Twitter, for example, where user content is generally visible to the world, might set a default ACL such as:

PFACL *defaultACL = [PFACL ACL];
[defaultACL setPublicReadAccess:YES];
[PFACL setDefaultACL:defaultACL withAccessForCurrentUser:YES];
var defaultACL = PFACL.ACL()
defaultACL.setPublicReadAccess(true)
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)

For an app like Dropbox, where a user's data is only accessible by the user itself unless explicit permission is given, you would provide a default ACL where only the current user is given access:

[PFACL setDefaultACL:[PFACL ACL] withAccessForCurrentUser:YES];
PFACL.setDefaultACL(PFACL.ACL(), withAccessForCurrentUser:true)

For an application that logs data to Parse but doesn't provide any user access to that data, you would deny access to the current user while providing a restrictive ACL:

[PFACL setDefaultACL:[PFACL ACL] withAccessForCurrentUser:NO];
PFACL.setDefaultACL(PFACL.ACL(), withAccessForCurrentUser:false)

Operations that are forbidden, such as deleting an object that you do not have write access to, result in a kPFErrorObjectNotFound error code. For security purposes, this prevents clients from distinguishing which object ids exist but are secured, versus which object ids do not exist at all.

Resetting Passwords

It's a fact that as soon as you introduce passwords into a system, users will forget them. In such cases, our library provides a way to let them securely reset their password.

To kick off the password reset flow, ask the user for their email address, and call:

[PFUser requestPasswordResetForEmailInBackground:@"email@example.com"];
PFUser.requestPasswordResetForEmailInBackground("email@example.com")

This will attempt to match the given email with the user's email or username field, and will send them a password reset email. By doing this, you can opt to have users use their email as their username, or you can collect it separately and store it in the email field.

The flow for password reset is as follows:

  1. User requests that their password be reset by typing in their email.
  2. Parse sends an email to their address, with a special password reset link.
  3. User clicks on the reset link, and is directed to a special Parse page that will allow them type in a new password.
  4. User types in a new password. Their password has now been reset to a value they specify.

Note that the messaging in this flow will reference your app by the name that you specified when you created this app on Parse.

Querying

To query for users, you need to use the special user query:

PFQuery *query = [PFUser query];
[query whereKey:@"gender" equalTo:@"female"]; // find all the women
NSArray *girls = [query findObjects];
var query = PFUser.query()
query.whereKey("gender", equalTo:"female")
var girls = query.findObjects()

In addition, you can use getUserObjectWithId:objectId to get a PFUser by id.

Associations

Associations involving a PFUser work right out of the box. For example, let's say you're making a blogging app. To store a new post for a user and retrieve all their posts:

PFUser *user = [PFUser currentUser];

// Make a new post
PFObject *post = [PFObject objectWithClassName:@"Post"];
post[@"title"] = @"My New Post";
post[@"body"] = @"This is some great content.";
post[@"user"] = user;
[post save];

// Find all posts by the current user
PFQuery *query = [PFQuery queryWithClassName:@"Post"];
[query whereKey:@"user" equalTo:user];
NSArray *usersPosts = [query findObjects];
var user = PFUser.currentUser()

// Make a new post
var post = PFObject(className:"Post")
post["title"] = "My New Post"
post["body"] = "This is some great content."
post["user"] = user
post.save()

Facebook Users

Parse provides an easy way to integrate Facebook with your application. The Facebook SDK can be used with our SDK, and is integrated with the PFUser class to make linking your users to their Facebook identities easy.

Learn how to use Parse with the Facebook API to create a profile viewer application. The Integrating Facebook in iOS tutorial will teach you how to create and login PFUsers through Facebook and make queries to the Facebook Graph API.

Using our Facebook integration, you can associate an authenticated Facebook user with a PFUser. With just a few lines of code, you'll be able to provide a "log in with Facebook" option in your app, and be able to save the user's data to Parse.

Note: Parse SDK is compatible both with Facebook SDK 3.x and 4.x for iOS. These instructions are for Facebook SDK 4.x.

Setup

To start using Facebook with Parse, you need to:

  1. Set up a Facebook app, if you haven't already.
  2. Add your application's Facebook Application ID on your Parse application's settings page.
  3. Follow Facebook's instructions for getting started with the Facebook SDK to create an app linked to the Facebook SDK. Double-check that you have added FacebookAppID and URL Scheme values to your application's .plist file.
  4. Download and unzip Parse iOS SDK, if you haven't already.
  5. Add ParseFacebookUtils.framework to your Xcode project, by dragging it into your project folder target.

There's also two code changes you'll need to make. First, add the following to your application:didFinishLaunchingWithOptions: method, after you've initialized the Parse SDK.

// AppDelegate.m
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <ParseFacebookUtilsV4/PFFacebookUtils.h>

@implementation AppDelegate

- (void)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [Parse setApplicationId:@"parseAppId" clientKey:@"parseClientKey"];
  [PFFacebookUtils initializeFacebookWithApplicationLaunchOptions:launchOptions];
}
// Import this header into your Swift bridge header file
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <ParseFacebookUtilsV4/PFFacebookUtils.h>

// AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  Parse.setApplicationId("parseAppId", clientKey:"parseClientKey")
  PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
}

Next, add the following handlers in your app delegate.

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
  return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                        openURL:url
                                              sourceApplication:sourceApplication
                                                     annotation:annotation];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  [FBSDKAppEvents activateApp];
}
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()
}

There are two main ways to use Facebook with your Parse users: (1) to log in (or sign up) as a Facebook user and creating a PFUser, or (2) linking Facebook to an existing PFUser.

It is up to you to record any data that you need from the Facebook user after they authenticate. To accomplish this, you'll need to do a graph query via Facebook's SDK.

Log In & Sign Up

PFUser provides a way to allow your users to log in or sign up through Facebook. This is done by using the logInInBackgroundWithReadPermissions method like so:

[PFFacebookUtils logInInBackgroundWithReadPermissions:permissions block:^(PFUser *user, NSError *error) {
  if (!user) {
    NSLog(@"Uh oh. The user cancelled the Facebook login.");
  } else if (user.isNew) {
    NSLog(@"User signed up and logged in through Facebook!");
  } else {
    NSLog(@"User logged in through Facebook!");
  }
}];
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
  (user: PFUser?, error: NSError?) -> Void in
  if let user = user {
    if user.isNew {
      println("User signed up and logged in through Facebook!")
    } else {
      println("User logged in through Facebook!")
    }
  } else {
    println("Uh oh. The user cancelled the Facebook login.")
  }
}

When this code is run, the following happens:

  1. The user is shown the Facebook login dialog.
  2. The user authenticates via Facebook, and your app receives a callback using handleOpenURL.
  3. Our SDK receives the user's Facebook access data and saves it to a PFUser. If no PFUser exists with the same Facebook ID, then a new PFUser is created.
  4. Your code block is called with the user.
  5. The current user reference will be updated to this user.

The permissions argument is an array of strings that specifies what permissions your app requires from the Facebook user. These permissions must only include read permissions. The PFUser integration doesn't require any permissions to work out of the box. Read more permissions on Facebook's developer guide.

To acquire publishing permissions for a user so that your app can, for example, post status updates on their behalf, you must call [PFFacebookUtils logInInBackgroundWithPublishPermissions:]:

[PFFacebookUtils logInInBackgroundWithPublishPermissions:@[ @"publish_actions" ] block:^(PFUser *user, NSError *error) {
  if (!user) {
    NSLog(@"Uh oh. The user cancelled the Facebook login.");
  } else {
    NSLog(@"User now has publish permissions!");
  }
}];
PFFacebookUtils.logInInBackgroundWithPublishPermissions(["publish_actions"], {
  (user: PFUser?, error: NSError?) -> Void in
  if user != nil {
    // Your app now has publishing permissions for the user
  }
})

Linking

If you want to associate an existing PFUser to a Facebook account, you can link it like so:

if (![PFFacebookUtils isLinkedWithUser:user]) {
  [PFFacebookUtils linkUserInBackground:user withReadPermissions:nil block:^(BOOL succeeded, NSError *error) {
    if (succeeded) {
      NSLog(@"Woohoo, user is linked with Facebook!");
    }
  }];
}
if !PFFacebookUtils.isLinkedWithUser(user) {
  PFFacebookUtils.linkUserInBackground(user, withReadPermissions: nil, {
    (succeeded: Bool?, error: NSError?) -> Void in
    if succeeded {
      println("Woohoo, the user is linked with Facebook!")
    }
  })
}

The steps that happen when linking are very similar to log in. The difference is that on successful login, the existing PFUser is updated with the Facebook information. Future logins via Facebook will now log in the user to their existing account.

If you want to unlink Facebook from a user, simply do this:

[PFFacebookUtils unlinkUserInBackground:user block:^(BOOL succeeded, NSError *error) {
  if (succeeded) {
    NSLog(@"The user is no longer associated with their Facebook account.");
  }
}];
PFFacebookUtils.unlinkUserInBackground(user, {
  (succeeded: Bool?, error: NSError?) -> Void in
  if succeeded {
    println("The user is no longer associated with their Facebook account.")
  }
})

Log In / Link via Token

In the previous sections, you've seen how PFFacebookUtils can be used to log in with the Facebook SDK and create a PFUser or link with existing ones. If you have already integrated the Facebook SDK and have a FBSDKAccessToken, there is an option to directly log in or link the users like this:

FBSDKAccessToken *accessToken = ...; // Use existing access token.

// Log In (create/update currentUser) with FBSDKAccessToken
[PFFacebookUtils logInInBackgroundWithAccessToken:accessToken
                                            block:^(PFUser *user, NSError *error) {
  if (!user) {
    NSLog(@"Uh oh. There was an error logging in.");
  } else {
    NSLog(@"User logged in through Facebook!");
  }
}];

//
// or
//

// Link PFUser with FBSDKAccessToken
[PFFacebookUtils linkUserInBackground:user
                      withAccessToken:accessToken
                                block:^(BOOL succeeded, NSError *error) {
  if (succeeded) {
    NSLog(@"Woohoo, the user is linked with Facebook!");
  }
}];
let accessToken: FBSDKAccessToken = ...; // Use existing access token.

// Log In (create/update currentUser) with FBSDKAccessToken
PFFacebookUtils.logInInBackgroundWithAccessToken(accessToken, {
  (user: PFUser?, error: NSError?) -> Void in
  if user != nil {
    println("User logged in through Facebook!")
  } else {
    println("Uh oh. There was an error logging in.")
  }
})

//
// or
//

// Link PFUser with FBSDKAccessToken
PFFacebookUtils.linkUserInBackground(user, withAccessToken: accessToken, {
  (succeeded: Bool?, error: NSError?) -> Void in
  if succeeded {
    println("Woohoo, the user is linked with Facebook!")
  }
})

Additional Permissions

Since Facebook SDK v4.0 - it is required to request read and publish permissions separately. With Parse SDK integration you can do that by logging in with read permissions first, and later, when the user wants to post to Facebook - linking a user with new set of publish permissions. This also works the other way around: logging in with publish permissions and linking with additional read permissions.

// Log In with Read Permissions
[PFFacebookUtils logInInBackgroundWithReadPermissions:permissions block:^(PFUser *user, NSError *error) {
  if (!user) {
    NSLog(@"Uh oh. The user cancelled the Facebook login.");
  } else if (user.isNew) {
    NSLog(@"User signed up and logged in through Facebook!");
  } else {
    NSLog(@"User logged in through Facebook!");
  }
}];

// Request new Publish Permissions
[PFFacebookUtils linkUserInBackground:[PFUser currentUser]
                withPublishPermissions:@[ @"publish_actions"]
                                block:^(BOOL succeeded, NSError *error) {
  if (succeeded) {
    NSLog(@"User now has read and publish permissions!");
  }
}];
// Log In with Read Permissions
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions, {
  (user: PFUser?, error: NSError?) -> Void in
  if let user = user {
    if user.isNew {
      println("User signed up and logged in through Facebook!")
    } else {
      println("User logged in through Facebook!")
    }
  } else {
    println("Uh oh. The user cancelled the Facebook login.")
  }
})

// Request new Publish Permissions
PFFacebookUtils.linkUserInBackground(user, withPublishPermissions: ["publish_actions"], {
  (succeeded: Bool?, error: NSError?) -> Void in
  if succeeded {
    println("User now has read and publish permissions!")
  }
})

Facebook SDK and Parse

The Facebook iOS SDK provides a number of helper classes for interacting with Facebook's API. Generally, you will use the FBSDKGraphRequest class to interact with Facebook on behalf of your logged-in user. You can read more about the Facebook SDK here.

To access the user's Facebook access token, you can simply call [FBSDKAccessToken currentAccessToken] to access the FBSDKAccessToken instance, which can be passed to FBSDKGraphRequests.

Twitter Users

As with Facebook, Parse also provides an easy way to integrate Twitter authentication into your application. The Parse SDK provides a straightforward way to authorize and link a Twitter account to your PFUsers. With just a few lines of code, you'll be able to provide a "log in with Twitter" option in your app, and be able to save their data to Parse.

Setup

To start using Twitter with Parse, you need to:

  1. Set up a Twitter app, if you haven't already.
  2. Add your application's Twitter consumer key on your Parse application's settings page.
  3. When asked to specify a "Callback URL" for your Twitter app, please insert a valid URL. This value will not be used by your iOS or Android application, but is necessary in order to enable authentication through Twitter.
  4. Add the Accounts.framework and Social.framework libraries to your Xcode project.
  5. Add the following where you initialize the Parse SDK, such as in application:didFinishLaunchingWithOptions:.
    [PFTwitterUtils initializeWithConsumerKey:@"YOUR CONSUMER KEY"
                           consumerSecret:@"YOUR CONSUMER SECRET"];
    
    PFTwitterUtils.initializeWithConsumerKey("YOUR CONSUMER KEY",  consumerSecret:"YOUR CONSUMER SECRET")
    

If you encounter any issues that are Twitter-related, a good resource is the official Twitter documentation.

There are two main ways to use Twitter with your Parse users: (1) logging in as a Twitter user and creating a PFUser, or (2) linking Twitter to an existing PFUser.

Login & Signup

PFTwitterUtils provides a way to allow your PFUsers to log in or sign up through Twitter. This is accomplished using the logInWithBlock or logInWithTarget messages:

[PFTwitterUtils logInWithBlock:^(PFUser *user, NSError *error) {
    if (!user) {
      NSLog(@"Uh oh. The user cancelled the Twitter login.");
      return;
    } else if (user.isNew) {
      NSLog(@"User signed up and logged in with Twitter!");
    } else {
      NSLog(@"User logged in with Twitter!");
    }
}];
PFTwitterUtils.logInWithBlock {
  (user: PFUser?, error: NSError?) -> Void in
  if let user = user {
    if user.isNew {
      println("User signed up and logged in with Twitter!")
    } else {
      println("User logged in with Twitter!")
    }
  } else {
    println("Uh oh. The user cancelled the Twitter login.")
  }
}

When this code is run, the following happens:

  1. The user is shown the Twitter login dialog.
  2. The user authenticates via Twitter, and your app receives a callback.
  3. Our SDK receives the Twitter data and saves it to a PFUser. If it's a new user based on the Twitter handle, then that user is created.
  4. Your block is called with the user.

Twitter Linking

If you want to associate an existing PFUser with a Twitter account, you can link it like so:

if (![PFTwitterUtils isLinkedWithUser:user]) {
    [PFTwitterUtils linkUser:user block:^(BOOL succeeded, NSError *error) {
        if ([PFTwitterUtils isLinkedWithUser:user]) {
          NSLog(@"Woohoo, user logged in with Twitter!");
        }
    }];
}
if !PFTwitterUtils.isLinkedWithUser(user) {
  PFTwitterUtils.linkUser(user, {
    (succeeded: Bool?, error: NSError?) -> Void in
    if PFTwitterUtils.isLinkedWithUser(user) {
      println("Woohoo, user logged in with Twitter!")
    }
  })
}

The steps that happen when linking are very similar to log in. The difference is that on successful login, the existing PFUser is updated with the Twitter information. Future logins via Twitter will now log the user into their existing account.

If you want to unlink Twitter from a user, simply do this:

[PFTwitterUtils unlinkUserInBackground:user block:^(BOOL succeeded, NSError *error) {
    if (!error && succeeded) {
      NSLog(@"The user is no longer associated with their Twitter account.");
    }
}];
PFTwitterUtils.unlinkUserInBackground(user, {
  (succeeded: Bool?, error: NSError?) -> Void in
  if error == nil && succeeded {
    println("The user is no longer associated with their Twitter account.")
  }
})

Twitter API Calls

Our SDK provides a straightforward way to sign your API HTTP requests to the Twitter REST API when your app has a Twitter-linked PFUser. To make a request through our API, you can use the PF_Twitter singleton provided by PFTwitterUtils:

NSURL *verify = [NSURL URLWithString:@"https://api.twitter.com/1/account/verify_credentials.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:verify];
[[PFTwitterUtils twitter] signRequest:request];
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:&response  
                                                 error:&error];
Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Sessions

Sessions represent an instance of a user logged into a device. Sessions are automatically created when users log in or sign up. They are automatically deleted when users log out. There is one distinct PFSession object for each user-installation pair; if a user issues a login request from a device they're already logged into, that user's previous PFSession object for that Installation is automatically deleted. PFSession objects are stored on Parse in the Session class, and you can view them on the Parse.com Data Browser. We provide a set of APIs to manage PFSession objects in your app.

Session APIs are only available in apps with revocable sessions enabled. Parse apps created after March 25, 2015 have this enabled by default ("Require Revocable Sessions" toggle in your Parse.com app settings page). If you have an existing app, you can upgrade to revocable sessions by following the Session Migration Tutorial.

PFSession is a subclass of PFObject, so you can query, update, and delete sessions in the same way that you manipulate normal objects on Parse. Because the Parse Cloud automatically creates sessions when you log in or sign up users, you should not manually create PFSession objects unless you are building a "Parse for IoT" app (e.g. Arduino or Embedded C). Deleting a PFSession will log the user out of the device that is currently using this session's token.

Unlike other Parse objects, the PFSession class does not have Cloud Code triggers. So you cannot register a beforeSave or afterSave handler for the Session class.

Properties

The PFSession object has these special fields:

Handling Invalid Session Token Error

Apps created before March 25, 2015 use legacy session tokens until you migrate them to use the new revocable sessions. On API requests with legacy tokens, if the token is invalid (e.g. User object was deleted), then the request is executed as a non-logged in user and no error was returned. On API requests with revocable session tokens, an invalid session token will always fail with the "invalid session token" error. This new behavior lets you know when you need to ask the user to log in again.

With revocable sessions, your current session token could become invalid if its corresponding PFSession object is deleted from the Parse Cloud. This could happen if you implement a Session Manager UI that lets users log out of other devices, or if you manually delete the session via Cloud Code, REST API, or Data Browser. Sessions could also be deleted due to automatic expiration (if configured in app settings). When a device's session token no longer corresponds to a PFSession object on the Parse Cloud, all API requests from that device will fail with “Error 209: invalid session token”.

To handle this error, we recommend writing a global utility function that is called by all of your Parse request error callbacks. You can then handle the "invalid session token" error in this global function. You should prompt the user to login again so that they can obtain a new session token. This code could look like this:

@interface ParseErrorHandlingController : NSObject

+ (void)handleParseError:(NSError *)error;

@end

@implementation ParseErrorHandlingController

+ (void)handleError:(NSError *)error {
  if (![error.domain isEqualToString:PFParseErrorDomain]) {
    return;
  }

  switch (error.code) {
    case kPFErrorInvalidSessionToken: {
      [self _handleInvalidSessionTokenError];
      break;
    }
    ... // Other Parse API Errors that you want to explicitly handle.
  }
}

+ (void)_handleInvalidSessionTokenError {
  //--------------------------------------
  // Option 1: Show a message asking the user to log out and log back in.
  //--------------------------------------
  // If the user needs to finish what they were doing, they have the opportunity to do so.
  //
  // UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Invalid Session"
  //                                                     message:@"Session is no longer valid, please log out and log in again."
  //                                                    delegate:self
  //                                           cancelButtonTitle:@"Not Now"
  //                                           otherButtonTitles:@"OK"];
  // [alertView show];

  //--------------------------------------
  // Option #2: Show login screen so user can re-authenticate.
  //--------------------------------------
  // You may want this if the logout button is inaccessible in the UI.
  //
  // UIViewController *presentingViewController = [[UIApplication sharedApplication].keyWindow.rootViewController;
  // PFLogInViewController *logInViewController = [[PFLogInViewController alloc] init];
  // [presentingViewController presentViewController:logInViewController animated:YES completion:nil];
}

@end

// In all API requests, call the global error handler, e.g.
[[PFQuery queryWithClassName:@"Object"] findInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    // Query succeeded - continue your app logic here.
  } else {
    // Query failed - handle an error.
    [ParseErrorHandlingController handleParseError:error];
  }
}];
class ParseErrorHandlingController {
  class func handleParseError(error: NSError) {
    if error.domain != PFParseErrorDomain {
      return
    }

    switch (error.code) {
    case kPFErrorInvalidSessionToken:
      handleInvalidSessionTokenError()

    ... // Other Parse API Errors that you want to explicitly handle.
  }

  private class func handleInvalidSessionTokenError() {
    //--------------------------------------
    // Option 1: Show a message asking the user to log out and log back in.
    //--------------------------------------
    // If the user needs to finish what they were doing, they have the opportunity to do so.
    //
    // let alertView = UIAlertView(
    //   title: "Invalid Session",
    //   message: "Session is no longer valid, please log out and log in again.",
    //   delegate: nil,
    //   cancelButtonTitle: "Not Now",
    //   otherButtonTitles: "OK"
    // )
    // alertView.show()

    //--------------------------------------
    // Option #2: Show login screen so user can re-authenticate.
    //--------------------------------------
    // You may want this if the logout button is inaccessible in the UI.
    //
    // let presentingViewController = UIApplication.sharedApplication().keyWindow?.rootViewController
    // let logInViewController = PFLogInViewController()
    // presentingViewController?.presentViewController(logInViewController, animated: true, completion: nil)
  }
}

// In all API requests, call the global error handler, e.g.
let query = PFQuery(className: "Object")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
  if error == nil {
    // Query Succeeded - continue your app logic here.
  } else {
    // Query Failed - handle an error.
    ParseErrorHandlingController.handleParseError(error)
  }
}
public class ParseErrorHandler {
  public static void handleParseError(ParseException e) {
    switch (e.getCode()) {
      case INVALID_SESSION_TOKEN: handleInvalidSessionToken()
        break;

      ... // Other Parse API errors that you want to explicitly handle
    }
  }

  private static void handleInvalidSessionToken() {
    //--------------------------------------
    // Option 1: Show a message asking the user to log out and log back in.
    //--------------------------------------
    // If the user needs to finish what they were doing, they have the opportunity to do so.
    //
    // new AlertDialog.Builder(getActivity())
    //   .setMessage("Session is no longer valid, please log out and log in again.")
    //   .setCancelable(false).setPositiveButton("OK", ...).create().show();

    //--------------------------------------
    // Option #2: Show login screen so user can re-authenticate.
    //--------------------------------------
    // You may want this if the logout button could be inaccessible in the UI.
    //
    // startActivityForResult(new ParseLoginBuilder(getActivity()).build(), 0);
  }
});

// In all API requests, call the global error handler, e.g.
query.findInBackground(new FindCallback<ParseObject>() {
  public void done(List<ParseObject> results, ParseException e) {
    if (e == null) {
      // Query successful, continue other app logic
    } else {
      // Query failed
      ParseErrorHandler.handleParseError(e);
    }
  }
});
function handleParseError(err) {
  switch (err.code) {
    case Parse.Error.INVALID_SESSION_TOKEN:
      Parse.User.logOut();
      ... // If web browser, render a log in screen
      ... // If Express.js, redirect the user to the log in route
      break;

    ... // Other Parse API errors that you want to explicitly handle
  }
}

// For each API request, call the global error handler
query.find().then(function() {
  ...
}, function(err) {
  handleParseError(err);
});
public class ParseErrorHandler {
  public static void HandleParseError(ParseException e) {
    switch (e.Code) {
      case ParseException.ErrorCode.InvalidSessionToken:
        HandleInvalidSessionToken()
        break;

      ... // Other Parse API errors that you want to explicitly handle
    }
  }

  private static void HandleInvalidSessionToken() {
    //--------------------------------------
    // Option 1: Show a message asking the user to log out and log back in.
    //--------------------------------------
    // If the user needs to finish what they were doing, they have the opportunity to do so.

    //--------------------------------------
    // Option #2: Show login screen so user can re-authenticate.
    //--------------------------------------
    // You may want this if the logout button is inaccessible in the UI.
  }
});

// In all API requests, call the global error handler, e.g.
query.FindAsync().ContinueWith(t => {
  if (t.IsFaulted) {
    // Query Failed - handle an error.
    ParseErrorHandler.HandleParseError(t.Exception.InnerException as ParseException);
  } else {
    // Query Succeeded - continue your app logic here.
  }
});
public class ParseErrorHandler {
  public static handleParseError(ParseException $e) {
    $code = $e->getCode();
    switch ($code) {
      case: 209: // INVALID_SESSION_TOKEN
        ParseUser::logOut();
        ... // Redirect the to login page.
        break;

      ... // Other Parse API errors that you want to explicitly handle
    }
  }
});

// For each API request, call the global error handler
try {
  $results = $query->find();
  // ...
} catch (ParseException $e) {
  ParseErrorHandler::handleParseError($e)
}

Security

PFSession objects can only be accessed by the user specified in the user field. All PFSession objects have an ACL that is read and write by that user only. You cannot change this ACL. This means querying for sessions will only return objects that match the current logged-in user.

When you log in a user via [ParseUser logInInBackground], Parse will automatically create a new unrestricted PFSession object in the Parse Cloud. Same for signups and Facebook/Twitter logins.

Session objects manually created from client SDKs (by creating an instance of PFSession, and saving it) are always restricted. You cannot manually create an unrestricted sessions using the object creation API.

Restricted sessions are prohibited from creating, modifying, or deleting any data in the PFUser, PFSession, and PFRole classes. Restricted session also cannot read unrestricted sessions. Restricted Sessions are useful for "Parse for IoT" devices (e.g Arduino or Embedded C) that may run in a less-trusted physical environment than mobile apps. However, please keep in mind that restricted sessions can still read data on PFUser, PFSession, and PFRole classes, and can read/write data in any other class just like a normal session. So it is still important for IoT devices to be in a safe physical environment and ideally use encrypted storage to store the session token.

If you want to prevent restricted Sessions from modifying classes other than PFUser, PFSession, or PFRole, you can write a Cloud Code beforeSave handler for that class:

Parse.Cloud.beforeSave("MyClass", function(request, response) {
  Parse.Session.current().then(function(session) {
    if (session.get('restricted')) {
      response.error('write operation not allowed');
    }
    response.success();
  });
});

You can configure Class-Level Permissions (CLPs) for the Session class just like other classes on Parse. CLPs restrict reading/writing of sessions via the PFSession API, but do not restrict Parse Cloud's automatic session creation/deletion when users log in, sign up, and log out. We recommend that you disable all CLPs not needed by your app. Here are some common use cases for Session CLPs:

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Roles

As your app grows in scope and user-base, you may find yourself needing more coarse-grained control over access to pieces of your data than user-linked ACLs can provide. To address this requirement, Parse supports a form of Role-based Access Control. Roles provide a logical way of grouping users with common access privileges to your Parse data. Roles are named objects that contain users and other roles. Any permission granted to a role is implicitly granted to its users as well as to the users of any roles that it contains.

For example, in your application with curated content, you may have a number of users that are considered "Moderators" and can modify and delete content created by other users. You may also have a set of users that are "Administrators" and are allowed all of the same privileges as Moderators, but can also modify the global settings for the application. By adding users to these roles, you can ensure that new users can be made moderators or administrators, without having to manually grant permission to every resource for each user.

We provide a specialized class called PFRole that represents these role objects in your client code. PFRole is a subclass of PFObject, and has all of the same features, such as a flexible schema, automatic persistence, and a key value interface. All the methods that are on PFObject also exist on PFRole. The difference is that PFRole has some additions specific to management of roles.

Properties

PFRole has several properties that set it apart from PFObject:

Security for Role Objects

The PFRole uses the same security scheme (ACLs) as all other objects on Parse, except that it requires an ACL to be set explicitly. Generally, only users with greatly elevated privileges (e.g. a master user or Administrator) should be able to create or modify a Role, so you should define its ACLs accordingly. Remember, if you give write-access to a PFRole to a user, that user can add other users to the role, or even delete the role altogether.

To create a new PFRole, you would write:

// By specifying no write privileges for the ACL, we can ensure the role cannot be altered.
PFACL *roleACL = [PFACL ACL];
[roleACL setPublicReadAccess:YES];
PFRole *role = [PFRole roleWithName:@"Administrator" acl:roleACL];
[role saveInBackground];
// By specifying no write privileges for the ACL, we can ensure the role cannot be altered.
var roleACL = PFACL.ACL()
roleACL.setPublicReadAccess(true)
var role = PFRole.roleWithName("Administrator", acl:roleACL)
role.saveInBackground()

You can add users and roles that should inherit your new role's permissions through the "users" and "roles" relations on PFRole:

PFRole *role = [PFRole roleWithName:roleName acl:roleACL];
for (PFUser *user in usersToAddToRole) {
  [role.users addObject:user];
}
for (PFRole *childRole in rolesToAddToRole) {
  [role.roles addObject:childRole];
}
[role saveInBackground];
var role = PFRole.roleWithName(roleName, acl:roleACL)
for user in usersToAddToRole {
  role.users.addObject(user)
}
for childRole in rolesToAddToRole {
  role.roles.addObject(childRole)
}
role.saveInBackground()

Take great care when assigning ACLs to your roles so that they can only be modified by those who should have permissions to modify them.

Security for Other Objects

Now that you have created a set of roles for use in your application, you can use them with ACLs to define the privileges that their users will receive. Each PFObject can specify a PFACL, which provides an access control list that indicates which users and roles should be granted read or write access to the object.

Giving a role read or write permission to an object is straightforward. You can either use the PFRole:

PFRole *moderators = /* Query for some PFRole */;
PFObject *wallPost = [PFObject objectWithClassName:@"WallPost"];
PFACL *postACL = [PFACL ACL];
[postACL setWriteAccess:YES forRole:moderators];
wallPost.ACL = postACL;
[wallPost saveInBackground];
var moderators = /* Query for some PFRole */
var wallPost = PFObject(className:"WallPost")
var postACL = PFACL.ACL()
postACL.setWriteAccess(true, forRole:moderators)
wallPost.ACL = postACL
wallPost.saveInBackground()

You can avoid querying for a role by specifying its name for the ACL:

PFObject *wallPost = [PFObject objectWithClassName:@"WallPost"];
PFACL *postACL = [PFACL ACL];
[postACL setWriteAccess:YES forRoleWithName:@"Moderators"];
wallPost.ACL = postACL;
[wallPost saveInBackground];
var wallPost = PFObject(className:"WallPost")
var postACL = PFACL.ACL()
postACL.setWriteAccess(true, forRoleWithName:"Moderators")
wallPost.ACL = postACL
wallPost.saveInBackground()

Role-based PFACLs can also be used when specifying default ACLs for your application, making it easy to protect your users' data while granting access to users with additional privileges. For example, a moderated forum application might specify a default ACL like this:

PFACL *defaultACL = [PFACL ACL];
// Everybody can read objects created by this user
[defaultACL setPublicReadAccess:YES];
// Moderators can also modify these objects
[defaultACL setWriteAccess:YES forRoleWithName:@"Moderators"];
// And the user can read and modify its own objects
[PFACL setDefaultACL:defaultACL withAccessForCurrentUser:YES];
var defaultACL = PFACL.ACL()
// Everybody can read objects created by this user
defaultACL.setPublicReadAccess(true)
// Moderators can also modify these objects
defaultACL.setWriteAccess(true, forRoleWithName:"Moderators")
// And the user can read and modify its own objects
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)

Role Hierarchy

As described above, one role can contain another, establishing a parent-child relationship between the two roles. The consequence of this relationship is that any permission granted to the parent role is implicitly granted to all of its child roles.

These types of relationships are commonly found in applications with user-managed content, such as forums. Some small subset of users are "Administrators", with the highest level of access to tweaking the application's settings, creating new forums, setting global messages, and so on. Another set of users are "Moderators", who are responsible for ensuring that the content created by users remains appropriate. Any user with Administrator privileges should also be granted the permissions of any Moderator. To establish this relationship, you would make your "Administrators" role a child role of "Moderators", like this:

PFRole *administrators = /* Your "Administrators" role */;
PFRole *moderators = /* Your "Moderators" role */;
[moderators.roles addObject:administrators];
[moderators saveInBackground];
var administrators = /* Your "Administrators" role */
var moderators = /* Your "Moderators" role */
moderators.roles.addObject(administrators)
moderators.saveInBackground()
Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Files

The PFFile

PFFile lets you store application files in the cloud that would otherwise be too large or cumbersome to fit into a regular PFObject. The most common use case is storing images but you can also use it for documents, videos, music, and any other binary data (up to 10 megabytes).

Learn how to make an app that allows the user to take photos and upload it directly to Parse in our Saving Images tutorial.

Getting started with PFFile is easy. First, you'll need to have the data in NSData form and then create a PFFile with it. In this example, we'll just use a string:

NSData *data = [@"Working at Parse is great!" dataUsingEncoding:NSUTF8StringEncoding];
PFFile *file = [PFFile fileWithName:@"resume.txt" data:data];
let str = "Working at Parse is great!"
let data = str.dataUsingEncoding(NSUTF8StringEncoding)
let file = PFFile(name:"resume.txt", data:data)

Notice in this example that we give the file a name of resume.txt. There's two things to note here:

Next you'll want to save the file up to the cloud. As with PFObject, there are many variants of the save method you can use depending on what sort of callback and error handling suits you.

[file saveInBackground];
file.saveInBackground()

Finally, after the save completes, you can associate a PFFile onto a PFObject just like any other piece of data:

PFObject *jobApplication = [PFObject objectWithClassName:@"JobApplication"]
jobApplication[@"applicantName"] = @"Joe Smith";
jobApplication[@"applicantResumeFile"] = file;
[jobApplication saveInBackground];
var jobApplication = PFObject(className:"JobApplication")
jobApplication["applicantName"] = "Joe Smith"
jobApplication["applicantResumeFile"] = file
jobApplication.saveInBackground()

Retrieving it back involves calling one of the getData variants on the PFFile. Here we retrieve the resume file off another JobApplication object:

PFFile *applicantResume = anotherApplication[@"applicantResumeFile"];
NSData *resumeData = [applicantResume getData];
let applicantResume = annotherApplication["applicationResumeFile"] as PFFile
let resumeData = applicantResume.getData()

Just like on PFObject, you will most likely want to use the background version of getData.

Images

You can easily store images by converting them to NSData and then using PFFile. Suppose you have a UIImage named image that you want to save as a PFFile:

NSData *imageData = UIImagePNGRepresentation(image);
PFFile *imageFile = [PFFile fileWithName:@"image.png" data:imageData];

PFObject *userPhoto = [PFObject objectWithClassName:@"UserPhoto"];
userPhoto[@"imageName"] = @"My trip to Hawaii!";
userPhoto[@"imageFile"] = imageFile;
[userPhoto saveInBackground];
let imageData = UIImagePNGRepresentation(image)
let imageFile = PFFile(name:"image.png", data:imageData)

var userPhoto = PFObject(className:"UserPhoto")
userPhoto["imageName"] = "My trip to Hawaii!"
userPhoto["imageFile"] = imageFile
userPhoto.saveInBackground()

Your PFFile will be uploaded as part of the save operation on the userPhoto object. It's also possible to track a PFFile's upload and download progress.

Retrieving the image back involves calling one of the getData variants on the PFFile. Here we retrieve the image file off another UserPhoto named anotherPhoto:

PFFile *userImageFile = anotherPhoto[@"imageFile"];
[userImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
    if (!error) {
        UIImage *image = [UIImage imageWithData:imageData];
    }
}];
let userImageFile = anotherPhoto["imageFile"] as PFFile
userImageFile.getDataInBackgroundWithBlock {
  (imageData: NSData?, error: NSError?) -> Void in
  if error == nil {
    if let imageData = imageData {
        let image = UIImage(data:imageData)
    }
  }
}

Progress

It's easy to get the progress of both uploads and downloads using PFFile using saveInBackgroundWithBlock:progressBlock: and getDataInBackgroundWithBlock:progressBlock: respectively. For example:

NSData *data = [@"Working at Parse is great!" dataUsingEncoding:NSUTF8StringEncoding];
PFFile *file = [PFFile fileWithName:@"resume.txt" data:data];
[file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
  // Handle success or failure here ...
} progressBlock:^(int percentDone) {
  // Update your progress spinner here. percentDone will be between 0 and 100.
}];
let str = "Working at Parse is great!"
let data = str.dataUsingEncoding(NSUTF8StringEncoding)
let file = PFFile(name:"resume.txt", data:data)
file.saveInBackgroundWithBlock({
  (succeeded: Bool, error: NSError?) -> Void in
  // Handle success or failure here ...
}, progressBlock: {
  (percentDone: Int32) -> Void in
  // Update your progress spinner here. percentDone will be between 0 and 100.
})

You can delete files that are referenced by objects using the REST API. You will need to provide the master key in order to be allowed to delete a file.

If your files are not referenced by any object in your app, it is not possible to delete them through the REST API. You may request a cleanup of unused files in your app's Settings page. Keep in mind that doing so may break functionality which depended on accessing unreferenced files through their URL property. Files that are currently associated with an object will not be affected.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

GeoPoints

Parse allows you to associate real-world latitude and longitude coordinates with an object. Adding a PFGeoPoint to a PFObject allows queries to take into account the proximity of an object to a reference point. This allows you to easily do things like find out what user is closest to another user or which places are closest to a user.

Explore the use of PFGeoPoints and PFUser in a real application with our Anywall tutorial. You'll learn everything from implementing a basic user management workflow to tracking GPS location with Core Location.

PFGeoPoint

To associate a point with an object you first need to create a PFGeoPoint. For example, to create a point with latitude of 40.0 degrees and -30.0 degrees longitude:

PFGeoPoint *point = [PFGeoPoint geoPointWithLatitude:40.0 longitude:-30.0];
let point = PFGeoPoint(latitude:40.0, longitude:-30.0)

This point is then stored in the object as a regular field.

placeObject[@"location"] = point;
placeObject["location"] = point

Note: Currently only one key in a class may be a PFGeoPoint.

Getting the User's Current Location

PFGeoPoint also provides a helper method for fetching the user's current location. This is accomplished via geoPointForCurrentLocationInBackground:

[PFGeoPoint geoPointForCurrentLocationInBackground:^(PFGeoPoint *geoPoint, NSError *error) {
    if (!error) {
        // do something with the new geoPoint
    }
}];
PFGeoPoint.geoPointForCurrentLocationInBackground {
  (geoPoint: PFGeoPoint?, error: NSError?) -> Void in
  if error == nil {
    // do something with the new geoPoint
  }
}

When this code is run, the following happens:

  1. An internal CLLocationManager starts listening for location updates (via startsUpdatingLocation).
  2. Once a location is received, the location manager stops listening for location updates (via stopsUpdatingLocation) and a PFGeoPoint is created from the new location. If the location manager errors out, it still stops listening for updates, and returns an NSError instead.
  3. Your block is called with the PFGeoPoint.

For those who choose to use CLLocationManager directly, we also provide a +geoPointWithLocation: constructor to transform CLLocations directly into PFGeoPoints - great for apps that require constant polling.

Geo Queries

Now that you have a bunch of objects with spatial coordinates, it would be nice to find out which objects are closest to a point. This can be done by adding another restriction to PFQuery using whereKey:nearGeoPoint:. Getting a list of ten places that are closest to a user may look something like:

// User's location
PFGeoPoint *userGeoPoint = userObject[@"location"];
// Create a query for places
PFQuery *query = [PFQuery queryWithClassName:@"PlaceObject"];
// Interested in locations near user.
[query whereKey:@"location" nearGeoPoint:userGeoPoint];
// Limit what could be a lot of points.
query.limit = 10;
// Final list of objects
placesObjects = [query findObjects];
// User's location
let userGeoPoint = userObject["location"] as PFGeoPoint
// Create a query for places
var query = PFQuery(className:"PlaceObject")
// Interested in locations near user.
query.whereKey("location", nearGeoPoint:userGeoPoint)
// Limit what could be a lot of points.
query.limit = 10
// Final list of objects
placesObjects = query.findObjects()

At this point placesObjects will be an array of objects ordered by distance (nearest to farthest) from userGeoPoint. Note that if an additional orderByAscending:/orderByDescending: constraint is applied, it will take precedence over the distance ordering.

To limit the results using distance check out whereKey:nearGeoPoint:withinMiles, whereKey:nearGeoPoint:withinKilometers, and whereKey:nearGeoPoint:withinRadians.

It's also possible to query for the set of objects that are contained within a particular area. To find the objects in a rectangular bounding box, add the whereKey:withinGeoBoxFromSouthwest:toNortheast: restriction to your PFQuery.

PFGeoPoint *swOfSF = [PFGeoPoint geoPointWithLatitude:37.708813 longitude:-122.526398];
PFGeoPoint *neOfSF = [PFGeoPoint geoPointWithLatitude:37.822802 longitude:-122.373962];
PFQuery *query = [PFQuery queryWithClassName:@"PizzaPlaceObject"];
[query whereKey:@"location" withinGeoBoxFromSouthwest:swOfSF toNortheast:neOfSF];
NSArray *pizzaPlacesInSF = [query findObjects];
let swOfSF = PFGeoPoint(latitude:37.708813, longitude:-122.526398)
let neOfSF = PFGeoPoint(latitude:37.822802, longitude:-122.373962)
var query = PFQuery(className:"PizzaPlaceObject")
query.whereKey("location", withinGeoBoxFromSouthwest:swOfSF, toNortheast:neOfSF)
var pizzaPlacesInSF = query.findObjects()

Caveats

At the moment there are a couple of things to watch out for:

  1. Each PFObject class may only have one key with a PFGeoPoint object.
  2. Using the nearGeoPoint constraint will also limit results to within 100 miles.
  3. Points should not equal or exceed the extreme ends of the ranges. Latitude should not be -90.0 or 90.0. Longitude should not be -180.0 or 180.0. Attempting to set latitude or longitude out of bounds will cause an error.
Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Relations

There are three kinds of relationships. One-to-one relationships enable one object to be associated with another object. One-to-many relationships enable one object to have many related objects. Finally, many-to-many relationships enable complex relationships among many objects.

There are four ways to build relationships in Parse:

One-to-Many

When you’re thinking about one-to-many relationships and whether to implement Pointers or Arrays, there are several factors to consider. First, how many objects are involved in this relationship? If the "many" side of the relationship could contain a very large number (greater than 100 or so) of objects, then you have to use Pointers. If the number of objects is small (fewer than 100 or so), then Arrays may be more convenient, especially if you typically need to get all of the related objects (the "many" in the "one-to-many relationship") at the same time as the parent object.

Using Pointers

Let's say we have a game app. The game keeps track of the player's score and achievements every time she chooses to play. In Parse, we can store this data in a single Game object. If the game becomes incredibly successful, each player will store thousands of Game objects in the system. For circumstances like this, where the number of relationships can be arbitrarily large, Pointers are the best option.

Suppose in this game app, we want to make sure that every Game object is associated with a Parse User. We can implement this like so:

ParseObject game = new ParseObject("Game");
game.put("createdBy", ParseUser.getCurrentUser());
PFObject *game= [PFObject objectWithClassName:@"Game"];
[game setObject:[PFUser currentUser] forKey:@"createdBy"];
let game = PFObject(className:"Game")
game["createdBy"] = PFUser.currentUser()
$game = ParseObject::create("Game");
$game->set("createdBy", ParseUser::getCurrentUser());
var game = new ParseObject("Game");
game["createdBy"] = ParseUser.CurrentUser;
var game = new Parse.Object("Game");
game.set("createdBy", Parse.User.current());

We can obtain all of the Game objects created by a Parse User with a query:

ParseQuery<ParseObject> gameQuery = ParseQuery.getQuery("Game");
gameQuery.whereEqualTo("createdBy", ParseUser.getCurrentUser());
PFQuery *gameQuery = [PFQuery queryWithClassName:@"Game"];
[gameQuery whereKey:@"createdBy" equalTo:[PFUser currentUser]];
let gameQuery = PFQuery(className:"Game")
if let user = PFUser.currentUser() {
  gameQuery.whereKey("createdBy", equalTo: user)
}
$gameQuery = new ParseQuery("Game");
$gameQuery->equalTo("createdBy", ParseUser::getCurrentUser());
var query = ParseObject.getQuery("Game").WhereEqualTo("createdBy", ParseUser.CurrentUser);
var query = new Parse.Query("Game");
query.equalTo("createdBy", Parse.User.current());

And, if we want to find the Parse User who created a specific Game, that is a lookup on the createdBy key:

// say we have a Game object
ParseObject game = ...

// getting the user who created the Game
ParseUser createdBy = game.getUser("createdBy");
// say we have a Game object
PFObject *game = ...

// getting the user who created the Game
PFUser *createdBy = [game objectForKey@"createdBy"];
// say we have a Game object
let game = ...

// getting the user who created the Game
let createdBy = game["createdBy"]
// say we have a Game object
$game = ...

// getting the user who created the Game
$user = $game["createdBy"];
// say we have a Game object
ParseObject game = ...

// getting the user who created the Game
ParseUser user = game["createdBy"];
// say we have a Game object
var game = ...

// getting the user who created the Game
var user = game.get("createdBy");

For most scenarios, Pointers will be your best bet for implementing one-to-many relationships.

Using Arrays

Arrays are ideal when we know that the number of objects involved in our one-to-many relationship are going to be small. Arrays will also provide some productivity benefit via the includeKey parameter. Supplying the parameter will enable you to obtain all of the "many" objects in the "one-to-many" relationship at the same time that you obtain the "one" object. However, the response time will be slower if the number of objects involved in the relationship turns out to be large.

Suppose in our game, we enabled players to keep track of all the weapons their character has accumulated as they play, and there can only be a dozen or so weapons. In this example, we know that the number of weapons is not going to be very large. We also want to enable the player to specify the order in which the weapons will appear on screen. Arrays are ideal here because the size of the array is going to be small and because we also want to preserve the order the user has set each time they play the game:

Let's start by creating a column on our Parse User object called weaponsList.

Now let's store some Weapon objects in the weaponsList:

// let's say we have four weapons
ParseObject scimitar = ...
ParseObject plasmaRifle = ...
ParseObject grenade = ...
ParseObject bunnyRabbit = ...

// stick the objects in an array
ArrayList<ParseObject> weapons = new ArrayList<ParseObject>();
weapons.add(scimitar);
weapons.add(plasmaRifle);
weapons.add(grenade);
weapons.add(bunnyRabbit);

// store the weapons for the user
ParseUser.getCurrentUser().put("weaponsList", weapons);
// let's say we have four weapons
PFObject *scimitar = ...
PFObject *plasmaRifle = ...
PFObject *grenade = ...
PFObject *bunnyRabbit = ...

// stick the objects in an array
NSArray *weapons = @[scimitar, plasmaRifle, grenade, bunnyRabbit];

// store the weapons for the user
[[PFUser currentUser] setObject:weapons forKey:@weaponsList"];
// let's say we have four weapons
let scimitar = ...
let plasmaRifle = ...
let grenade = ...
let bunnyRabbit = ...

// stick the objects in an array
let weapons = [scimitar, plasmaRifle, grenade, bunnyRabbit]

// store the weapons for the user
let user = PFUser.currentUser()
user["weaponsList"] = weapons
// let's say we have four weapons
$scimitar = ...
$plasmaRifle = ...
$grenade = ...
$bunnyRabbit = ...

// stick the objects in an array
$weapons = [$scimitar, $plasmaRifle, $grenade, $bunnyRabbit];

// store the weapons for the user
$user = ParseUser::getCurrentUser();
$user->set("weaponsList", weapons);
// no c# example
// no js example

Later, if we want to retrieve the Weapon objects, it's just one line of code:

ArrayList<ParseObject> weapons = ParseUser.getCurrentUser().get("weaponsList");
NSArray *weapons = [[PFUser currentUser] objectForKey:@"weaponsList"];
let weapons = PFUser.currentUser()?.objectForKey("weaponsList")
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

Sometimes, we will want to fetch the "many" objects in our one-to-many relationship at the same time as we fetch the "one" object. One trick we could employ is to use the includeKey (or include in Android) parameter whenever we use a Parse Query to also fetch the array of Weapon objects (stored in the weaponsList column) along with the Parse User object:

// set up our query for a User object
ParseQuery<ParseUser> userQuery = ParseUser.getQuery();

// configure any constraints on your query...
// for example, you may want users who are also playing with or against you
// tell the query to fetch all of the Weapon objects along with the user
// get the "many" at the same time that you're getting the "one"
userQuery.include("weaponsList");

// execute the query
userQuery.findInBackground(new FindCallback<ParseUser>() {
  public void done(List<ParseUser> userList, ParseException e) {
    // userList contains all of the User objects, and their associated Weapon objects, too
  }
});
// set up our query for a User object
PFQuery *userQuery = [PFUser query];

// configure any constraints on your query...
// for example, you may want users who are also playing with or against you

// tell the query to fetch all of the Weapon objects along with the user
// get the "many" at the same time that you're getting the "one"
[userQuery includeKey:@"weaponsList"];

// execute the query
[userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    // objects contains all of the User objects, and their associated Weapon objects, too
}];
// set up our query for a User object
let userQuery = PFUser.query();

// configure any constraints on your query...
// for example, you may want users who are also playing with or against you

// tell the query to fetch all of the Weapon objects along with the user
// get the "many" at the same time that you're getting the "one"
userQuery?.includeKey("weaponsList");

// execute the query
userQuery?.findObjectsInBackgroundWithBlock {
    (objects: [AnyObject]?, error: NSError?) -> Void in
    // objects contains all of the User objects, and their associated Weapon objects, too
}
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

You can also get the "one" side of the one-to-many relationship from the "many" side. For example, if we want to find all Parse User objects who also have a given Weapon, we can write a constraint for our query like this:

// add a constraint to query for whenever a specific Weapon is in an array
userQuery.whereEqualTo("weaponsList", scimitar);

// or query using an array of Weapon objects...
userQuery.whereEqualTo("weaponsList", arrayOfWeapons);
// add a constraint to query for whenever a specific Weapon is in an array
[userQuery whereKey:@"weaponsList" equalTo:scimitar];

// or query using an array of Weapon objects...
[userQuery whereKey:@"weaponsList" containedIn:arrayOfWeapons];
// add a constraint to query for whenever a specific Weapon is in an array
userQuery?.whereKey("weaponsList", equalTo: scimitar);

// or query using an array of Weapon objects...
userQuery?.whereKey("weaponsList", containedIn: arrayOfWeapons)
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

Many-to-Many

Now let’s tackle many-to-many relationships. Suppose we had a book reading app and we wanted to model Book objects and Author objects. As we know, a given author can write many books, and a given book can have multiple authors. This is a many-to-many relationship scenario where you have to choose between Arrays, Parse Relations, or creating your own Join Table.

The decision point here is whether you want to attach any metadata to the relationship between two entities. If you don’t, Parse Relation or using Arrays are going to be the easiest alternatives. In general, using arrays will lead to higher performance and require fewer queries. If either side of the many-to-many relationship could lead to an array with more than 100 or so objects, then, for the same reason Pointers were better for one-to-many relationships, Parse Relation or Join Tables will be better alternatives.

On the other hand, if you want to attach metadata to the relationship, then create a separate table (the "Join Table") to house both ends of the relationship. Remember, this is information about the relationship, not about the objects on either side of the relationship. Some examples of metadata you may be interested in, which would necessitate a Join Table approach, include:

Using Parse Relations

Using Parse Relations, we can create a relationship between a Book and a few Author objects. In the Data Browser, you can create a column on the Book object of type relation and name it authors.

After that, we can associate a few authors with this book:

// let’s say we have a few objects representing Author objects
ParseObject authorOne =
ParseObject authorTwo =
ParseObject authorThree =

// now we create a book object
ParseObject book = new ParseObject("Book");

// now let’s associate the authors with the book
// remember, we created a "authors" relation on Book
ParseRelation<ParseObject> relation = book.getRelation("authors");
relation.add(authorOne);
relation.add(authorTwo);
relation.add(authorThree);

// now save the book object
book.saveInBackground();
// let’s say we have a few objects representing Author objects
PFObject *authorOne = …
PFObject *authorTwo = …
PFObject *authorThree = …

// now we create a book object
PFObject *book= [PFObject objectWithClassName:@"Book"];

// now let’s associate the authors with the book
// remember, we created a "authors" relation on Book
PFRelation *relation = [book relationForKey:@"authors"];
[relation addObject:authorOne];
[relation addObject:authorTwo];
[relation addObject:authorThree];

// now save the book object
[book saveInBackground];
// let’s say we have a few objects representing Author objects
let authorOne = ...
let authorTwo = ...
let authorThree = ...

// now we create a book object
let book = PFObject(className: "Book")

// now let’s associate the authors with the book
// remember, we created a "authors" relation on Book
let relation = book.relationForKey("authors")
relation.addObject(authorOne)
relation.addObject(authorTwo)
relation.addObject(authorThree)

// now save the book object
book.saveInBackground()
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

To get the list of authors who wrote a book, create a query:

// suppose we have a book object
ParseObject book = ...

// create a relation based on the authors key
ParseRelation relation = book.getRelation("authors");

// generate a query based on that relation
ParseQuery query = relation.getQuery();

// now execute the query
// suppose we have a book object
PFObject *book = ...

// create a relation based on the authors key
PFRelation *relation = [book relationForKey:@"authors"];

// generate a query based on that relation
PFQuery *query = [relation query];

// now execute the query
// suppose we have a book object
let book = ...

// create a relation based on the authors key
let relation = book.relationForKey("authors")

// generate a query based on that relation
let query = relation.query()

// now execute the query
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

Perhaps you even want to get a list of all the books to which an author contributed. You can create a slightly different kind of query to get the inverse of the relationship:

// suppose we have a author object, for which we want to get all books
ParseObject author = ...

// first we will create a query on the Book object
ParseQuery<ParseObject> query = ParseQuery.getQuery("Book");

// now we will query the authors relation to see if the author object we have
// is contained therein
query.whereEqualTo("authors", author);
// suppose we have a author object, for which we want to get all books
PFObject *author = ...

// first we will create a query on the Book object
PFQuery *query = [PFQuery queryWithClassName:@"Book"];

// now we will query the authors relation to see if the author object
// we have is contained therein
[query whereKey:@"authors" equalTo:author];
// suppose we have a author object, for which we want to get all books
let author = ...

// first we will create a query on the Book object
let query = PFQuery(className: "Book")

// now we will query the authors relation to see if the author object
// we have is contained therein
query?.whereKey("authors", equalTo: author)
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

Using Join Tables

There may be certain cases where we want to know more about a relationship. For example, suppose we were modeling a following/follower relationship between users: a given user can follow another user, much as they would in popular social networks. In our app, we not only want to know if User A is following User B, but we also want to know when User A started following User B. This information could not be contained in a Parse Relation. In order to keep track of this data, you must create a separate table in which the relationship is tracked. This table, which we will call Follow, would have a from column and a to column, each with a pointer to a Parse User. Alongside the relationship, you can also add a column with a Date object named date.

Now, when you want to save the following relationship between two users, create a row in the Follow table, filling in the from, to, and date keys appropriately:

// suppose we have a user we want to follow
ParseUser otherUser = ...

// create an entry in the Follow table
ParseObject follow = new ParseObject("Follow");
follow.put("from", ParseUser.getCurrentUser());
follow.put("to", otherUser);
follow.put("date", Date());
follow.saveInBackground();
// suppose we have a user we want to follow
PFUser *otherUser = ...

// create an entry in the Follow table
PFObject *follow = [PFObject objectWithClassName:@"Follow"];
[follow setObject:[PFUser currentUser]  forKey:@"from"];
[follow setObject:otherUser forKey:@"to"];
[follow setObject:[NSDate date] forKey@"date"];
[follow saveInBackground];
// suppose we have a user we want to follow
let otherUser = ...

// create an entry in the Follow table
let follow = PFObject(className: "Follow")
follow.setObject(PFUser.currentUser()!, forKey: "from")
follow.setObject(otherUser, forKey: "to")
follow.setObject(NSDate(), forKey: "date")
follow.saveInBackground()
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

If we want to find all of the people we are following, we can execute a query on the Follow table:

// set up the query on the Follow table
ParseQuery<ParseObject> query = ParseQuery.getQuery("Follow");
query.whereEqualTo("from", ParseUser.getCurrentUser());

// execute the query
query.findInBackground(newFindCallback<ParseObject>() {
    public void done(List<ParseObject> followList, ParseException e) {

    }
});
// set up the query on the Follow table
PFQuery *query = [PFQuery queryWithClassName:@"Follow"];
[query whereKey:@"from" equalTo:[PFUser currentUser]];

// execute the query
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  for(PFObject *o in objects) {
    // o is an entry in the Follow table
    // to get the user, we get the object with the to key
    PFUser *otherUser = [o objectForKey@"to"];

    // to get the time when we followed this user, get the date key
    PFObject *when = [o objectForKey@"date"];
  }
}];
// set up the query on the Follow table
let query = PFQuery(className: "Follow")
query.whereKey("from", equalTo: PFUser.currentUser()!)

// execute the query
query.findObjectsInBackgroundWithBlock{
    (objects: [AnyObject]?, error: NSError?) -> Void in
    if let objects = objects {
        for o in objects {
            // o is an entry in the Follow table
            // to get the user, we get the object with the to key
            let otherUse = o.objectForKey("to") as? PFUser

            // to get the time when we followed this user, get the date key
            let when = o.objectForKey("date") as? PFObject
        }
    }
}
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

It’s also pretty easy to find all the users that are following the current user by querying on the to key:

// set up the query on the Follow table
ParseQuery<ParseObject> query = ParseQuery.getQuery("Follow");
query.whereEqualTo("to", ParseUser.getCurrentUser());

// execute the query
query.findInBackground(newFindCallback<ParseObject>() {
    public void done(List<ParseObject> followList, ParseException e) {

    }
});
// set up the query on the Follow table
PFQuery *query = [PFQuery queryWithClassName:@"Follow"];
[query whereKey:@"to" equalTo:[PFUser currentUser]];

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  for(PFObject *o in objects) {
     // o is an entry in the Follow table
     // to get the user, we get the object with the from key
    PFUser *otherUser = [o objectForKey@"from"];

    // to get the time the user was followed, get the date key
    PFObject *when = [o objectForKey@"date"];
  }
}];
// set up the query on the Follow table
let query = PFQuery(className: "Follow")
query.whereKey("to", equalTo: PFUser.currentUser()!)

query.findObjectsInBackgroundWithBlock{
    (objects: [AnyObject]?, error: NSError?) -> Void in
    if let objects = objects {
        for o in objects {
            // o is an entry in the Follow table
            // to get the user, we get the object with the to key
            let otherUse = o.objectForKey("to") as? PFUser

            // to get the time when we followed this user, get the date key
            let when = o.objectForKey("date") as? PFObject
        }

    }
}
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

Using an Array

Arrays are used in Many-to-Many relationships in much the same way that they are for One-to-Many relationships. All objects on one side of the relationship will have an Array column containing several objects on the other side of the relationship.

Suppose we have a book reading app with Book and Author objects. The Book object will contain an Array of Author objects (with a key named authors). Arrays are a great fit for this scenario because it's highly unlikely that a book will have more than 100 or so authors. We will put the Array in the Book object for this reason. After all, an author could write more than 100 books.

Here is how we save a relationship between a Book and an Author.

// let's say we have an author
ParseObject author = ...

// and let's also say we have an book
ParseObject book = ...

// add the author to the authors list for the book
book.put("authors", author);
// let's say we have an author
PFObject *author = ...

// and let's also say we have an book
PFObject *book = ...

// add the author to the authors list for the book
[book addObject:author forKey:@"authors"];
// let's say we have an author
let author = ...

// and let's also say we have an book
let book = ...

// add the author to the authors list for the book
book.addObject(author, forKey: "authors")
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

Because the author list is an Array, you should use the includeKey (or include on Android) parameter when fetching a Book so that Parse returns all the authors when it also returns the book:

// set up our query for the Book object
ParseQuery bookQuery = ParseQuery.getQuery("Book");

// configure any constraints on your query...
// tell the query to fetch all of the Author objects along with the Book
bookQuery.include("authors");

// execute the query
bookQuery.findInBackground(newFindCallback<ParseObject>() {
    public void done(List<ParseObject> bookList, ParseException e) {
    }
});
// set up our query for the Book object
PFQuery *bookQuery = [PFQuery queryWithClassName:@"Book"];

// configure any constraints on your query...
// tell the query to fetch all of the Author objects along with the Book
[bookQuery includeKey:@"authors"];

// execute the query
[bookQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    // objects is all of the Book objects, and their associated
    // Author objects, too
}];
// set up our query for the Book object
let bookQuery = PFQuery(className: "Book")

// configure any constraints on your query...
// tell the query to fetch all of the Author objects along with the Book
bookQuery.includeKey("authors")

// execute the query
bookQuery.findObjectsInBackgroundWithBlock{
    (objects: [AnyObject]?, error: NSError?) -> Void in
    // objects is all of the Book objects, and their associated
    // Author objects, too
}
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

At that point, getting all the Author objects in a given Book is a pretty straightforward call:

ArrayList<ParseObject> authorList = book.getList("authors");
NSArray *authorList = [book objectForKey@"authors"];
let authorList = book.objectForKey("authors") as? NSArray
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

Finally, suppose you have an Author and you want to find all the Book objects in which she appears. This is also a pretty straightforward query with an associated constraint:

// set up our query for the Book object
ParseQuery bookQuery = ParseQuery.getQuery("Book");

// configure any constraints on your query...
booKQuery.whereEqualTo("authors", author);

// tell the query to fetch all of the Author objects along with the Book
bookQuery.include("authors");

// execute the query
bookQuery.findInBackground(newFindCallback<ParseObject>() {
    public void done(List<ParseObject> bookList, ParseException e) {

    }
});
// suppose we have an Author object
PFObject *author = ...

// set up our query for the Book object
PFQuery *bookQuery = [PFQuery queryWithClassName:@"Book"];

// configure any constraints on your query...
[bookQuery whereKey:@"authors" equalTo:author];

// tell the query to fetch all of the Author objects along with the Book
[bookQuery includeKey:@"authors"];

// execute the query
[bookQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    // objects is all of the Book objects, and their associated Author objects, too
}];
// suppose we have an Author object
let author = ...

// set up our query for the Book object
let bookQuery = PFQuery(className: "Book")

// configure any constraints on your query...
bookQuery.whereKey("authors", equalTo: author)

// tell the query to fetch all of the Author objects along with the Book
bookQuery.includeKey("authors")

// execute the query
bookQuery.findObjectsInBackgroundWithBlock{
    (objects: [AnyObject]?, error: NSError?) -> Void in
    // objects is all of the Book objects, and their associated Author objects, too
}
// no php example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no c# example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs
// no js example
// Want to contribute to this doc? https://github.com/ParsePlatform/Docs

One-to-One

In Parse, a one-to-one relationship is great for situations where you need to split one object into two objects. These situations should be rare, but two examples include:

Thank you for reading this far. We apologize for the complexity. Modeling relationships in data is a hard subject, in general. But look on the bright side: it's still easier than relationships with people.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Handling Errors

Parse has a few simple patterns for surfacing errors and handling them in your code.

There are two types of errors you may encounter. The first is those dealing with logic errors in the way you're using the SDK. These types of errors result in an NSException being raised. For an example take a look at the following code:

PFUser *user = [PFUser user];
[user signUp];
let user = PFUser()
user.signUp

This will throw an NSInternalInconsistencyException because signUp was called without first setting the required properties (username and password).

The second type of error is one that occurs when interacting with the Parse Cloud over the network. These errors are either related to problems connecting to the cloud or problems performing the requested operation. Let's take a look at another example:

- (void)getMyNote {
    PFQuery *query = [PFQuery queryWithClassName:@"Note"];
    [query getObjectInBackgroundWithId:@"thisObjectIdDoesntExist"
                                target:self
                              selector:@selector(callbackForGet:error:)];
}
func getMyNote() -> Void {
    let query = PFQuery(className: "Note")
    query.getObjectInBackgroundWithId("thisObjectIdDoesntExist", target: self, selector: Selector("callbackForGet:error:"))
}

In the above code, we try to fetch an object with a non-existent objectId. The Parse Cloud will return an error with an error code set in code and message in the error's userInfo. Here's how to handle it properly in your callback:

- (void)callbackForGet:(PFObject *)result error:(NSError *)error {
    if (result) {
        NSLog(@"Everything went fine!");
    } else {
        if ([error code] == kPFErrorObjectNotFound) {
            NSLog(@"Uh oh, we couldn't find the object!");
        } else if (error) {
            NSLog(@"Error: %@", [error userInfo][@"error"]);
        }
    }
}
func callbackForGet(result: PFObject?, error: NSError?) -> Void {
    if let result = result {
        println("Everything went fine!")
    } else {
        if let error = error {
            if error.code == PFErrorCode.ErrorObjectNotFound.rawValue {
                println("Uh oh, we couldn't find the object!")
            } else {
                let errorString = error.userInfo!["error"] as? NSString
                println("Error: \(errorString)")
            }
        }
    }
}

The query might also fail because the device couldn't connect to the Parse Cloud. Here's the same callback but with a bit of extra code to handle that scenario explicitly:

- (void)callbackForGet:(PFObject *)result error:(NSError *)error {
    if (result) {
        NSLog(@"Everything went fine!");
    } else {
        if ([error code] == kPFErrorObjectNotFound) {
            NSLog(@"Uh oh, we couldn't find the object!");
        // Now also check for connection errors:
        } else if ([error code] == kPFErrorConnectionFailed) {
            NSLog(@"Uh oh, we couldn't even connect to the Parse Cloud!");
        } else if (error) {
            NSLog(@"Error: %@", [error userInfo][@"error"]);
        }
    }
}
func callbackForGet(result: PFObject?, error: NSError?) -> Void {
    if let result = result {
        println("Everything went fine!")
    } else {
        if let error = error {
            if error.code == PFErrorCode.ErrorObjectNotFound.rawValue {
                println("Uh oh, we couldn't find the object!")
                // Now also check for connection errors:
            } else if error.code == PFErrorCode.ErrorConnectionFailed.rawValue {
                println("Uh oh, we couldn't even connect to the Parse Cloud!")
            } else {
                let errorString = error.userInfo!["error"] as? NSString
                println("Error: \(errorString)")
            }
        }
    }
}

When the callback expects a NSNumber, its boolValue tells you whether the operation succeeded or not. For example, this is how you might implement the callback for PFObject's saveInBackgroundWithTarget:selector: method:

- (void)callbackForSave:(NSNumber *)result error:(NSError *)error {
    if ([result boolValue]) {
        NSLog(@"Everything went fine!");
    } else {
        if ([error code] == kPFErrorConnectionFailed) {
            NSLog(@"Uh oh, we couldn't even connect to the Parse Cloud!");
        } else if (error) {
            NSLog(@"Error: %@", [error userInfo][@"error"]);
        }
    }
}
func callbackForSave(result: NSNumber?, error: NSError?) -> Void {
    if result?.boolValue == true {
        println("Everything went fine!")
    } else {
        if let error = error {
            if error.code == PFErrorCode.ErrorConnectionFailed.rawValue {
                println("Uh oh, we couldn't even connect to the Parse Cloud!")
            } else {
                let errorString = error.userInfo!["error"] as? NSString
                println("Error: \(errorString)")
            }
        }
    }
}

For synchronous (non-background) methods, error handling is mostly the same except that instead of a NSNumber representing success or failure you'll get an actual BOOL directly.

By default, all connections have a timeout of 10 seconds, so the synchronous methods will not hang indefinitely.

For a list of all possible NSError types, scroll down to Error Codes, or see the PFErrorCode section of the iOS API or OSX API.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Data

Valid Data Types

We've designed the Parse SDKs so that you typically don't need to worry about how data is saved while using the client SDKs. Simply add data to the PFObject, and it'll be saved correctly.

Nevertheless, there are some cases where it's useful to be aware of how data is stored on the Parse platform.

Internally, Parse stores data as JSON, so any datatype that can be converted to JSON can be stored on Parse. The framework can also handle Date and File types. Overall, the following types are allowed for each field in your object:

The type Object simply denotes that each value can be composed of nested objects that are JSON-encodable. Keys including the characters $ or ., along with the key __type key, are reserved for the framework to handle additional types, so don't use those yourself.

We do not recommend storing large pieces of binary data like images or documents in a PFObject. PFObjects should not exceed 128 kilobytes in size. We recommend you use Files to store images, documents, and other types of files. You can do so by instantiating a PFFile object and setting it on a field.

Data Type Lock-in

When a class is initially created, it doesn't have an inherent schema defined. This means that for the first object, it could have any types of fields you want.

However, after a field has been set at least once, that field is locked into the particular type that was saved. For example, if a PFUser object is saved with field name of type String, that field will be restricted to the String type only (our SDK will return an error if you try to save anything else).

One special case is that any field can be set to null, no matter what type it is.

The Data Browser

The Data Browser is the web UI where you can update and create objects in each of your apps. Here, you can see the raw JSON values that are saved that represents each object in your class.

When using the interface, keep in mind the following:

The Data Browser is also a great place to test the Cloud Code validations contained in your Cloud Code functions (such as beforeSave). These are run whenever a value is changed or object is deleted from the Data Browser, just as they would be if the value was changed or deleted from your client code.

Importing Data

You may import data into your Parse app by using CSV or JSON files. To create a new class with data from a CSV or JSON file, go to the Data Browser and click the "Import" button on the left hand column.

The JSON format is an array of objects in our REST format or a JSON object with a results that contains an array of objects. It must adhere to the JSON standard. A file containing regular objects could look like:

{ "results": [
  {
    "score": 1337,
    "playerName": "Sean Plott",
    "cheatMode": false,
    "createdAt": "2012-07-11T20:56:12.347Z",
    "updatedAt": "2012-07-11T20:56:12.347Z",
    "objectId": "fchpZwSuGG"
  }]
}

Objects in either format should contain keys and values that also satisfy the following:

Normally, when objects are saved to Parse, they are automatically assigned a unique identifier through the objectId field, as well as a createdAt field and updatedAt field which represent the time that the object was created and last modified in the Parse Cloud. These fields can be manually set when data is imported from a JSON file. Please keep in mind the following:

In addition to the exposed fields, objects in the Parse User class can also have the bcryptPassword field set. The value of this field is a String that is the bcrypt hashed password + salt in the modular crypt format described in this StackOverflow answer. Most OpenSSL based bcrypt implementations should have built-in methods to produce these strings.

A file containing a PFUser object could look like:

{ "results":
  [{
    "username": "cooldude",
    "createdAt": "1983-09-13T22:42:30.548Z",
    "updatedAt": "2015-09-04T10:12:42.137Z",
    "objectId": "ttttSEpfXm",
    "sessionToken": "dfwfq3dh0zwe5y2sqv514p4ib",
    "bcryptPassword": "$2a$10$ICV5UeEf3lICfnE9W9pN9.O9Ved/ozNo7G83Qbdk5rmyvY8l16MIK"
  }]
}

Note that in CSV the import field types are limited to String, Boolean, and Number.

Exporting your Data

You can request an export of your data at any time from your app's Settings page. The data export runs at a lower priority than production queries, so if your app is still serving queries, production traffic will always be given a higher priority, which may slow down the delivery of your data export.

Export Formats

Each collection will be exported in the same JSON format used by our REST API and delivered in a single zipped file. Since data is stored internally as JSON, this allows us to ensure that the export closely matches how the data is saved to Parse. Other formats such as CSV cannot represent all of the data types supported by Parse without losing information. If you'd like to work with your data in CSV format, you can use any of the JSON-to-CSV converters available widely on the web.

Offline Analysis

For offline analysis of your data, we highly recommend using alternate ways to access your data that do not require extracting the entire collection at once. For example, you can try exporting only the data that has changed since your last export. Here are some ways of achieving this:

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Security

As your app development progresses, you will want to use Parse's security features in order to safeguard data. This document explains the ways in which you can secure your apps.

If your app is compromised, it's not only you as the developer who suffers, but potentially the users of your app as well. Continue reading for our suggestions for sensible defaults and precautions to take before releasing your app into the wild.

Client vs. Server

When an app first connects to Parse, it identifies itself with an Application ID and a Client key (or REST Key, or .NET Key, or JavaScript Key, depending on which platform you're using). These are not secret and by themselves they do not secure an app. These keys are shipped as a part of your app, and anyone can decompile your app or proxy network traffic from their device to find your client key. This exploit is even easier with JavaScript — one can simply "view source" in the browser and immediately find your client key.

This is why Parse has many other security features to help you secure your data. The client key is given out to your users, so anything that can be done with just the client key is doable by the general public, even malicious hackers.

The master key, on the other hand, is definitely a security mechanism. Using the master key allows you to bypass all of your app's security mechanisms, such as class-level permissions and ACLs. Having the master key is like having root access to your app's servers, and you should guard your master key with the same zeal with which you would guard your production machines' root password.

The overall philosophy is to limit the power of your clients (using client keys), and to perform any sensitive actions requiring the master key in Cloud Code. You'll learn how to best wield this power in the section titled Implementing Business Logic in Cloud Code.

A final note: All connections are made with HTTPS and SSL, and Parse will reject all non-HTTPS connections. As a result, you don't need to worry about man-in-the-middle attacks.

Class-Level Permissions

The second level of security is at the schema and data level. Enforcing security measures at this level will restrict how and when client applications can access and create data on Parse. When you first begin developing your Parse application, all of the defaults are set so that you can be a more productive developer. For example:

You can configure any of these permissions to apply to everyone, no one, or to specific users or roles in your app. Roles are groups that contain users or other roles, which you can assign to an object to restrict its use. Any permission granted to a role is also granted to any of its children, whether they are users or other roles, enabling you to create an access hierarchy for your apps. Each of the Parse guides includes a detailed description of employing Roles in your apps.

Once you are confident that you have the right classes and relationships between classes in your app, you should begin to lock it down by doing the following:

Almost every class that you create should have these permissions tweaked to some degree. For classes where every object has the same permissions, class-level settings will be most effective. For example, one common use case entails having a class of static data that can be read by anyone but written by no one.

Restricting class creation

As a start, you can configure your application so that clients cannot create new classes on Parse. This is done from the Settings tab on the Data Browser. Scroll down to the App Permissions section and turn off Allow client class creation. Once enabled, classes may only be created from the Data Browser. This will prevent attackers from filling your database with unlimited, arbitrary new classes.

Configuring Class-Level Permissions

Parse lets you specify what operations are allowed per class. This lets you restrict the ways in which clients can access or modify your classes. To change these settings, go to the Data Browser, select a class, and click the "Security" button.

You can configure the client's ability to perform each of the following operations for the selected class:

For each of the above actions, you can grant permission to all users (which is the default), or lock permissions down to a list of roles and users. For example, a class that should be available to all users would be set to read-only by only enabling get and find. A logging class could be set to write-only by only allowing creates. You could enable moderation of user-generated content by providing update and delete access to a particular set of users or roles.

Object-Level Access Control

Once you've locked down your schema and class-level permissions, it's time to think about how data is accessed by your users. Object-level access control enables one user's data to be kept separate from another's, because sometimes different objects in a class need to be accessible by different people. For example, a user’s private personal data should be accessible only to them.

Parse also supports the notion of anonymous users for those apps that want to store and protect user-specific data without requiring explicit login.

When a user logs into an app, they initiate a session with Parse. Through this session they can add and modify their own data but are prevented from modifying other users' data.

Access Control Lists

The easiest way to control who can access which data is through access control lists, commonly known as ACLs. The idea behind an ACL is that each object has a list of users and roles along with what permissions that user or role has. A user needs read permissions (or must belong to a role that has read permissions) in order to retrieve an object's data, and a user needs write permissions (or must belong to a role that has write permissions) in order to update or delete that object.

Once you have a User, you can start using ACLs. Remember: Users can be created through traditional username/password signup, through a third-party login system like Facebook or Twitter, or even by using Parse's automatic anonymous users functionality. To set an ACL on the current user's data to not be publicly readable, all you have to do is:

PFUser *user = [PFUser currentUser];
user.ACL = [PFACL ACLWithUser:user];
if let user = PFUser.currentUser() {
    user.ACL = PFACL(user: user)
}
ParseUser user = ParseUser.getCurrentUser();
user.setACL(new ParseACL(user));
var user = Parse.User.current();
user.setACL(new Parse.ACL(user));
// no c# example
// no php example

Most apps should do this. If you store any sensitive user data, such as email addresses or phone numbers, you need to set an ACL like this so that the user's private information isn't visible to other users. If an object doesn't have an ACL, it's readable and writeable by everyone. The only exception is the _User class. We never allow users to write each other's data, but they can read it by default. (If you as the developer need to update other _User objects, remember that your master key can provide the power to do this.)

To make it super easy to create user-private ACLs for every object, we have a way to set a default ACL that will be used for every new object you create:

[PFACL setDefaultACL:[PFACL ACL] withAccessForCurrentUser:YES];
PFACL.setDefaultACL(PFACL(), withAccessForCurrentUser: true)
ParseACL.setDefaultACL(new ParseACL(), true);
// no js example
// no c# example
// no php example

If you want the user to have some data that is public and some that is private, it's best to have two separate objects. You can add a pointer to the private data from the public one.

PFObject *privateData = [PFObject objectWithClassName:@"PrivateUserData"];
privateData.ACL = [PFACL ACLWithUser:[PFUser currentUser]];
[privateData setObject:@"555-5309" forKey:@"phoneNumber"];

[[PFUser currentUser] setObject:privateData forKey:@"privateData"];
if let currentUser = PFUser.currentUser() {
    let privateData = PFObject(className: "PrivateUserData")
    privateData.ACL = PFACL(user: currentUser)
    privateData.setObject("555-5309", forKey: "phoneNumber")
    currentUser.setObject(privateData, forKey: "privateData")
}
ParseObject privateData = new ParseObject("PrivateUserData");
privateData.setACL(new ParseACL(ParseUser.getCurrentUser()));
privateData.put("phoneNumber", "555-5309");

ParseUser.getCurrentUser().put("privateData", privateData);
var privateData = Parse.Object.extend("PrivateUserData");
privateData.setACL(new Parse.ACL(Parse.User.current()));
privateData.set("phoneNumber", "555-5309");

Parse.User.current().set("privateData", privateData);
// no c# example
// no php example

Of course, you can set different read and write permissions on an object. For example, this is how you would create an ACL for a public post by a user, where anyone can read it:

PFACL *acl = [PFACL ACL];
[acl setPublicReadAccess:true];
[acl setWriteAccess:true forUser:[PFUser currentUser]];
let acl = PFACL()
acl.setPublicReadAccess(true)
if let currentUser = PFUser.currentUser() {
    acl.setWriteAccess(true, forUser: currentUser)
}
ParseACL acl = new ParseACL();
acl.setPublicReadAccess(true);
acl.setWriteAccess(ParseUser.getCurrentUser(), true);
var acl = new Parse.ACL();
acl.setPublicReadAccess(true);
acl.setWriteAccess(Parse.User.current().id, true);
// no c# example
// no php example

Sometimes it's inconvenient to manage permissions on a per-user basis, and you want to have groups of users who get treated the same (like a set of admins with special powers). Roles are are a special kind of object that let you create a group of users that can all be assigned to the ACL. The best thing about roles is that you can add and remove users from a role without having to update every single object that is restricted to that role. To create an object that is writeable only by admins:

// Assuming you've already created a role called "admins"...
PFACL *acl = [PFACL ACL];
[acl setPublicReadAccess:true];
[acl setWriteAccess:true forRoleWithName:@"admins"];
let acl = PFACL()
acl.setPublicReadAccess(true)
acl.setWriteAccess(true, forRoleWithName: "admins")
// Assuming you've already created a role called "admins"...
ParseACL acl = new ParseACL();
acl.setPublicReadAccess(true);
acl.setRoleWriteAccess("admins", true);
var acl = new Parse.ACL();
acl.setPublicReadAccess(true);
acl.setRoleWriteAccess("admins", true);
// no c# example
// no php example

Of course, this snippet assumes you've already created a role named "admins". This is often reasonable when you have a small set of special roles set up while developing your app. Roles can also be created and updated on the fly — for example, adding new friends to a "friendOf_" role after each connection is made.

All this is just the beginning. Applications can enforce all sorts of complex access patterns through ACLs and class-level permissions. For example:

For the curious, here's the format for an ACL that restricts read and write permissions to the owner (whose objectId is identified by "aSaMpLeUsErId") and enables other users to read the object:

{
    "*": { "read":true },
    "aSaMpLeUsErId": { "read" :true, "write": true }
}

And here's another example of the format of an ACL that uses a Role:

{
    "role:RoleName": { "read": true },
    "aSaMpLeUsErId": { "read": true, "write": true }
}

Pointer Permissions

Pointer permissions are a special type of class-level permission that create a virtual ACL on every object in a class, based on users stored in pointer fields on those objects. For example, given a class with an owner field, setting a read pointer permission on owner will make each object in the class only readable by the user in that object's owner field. For a class with a sender and a reciever field, a read pointer permission on the sender field and a read and write pointer permission on the receiver field will make each object in the class readable by the user in the sender and receiver field, and writable only by the user in the sender field.

Given that objects often already have pointers to the user(s) that should have permissions on the object, pointer permissions provide a simple and fast solution for securing your app using data which is already there, that doesn't require writing any client code or cloud code.

Pointer permissions are like virtual ACLs. They don't appear in the ACL column, buf if you are familiar with how ACLs work, you can think of them like ACLs. In the above example with the sender and receiver, each object will act as if it has an ACL of:

{
    "<SENDER_USER_ID>": {
        "read": true,
        "write": true
    },
    "<RECEIVER_USER_ID>": {
        "read": true
    }
}

Note that this ACL is not actually created on each object. Any existing ACLs will not be modified when you add or remove pointer permissions, and any user attempting to interact with an object can only interact with the object if both the virtual ACL created by the pointer permissions, and the real ACL already on the object allow the interaction. For this reason, it can sometimes be confusing to combine pointer permissions and ACLs, so we recommend using pointer permissions for classes that don't have many ACLs set. Fortunately, it's easy to remove pointer permissions if you later decide to use Cloud Code or ACLs to secure your app.

CLP and ACL interaction

Class-Level Permissions (CLPs) and Access Control Lists (ACLs) are both powerful tools for securing your app, but they don't always interact exactly how you might expect. They actually represent two separate layers of security that each request has to pass through to return the correct information or make the intended change. These layers, one at the class level, and one at the object level, are shown below. A request must pass through BOTH layers of checks in order to be authorized. Note that despite acting similarly to ACLs, Pointer Permissions are a type of class level permission, so a request must pass the pointer permission check in order to pass the CLP check.

As you can see, whether a user is authorized to make a request can become complicated when you use both CLPs and ACLs. Let's look at an example to get a better sense of how CLPs and ACLs can interact. Say we have a Photo class, with an object, photoObject. There are 2 users in our app, user1 and user2. Now lets say we set a Get CLP on the Photo class, disabling public Get, but allowing user1 to perform Get. Now let's also set an ACL on photoObject to allow Read - which includes GET - for only user2.

You may expect this will allow both user1 and user2 to Get photoObject, but because the CLP layer of authentication and the ACL layer are both in effect at all times, it actually makes it so neither user1 nor user2 can Get photoObject. If user1 tries to Get photoObject, it will get through the CLP layer of authentication, but then will be rejected because it does not pass the ACL layer. If user2tries to Get photoObject, it will be rejected at the CLP layer of authentication.

Now lets look at example that uses Pointer Permissions. Say we have a Post class, with an object, myPost. There are 2 users in our app, poster, and viewer. Lets say we add a pointer permission that gives anyone in the Creator field of the Post class read and write access to the object, and for the myPost object, poster is the user in that field. There is also an ACL on the object that gives read access to viewer. You may expect that this will allow poster to read and edit myPost, and viewer to read it, but viewer will be rejected by the Pointer Permission, and poster will be rejected by the ACL, so again, neither user will be able to access the object.

Because of the complex interaction between CLPs, Pointer Permissions, and ACLs, we recommend being careful when using them together. Often it can be useful to use CLPs only to disable all permissions for a certain request type, and then using Pointer Permissions or ACLs for other request types. For example, you may want to disable Delete for a Photo class, but then put a Pointer Permission on Photo so the user who created it can edit it, just not delete it. Because of the especially complex way that Pointer Permissions and ACLs interact, we usually recommend only using one of those two types of security mechanisms.

Security Edge Cases

There are some special classes in Parse that don't follow all of the same security rules as every other class. Not all classes follow Class-Level Permissions (CLPs) or Access Control Lists (ACLs) exactly how they are defined, and here those exceptions are documented. Here "normal behavior" refers to CLPs and ACLs working normally, while any other special behaviors are described in the footnotes.

_User _Installation
Get normal behaviour [1, 2, 3] ignores CLP, but not ACL
Find normal behavior [3] master key only [6]
Create normal behavior [4] ignores CLP
Update normal behavior [5] ignores CLP, but not ACL [7]
Delete normal behavior [5] master key only [7]
Add Field normal behavior normal behavior
  1. Logging in, or /1/login in the REST API, does not respect the Get CLP on the user class. Login works just based on username and password, and cannot be disabled using CLPs.

  2. Retrieving the current user, or becoming a User based on a session token, which are both /1/users/me in the REST API, do not respect the Get CLP on the user class.

  3. Read ACLs do not apply to the logged in user. For example, if all users have ACLs with Read disabled, then doing a find query over users will still return the logged in user. However, if the Find CLP is disabled, then trying to perform a find on users will still return an error.

  4. Create CLPs also apply to signing up. So disabling Create CLPs on the user class also disables people from signing up without the master key.

  5. Users can only Update and Delete themselves. Public CLPs for Update and Delete may still apply. For example, if you disable public Update for the user class, then users cannot edit themselves. But no matter what the write ACL on a user is, that user can still Update or Delete itself, and no other user can Update or Delete that user. As always, however, using the master key allows users to update other users, independent of CLPs or ACLs.

  6. Get requests on installations follow ACLs normally. Find requests, however, return the installation making the request, and only that installation, no matter what ACL is defined on that installation.

  7. Update requests on installations do adhere to the ACL defined on the installation, but Delete requests are master-key-only. For more information about how installations work, check out the installations section of the REST guide.

Data Integrity in Cloud Code

For most apps, care around keys, class-level permissions, and object-level ACLs are all you need to keep your app and your users' data safe. Sometimes, though, you'll run into an edge case where they aren't quite enough. For everything else, there's Cloud Code.

Cloud Code allows you to upload JavaScript to Parse's servers, where we will run it for you. Unlike client code running on users' devices that may have been tampered with, Cloud Code is guaranteed to be the code that you've written, so it can be trusted with more responsibility.

One particularly common use case for Cloud Code is preventing invalid data from being stored. For this sort of situation, it's particularly important that a malicious client not be able to bypass the validation logic.

To create validation functions, Cloud Code allows you to implement a beforeSave trigger for your class. These triggers are run whenever an object is saved, and allow you to modify the object or completely reject a save. For example, this is how you create a Cloud Code beforeSave trigger to make sure every user has an email address set:

Parse.Cloud.beforeSave(Parse.User, function(request, response) {
  var user = request.object;
  if (!user.get("email")) {
    response.error("Every user must have an email address.");
  } else {
    response.success();
  }
});

Our Cloud Code guide provides instructions on how to upload this trigger to our servers.

Validations can lock down your app so that only certain values are acceptable. You can also use afterSave validations to normalize your data (e.g. formatting all phone numbers or currency identically). You get to retain most of the productivity benefits of accessing Parse data directly from your client applications, but you can also enforce certain invariants for your data on the fly.

Common scenarios that warrant validation include:

Implementing Business Logic in Cloud Code

While validation often makes sense in Cloud Code, there are likely certain actions that are particularly sensitive, and should be as carefully guarded as possible. In these cases, you can remove permissions or the logic from clients entirely and instead funnel all such operations to Cloud Code functions.

When a Cloud Code function is called, it can invoke the useMasterKey function to gain the ability to modify user data. With the master key, your Cloud Code function can override any ACLs and write data. This means that it'll bypass all the security mechanisms you've put in place in the previous sections.

Say you want to allow a user to "like" a Post object without giving them full write permissions on the object. You can do this by having the client call a Cloud Code function instead of modifying the Post itself:

The master key should be used carefully. When invoked, the master key is in effect for the duration of the Cloud Code function in which it is called:

Parse.Cloud.define("like", function(request, response) {
  Parse.Cloud.useMasterKey();
  // Everything after this point will bypass ACLs and other security
  // even if I do things besides just updating a Post object.
});

A more prudent way to use the master key would be to pass it as a parameter on a per-function basis. For example, instead of the above, set useMasterKey to true in each individual API function:

Parse.Cloud.define("like", function(request, response) {
  var post = new Parse.Object("Post");
  post.id = request.params.postId;
  post.increment("likes");
  post.save(null, { useMasterKey: true }).then(function() {
    // If I choose to do something else here, it won't be using
    // the master key and I'll be subject to ordinary security measures.
    response.success();
  }, function(error) {
    response.error(error);
  });
});

One very common use case for Cloud Code is sending push notifications to particular users. In general, clients can't be trusted to send push notifications directly, because they could modify the alert text, or push to people they shouldn't be able to. Your app's settings will allow you to set whether "client push" is enabled or not; we recommend that you make sure it's disabled. Instead, you should write Cloud Code functions that validate the data to be pushed and sender before sending a push.

Parse Security Summary

Parse provides a number of ways for you to secure data in your app. As you build your app and evaluate the kinds of data you will be storing, you can make the decision about which implementation to choose.

It is worth repeating that that the Parse User object is readable by all other users by default. You will want to set the ACL on your User object accordingly if you wish to prevent data contained in the User object (for example, the user's email address) from being visible by other users.

Most classes in your app will fall into one of a couple of easy-to-secure categories. For fully public data, you can use class-level permissions to lock down the table to put publicly readable and writeable by no one. For fully private data, you can use ACLs to make sure that only the user who owns the data can read it. But occasionally, you'll run into situations where you don't want data that’s fully public or fully private. For example, you may have a social app, where you have data for a user that should be readable only to friends whom they’ve approved. For this you'll need to a combination of the techniques discussed in this guide to enable exactly the sharing rules you desire.

We hope that you'll use these tools to do everything you can to keep your app's data and your users' data secure. Together, we can make the web a safer place.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Local Datastore

The Parse iOS/OSX SDK provides a local datastore which can be used to store and retrieve PFObjects, even when the network is unavailable. To enable this functionality, add libsqlite3.dylib and call [Parse enableLocalDatastore] before your call to setApplicationId:clientKey:.

@implementation AppDelegate

- (void)application:(UIApplication *)application didFinishLaunchWithOptions:(NSDictionary *)options {
  [Parse enableLocalDatastore];
  [Parse setApplicationId:@"parseAppId" clientKey:@"parseClientKey"];
}

@end
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    Parse.enableLocalDatastore()
    Parse.setApplicationId("parseAppId", clientKey: "parseClientKey")
  }
}

There are a couple of side effects of enabling the local datastore that you should be aware of. When enabled, there will only be one instance of any given PFObject. For example, imagine you have an instance of the "GameScore" class with an objectId of "xWMyZ4YEGZ", and then you issue a PFQuery for all instances of "GameScore" with that objectId. The result will be the same instance of the object you already have in memory.

Another side effect is that the current user and current installation will be stored in the local datastore, so you can persist unsaved changes to these objects between runs of your app using the methods below.

Calling the saveEventually method on a PFObject will cause the object to be pinned in the local datastore until the save completes. So now, if you change the current PFUser and call [[PFUser currentUser] saveEventually], your app will always see the changes that you have made.

Pinning

You can store a PFObject in the local datastore by pinning it. Pinning a PFObject is recursive, just like saving, so any objects that are pointed to by the one you are pinning will also be pinned. When an object is pinned, every time you update it by fetching or saving new data, the copy in the local datastore will be updated automatically. You don't need to worry about it at all.

PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"];
gameScore[@"score"] = @1337;
gameScore[@"playerName"] = @"Sean Plott";
gameScore[@"cheatMode"] = @NO;
[gameScore pinInBackground];
let gameScore = PFObject(className:"GameScore")
gameScore["score"] = 1337
gameScore["playerName"] = "Sean Plott"
gameScore["cheatMode"] = false
gameScore.pinInBackground()

If you have multiple objects, you can pin them all at once with the pinAllInBackground convenience method.

[PFObject pinAllInBackground:listOfObjects];
PFObject.pinAllInBackground(listOfObjects)

Retrieving Objects

Storing objects is great, but it's only useful if you can then get the objects back out later. Retrieving an object from the local datastore works just like retrieving one over the network. The only difference is calling the fromLocalDatastore method to tell the PFQuery where to look for its results.

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query fromLocalDatastore];
[[query getObjectInBackgroundWithId:@"xWMyZ4YE"] continueWithBlock:^id(BFTask *task) {
  if (task.error) {
    // Something went wrong.
    return task;
  }

  // task.result will be your game score
  return task;
}];
let query = PFQuery(className: "GameScore")
query.fromLocalDatastore()
query.getObjectInBackgroundWithId("xWMyZ4YE").continueWithBlock {
    (task: BFTask!) -> AnyObject in
    if let error = task.error {
        // Something went wrong.
        return task;
    }

    // task.result will be your game score
    return task;
}

Querying

Often, you'll want to find a whole list of objects that match certain criteria, instead of getting a single object by id. To do that, you can use a PFQuery. Any PFQuery can be used with the local datastore just as with the network. The results will include any object you have pinned that matches the query. Any unsaved changes you have made to the object will be considered when evaluating the query. So you can find a local object that matches, even if it was never returned from the server for this particular query.

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query fromLocalDatastore];
[query whereKey:@"playerName" equalTo:@"Joe Bob"];
[[query findObjectsInBackground] continueWithBlock:^id(BFTask *task) {
  if (task.error) {
    NSLog(@"Error: %@", task.error);
    return task;
  }

  NSLog(@"Retrieved %d", task.result.count);
  return task;
}];
let query = PFQuery(className: "GameScore")
query.fromLocalDatastore()
query.whereKey("playerName", equalTo: "Joe Bob")
query.findObjectsInBackground().continueWithBlock {
    (task: BFTask!) -> AnyObject in
    if let error = task.error {
        println("Error: \(error)")
        return task
    }

    println("Retrieved \(task.result.count)")
    return task
}

Security

The same security model that applies to objects in Parse applies to objects in the Local Datastore. Read-write permissions are defined by PFACLs and a user cannot access or modify anything they don't have permission to.

The only difference is that you won't be able to access any data protected by Role based ACLs due to the fact that the Roles are stored on the server. To access this data protected by Role based ACLs, you will need to ignore ACLs when executing a Local Datastore query:

PFQuery *query = [[[PFQuery queryWithClassName:@"Note"]
                   fromLocalDatastore]
                  ignoreACLs];
let query = PFQuery(className: "Note")
    .fromLocalDatastore
    .ignoreACLs

Unpinning

When you are done with an object and no longer need it to be in the local datastore, you can simply unpin it. This will free up disk space on the device and keep your queries on the local datastore running quickly.

[gameScore unpinInBackground];
gameScore.unpinInBackground()

There's also a method to unpin several objects at once.

[PFObject unpinAllInBackground:listOfObjects];
PFObject.unpinAllInBackground(listOfObjects)

Pinning with Labels

Manually pinning and unpinning each object individual is a bit like using malloc and free. It is a very powerful tool, but it can be difficult to manage what objects get stored in complex scenarios. For example, imagine you are making a game with separate high score lists for global high scores and your friends' high scores. If one of your friends happens to have a globally high score, you need to make sure you don't unpin them completely when you remove them from one of the cached queries. To make these scenarios easier, you can also pin with a label. Labels indicate a group of objects that should be stored together.

// Add several objects with a label.
[PFObject pinAllInBackground:someGameScores withName:@"MyScores"];

// Add another object with the same label.
[anotherGameScore pinInBackgroundWithName:@"MyScores"];
// Add several objects with a label.
PFObject.pinAllInBackground(objects:someGameScores withName:"MyScores")

// Add another object with the same label.
anotherGameScore.pinInBackgroundWithName("MyScores")

To unpin all of the objects with the same label at the same time, you can pass a label to the unpin methods. This saves you from having to manually track which objects are in each group you care about.

[PFObject unpinAllObjectsInBackgroundWithName:@"MyScores"];
PFObject.unpinAllObjectsInBackgroundWithName("MyScores")

Any object will stay in the datastore as long as it is pinned with any label. In other words, if you pin an object with two different labels, and then unpin it with one label, the object will stay in the datastore until you also unpin it with the other label.

Caching Query Results

Pinning with labels makes it easy to cache the results of queries. You can use one label to pin the results of each different query. To get new results from the network, just do a query and update the pinned objects.

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query orderByDescending:@"score"];

// Query for new results from the network
[[query findObjectsInBackground] continueWithSuccessBlock:^id(BFTask *task) {
  return [[PFObject unpinAllObjectsInBackgroundWithName:@"HighScores"] continueWithSuccessBlock:^id(BFTask *ignored) {
    // Cache the new results.
    NSArray *scores = task.result;
    return [PFObject pinAllInBackground:scores withName:@"HighScores"];
  }];
}];
let query = PFQuery(className:"GameScore")
query.orderByDescending("score")

// Query for new results from the network
query.findObjectsInBackground().continueWithSuccessBlock({
    (task: BFTask!) -> AnyObject! in

    return PFObject.unpinAllObjectsInBackgroundWithName("HighScores").continueWithSuccessBlock({
        (ignored: BFTask!) -> AnyObject! in

        // Cache new results
        let scores = task.result as? NSArray
        return PFObject.pinAllInBackground(scores as [AnyObject], withName: "HighScores")
    })
})

When you want to get the cached results for the query, you can then run the same query against the local datastore.

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query fromLocalDatastore];
[query orderByDescending:@"score"];

[[query findObjectsInBackground] continueWithBlock:^id(BFTask *task) {
  if (task.error) {
    // Something went wrong.
    return task;
  }

  // Yay! Cached scores!
  return task;
}];
let query = PFQuery(className:"GameScore")
query.fromLocalDatastore()
query.orderByDescending("score")

query.findObjectsInBackground().continueWithBlock({
  (task: BFTask!) -> AnyObject! in
    if task.error != nil {
        // There was an error.
        return task
    }

    // Yay! Cached scores!
    return task
})

Syncing Local Changes

Once you've saved some changes locally, there are a few different ways you can save those changes back to Parse over the network. The easiest way to do this is with saveEventually. When you call saveEventually on a PFObject, it will be pinned until it can be saved. The SDK will make sure to save the object the next time the network is available.

[gameScore saveEventually];
gameScore.saveEventually()

If you'd like to have more control over the way objects are synced, you can keep them in the local datastore until you are ready to save them yourself using saveInBackground. To manage the set of objects that need to be saved, you can again use a label. The fromPinWithName: method on PFQuery makes it easy to fetch just the objects you care about.

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query fromPinWithName:@"MyChanges"];
[[query findObjectsInBackground] continueWithBlock:^id(BFTask *task) {
  NSArray *scores = task.result;
  for (PFObject *score in scores) {
    [[score saveInBackground] continueWithSuccessBlock:^id(BFTask *task) {
      return [score unpinInBackground];
    }];
  }
  return task;
}];
let query = PFQuery(className:"GameScore")
query.fromPinWithName("MyChanges")
query.findObjectsInBackground().continueWithBlock({
  (task: BFTask!) -> AnyObject! in
  let scores = task.result as NSArray
  for score in scores {
    score.saveInBackground().continueWithSuccessBlock({
      (task: BFTask!) -> AnyObject! in
      return score.unpinInBackground()
    })
  }
  return task
})
Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Extensions and WatchKit

Local data sharing in Parse SDKs allows you do share persistent local data between your main application and extensions that it contains, including Apple Watch apps, Keyboard, Share/Today/Photo/Action extensions and Document Providers.

Shared Local Data

All local data that is persistent can be shared between apps and multiple extensions:

We do not recommend storing large pieces of data inside these persistent objects, both with and without data sharing enabled, as it might impact the performance of how fast this data is saved and loaded.

Furthermore, if you are using Local Datastore with data sharing - we recommend that you divide your objects amongst multiple pins, as querying and persisting data in a smaller pin is usually faster.

Enable Data Sharing

To share your local data between app and extensions you need to do the following:

// Enable data sharing in main app.
[Parse enableDataSharingWithApplicationGroupIdentifier:@"group.com.parse.parseuidemo"];
// Setup Parse
[Parse setApplicationId:@"<ParseAppId>" clientKey:@"<ClientKey>"];
// Enable data sharing in main app.
Parse.enableDataSharingWithApplicationGroupIdentifier("group.com.parse.parseuidemo")
// Setup Parse
Parse.setApplicationId("<ParseAppId>", clientKey: "<ClientKey>")
// Enable data sharing in app extensions.
[Parse enableDataSharingWithApplicationGroupIdentifier:@"group.com.parse.parseuidemo"
                                 containingApplication:@"com.parse.parseuidemo"];
// Setup Parse
[Parse setApplicationId:@"<ParseAppId>" clientKey:@"<ClientKey>"];
// Enable data sharing in main app.
Parse.enableDataSharingWithApplicationGroupIdentifier("group.com.parse.parseuidemo",
                            containingApplicaiton: "com.parse.parseuidemo")
// Setup Parse
Parse.setApplicationId("<ParseAppId>", clientKey: "<ClientKey>")

As you might have noticed - there are few pieces of information that need to be in sync for this to work and be enabled:

This process is required to be completed for both your main application and any extension, including WatchKit apps.

After all these steps are done, you are all set and all data will be shared between your app and any app extension that the app contains.

If you have an existing app using the Parse SDK, when users upgrade to your latest app version (with data sharing enabled), the Parse SDK will automatically move the main app's local persistent data (Local Datastore, current PFUser, current PFInstallation, etc) from the app's sandbox container to the shared container. This migration is irreversible; if you later release another app version with data sharing disabled, we will not move the shared container's data back into the main app's sandbox container. For more about the app/extension shared container, please see Apple's documentation.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Push Notifications

Push Notifications are a great way to keep your users engaged and informed about your app. You can reach your entire user base quickly and effectively. This guide will help you through the setup process and the general usage of Parse to send push notifications.

If you haven't installed the SDK yet, please head over to the Push QuickStart to get our SDK up and running.

Setting Up Push

If you want to start using push, start by completing the Push Tutorial to learn how to configure your app. Come back to this guide afterwards to learn more about the push features offered by Parse.

Installations

Every Parse application installed on a device registered for push notifications has an associated PFInstallation object. The PFInstallation object is where you store all the data needed to target push notifications. For example, in a baseball app, you could store the teams a user is interested in to send updates about their performance. Saving the PFInstallation object is also required for tracking push-related app open events.

In iOS or OS X, Installation objects are available through the PFInstallation class, a subclass of PFObject. It uses the same API for storing and retrieving data. To access the current Installation object from your app, use the [PFInstallation currentInstallation] method. The first time you save a PFInstallation, Parse will add it to your Installation class, and it will be available for targeting push notifications as long as its deviceToken field is set.

First, make your app register for remote notifications by adding the following in your application:didFinishLaunchingWithOptions: method (if you haven't already):

UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes  categories:nil];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
let userNotificationTypes = (UIUserNotificationType.Alert |  UIUserNotificationType.Badge |  UIUserNotificationType.Sound);

let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()

We will then update our PFInstallation with the deviceToken once the device is registered for push notifications:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  // Store the deviceToken in the current Installation and save it to Parse
  PFInstallation *currentInstallation = [PFInstallation currentInstallation];
  [currentInstallation setDeviceTokenFromData:deviceToken];
  [currentInstallation saveInBackground];
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
  // Store the deviceToken in the current Installation and save it to Parse
  let installation = PFInstallation.currentInstallation()
  installation.setDeviceTokenFromData(deviceToken)
  installation.saveInBackground()
}

While it is possible to modify a PFInstallation just like you would a PFObject, there are several special fields that help manage and target devices.

Sending Pushes

There are two ways to send push notifications using Parse: channels and advanced targeting. Channels offer a simple and easy to use model for sending pushes, while advanced targeting offers a more powerful and flexible model. Both are fully compatible with each other and will be covered in this section.

Sending notifications is often done from the Parse.com push console, the REST API or from Cloud Code. However, push notifications can also be triggered by the existing client SDKs. If you decide to send notifications from the client SDKs, you will need to set Client Push Enabled in the Push Notifications settings of your Parse app.

However, be sure you understand that enabling Client Push can lead to a security vulnerability in your app, as outlined on our blog. We recommend that you enable Client Push for testing purposes only, and move your push notification logic into Cloud Code when your app is ready to go into production.

You can view your past push notifications on the Parse.com push console for up to 30 days after creating your push. For pushes scheduled in the future, you can delete the push on the push console as long as no sends have happened yet. After you send the push, the push console shows push analytics graphs.

Using Channels

The simplest way to start sending notifications is using channels. This allows you to use a publisher-subscriber model for sending pushes. Devices start by subscribing to one or more channels, and notifications can later be sent to these subscribers. The channels subscribed to by a given Installation are stored in the channels field of the Installation object.

Subscribing to Channels

A channel is identified by a string that starts with a letter and consists of alphanumeric characters, underscores, and dashes. It doesn't need to be explicitly created before it can be used and each Installation can subscribe to any number of channels at a time.

Adding a channel subscription can be done using the addUniqueObject: method in PFObject. For example, in a baseball score app, we could do:

// When users indicate they are Giants fans, we subscribe them to that channel.
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation addUniqueObject:@"Giants" forKey:@"channels"];
[currentInstallation saveInBackground];
// When users indicate they are Giants fans, we subscribe them to that channel.
let currentInstallation = PFInstallation.currentInstallation()
currentInstallation.addUniqueObject("Giants" forKey: "channels")
currentInstallation.saveInBackground()

Once subscribed to the "Giants" channel, your Installation object should have an updated channels field.

Unsubscribing from a channel is just as easy:

// When users indicate they are no longer Giants fans, we unsubscribe them.
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
[currentInstallation removeObject:@"Giants" forKey:@"channels"];
[currentInstallation saveInBackground];
// When users indicate they are Giants fans, we subscribe them to that channel.
let currentInstallation = PFInstallation.currentInstallation()
currentInstallation.removeObject("Giants" forKey: "channels")
currentInstallation.saveInBackground()

The set of subscribed channels is cached in the currentInstallation object:

NSArray *subscribedChannels = [PFInstallation currentInstallation].channels;
let subscribedChannels = PFInstallation.currentInstallation().channels

If you plan on changing your channels from Cloud Code or the data browser, note that you'll need to call some form of fetch prior to this line in order to get the most recent channels.

Sending Pushes to Channels

In the iOS/OS X SDK, the following code can be used to alert all subscribers of the "Giants" channel that their favorite team just scored. This will display a notification center alert to iOS/OS X users and a system tray notification to Android users.

// Send a notification to all devices subscribed to the "Giants" channel.
PFPush *push = [[PFPush alloc] init];
[push setChannel:@"Giants"];
[push setMessage:@"The Giants just scored!"];
[push sendPushInBackground];
// Send a notification to all devices subscribed to the "Giants" channel.
let push = PFPush()
push.setChannel("Giants")
push.setMessage("The Giants just scored!")
push.sendPushInBackground()

If you want to target multiple channels with a single push notification, you can use an NSArray of channels.

NSArray *channels = [NSArray arrayWithObjects:@"Giants", @"Mets", nil];
PFPush *push = [[PFPush alloc] init];

// Be sure to use the plural 'setChannels'.
[push setChannels:channels];
[push setMessage:@"The Giants won against the Mets 2-3."];
[push sendPushInBackground];
let channels = [ "Giants", "Mets" ];
let push = PFPush()

// Be sure to use the plural 'setChannels'.
push.setChannels(channels)
push.setMessage("The Giants won against the Mets 2-3.")
push.sendPushInBackground()

Using Advanced Targeting

While channels are great for many applications, sometimes you need more precision when targeting the recipients of your pushes. Parse allows you to write a query for any subset of your Installation objects using the querying API and to send them a push.

Since PFInstallation is a subclass of PFObject, you can save any data you want and even create relationships between Installation objects and your other objects. This allows you to send pushes to a very customized and dynamic segment of your user base.

Saving Installation Data

Storing data on an Installation object is just as easy as storing any other data on Parse. In our Baseball app, we could allow users to get pushes about game results, scores and injury reports.

// Store app language and version
PFInstallation *installation = [PFInstallation currentInstallation];
[installation setObject:@YES forKey:@"scores"];
[installation setObject:@YES forKey:@"gameResults"];
[installation setObject:@YES forKey:@"injuryReports"];
[installation saveInBackground];
// Store app language and version
let installation = PFInstallation.currentInstallation()
installation["scores"] = true
installation["gameResults"] = true
installation["injuryReports"] = true
installation.saveInBackground()

You can even create relationships between your Installation objects and other classes saved on Parse. To associate a PFInstallation with a particular user, for example, you can simply store the current user on the PFInstallation.

// Associate the device with a user
PFInstallation *installation = [PFInstallation currentInstallation];
installation[@"user"] = [PFUser currentUser];
[installation saveInBackground];
// Associate the device with a user
let installation = PFInstallation.currentInstallation()
installation["user"] = PFUser.currentUser()
installation.saveInBackground()

Sending Pushes to Queries

Once you have your data stored on your Installation objects, you can use a PFQuery to target a subset of these devices. Installation queries work just like any other Parse query, but we use the special static method [PFInstallation query] to create it. We set this query on our PFPush object, before sending the notification.

// Create our Installation query
PFQuery *pushQuery = [PFInstallation query];
[pushQuery whereKey:@"injuryReports" equalTo:YES];

// Send push notification to query
PFPush *push = [[PFPush alloc] init];
[push setQuery:pushQuery]; // Set our Installation query
[push setMessage:@"Willie Hayes injured by own pop fly."];
[push sendPushInBackground];
// Create our Installation query
let pushQuery = PFInstallation.query()
pushQuery.whereKey("injuryReports", equalTo: true)

// Send push notification to query
let push = PFPush()
push.setQuery(pushQuery) // Set our Installation query
push.setMessage("Willie Hayes injured by own pop fly.")
push.sendPushInBackground()

We can even use channels with our query. To send a push to all subscribers of the "Giants" channel but filtered by those who want score update, we can do the following:

// Create our Installation query
PFQuery *pushQuery = [PFInstallation query];
[pushQuery whereKey:@"channels" equalTo:@"Giants"]; // Set channel
[pushQuery whereKey:@"scores" equalTo:YES];

// Send push notification to query
PFPush *push = [[PFPush alloc] init];
[push setQuery:pushQuery];
[push setMessage:@"Giants scored against the A's! It's now 2-2."];
[push sendPushInBackground];
// Create our Installation query
let pushQuery = PFInstallation.query()
pushQuery.whereKey("channels", equalTo:"Giants") // Set channel
pushQuery.whereKey("scores", equalTo:true)

// Send push notification to query
let push = PFPush()
push.setQuery(pushQuery) // Set our Installation query
push.setMessage("Giants scored against the A's! It's now 2-2.")
push.sendPushInBackground()

If we store relationships to other objects in our Installation class, we can also use those in our query. For example, we could send a push notification to all users near a given location like this.

// Find users near a given location
PFQuery *userQuery = [PFUser query];
[userQuery whereKey:@"location"    nearGeoPoint:stadiumLocation withinMiles:@1]

// Find devices associated with these users
PFQuery *pushQuery = [PFInstallation query];
[pushQuery whereKey:@"user" matchesQuery:userQuery];

// Send push notification to query
PFPush *push = [[PFPush alloc] init];
[push setQuery:pushQuery]; // Set our Installation query
[push setMessage:@"Free hotdogs at the Parse concession stand!"];
[push sendPushInBackground];
// Find users near a given location
let userQuery = PFUser.query()
userQuery.whereKey("location", nearGeoPoint: stadiumLocation, withinMiles: 1)

// Find devices associated with these users
let pushQuery = PFInstallation.query()
pushQuery.whereKey("user", matchesQuery: userQuery)

// Send push notification to query
let push = PFPush()
push.setQuery(pushQuery) // Set our Installation query
push.setMessage("Free hotdogs at the Parse concession stand!")
push.sendPushInBackground()

Sending Options

Push notifications can do more than just send a message. On iOS/OS X, pushes can also include the sound to be played, the badge number to display as well as any custom data you wish to send. An expiration date can also be set for the notification in case it is time sensitive.

Customizing your Notifications

If you want to send more than just a message, you will need to use an NSDictionary to package all of the data. There are some reserved fields that have a special meaning.

For example, to send a notification that increases the current badge number by 1 and plays a custom sound, you can do the following:

NSDictionary *data = @{
  @"alert" : @"The Mets scored! The game is now tied 1-1!",
  @"badge" : @"Increment",
  @"sounds" : @"cheering.caf"
};
PFPush *push = [[PFPush alloc] init];
[push setChannels:@[ @"Mets" ]];
[push setData:data];
[push sendPushInBackground];
let data = [
  "alert" : "The Mets scored! The game is now tied 1-1!",
  "badge" : "Increment",
  "sounds" : "cheering.caf"
]
let push = PFPush()
push.setChannels(["Mets"])
push.setData(data)
push.sendPushInBackground()

It is also possible to specify your own data in this dictionary. As we'll see in the Receiving Notifications section, you will have access to this data only when the user opens your app via the notification. This can be useful for displaying a different view controller when a user opens certain notifications.

NSDictionary *data = @{
  @"alert" : @"Ricky Vaughn was injured in last night's game!",
  @"name" : @"Vaughn",
  @"newsItem" : @"Man bites dog"
};
PFPush *push = [[PFPush alloc] init];
[push setQuery:injuryReportsQuery];
[push setChannel:@"Indians"];
[push setData:data];
[push sendPushInBackground];
let data = [
  "alert" : "Ricky Vaughn was injured in last night's game!",
  "name" : "Vaughn",
  "newsItem" : "Man bites dog"
]
let push = PFPush()
push.setQuery(injuryReportsdata)
push.setChannel("Indians")
push.setData(data)
push.sendPushInBackground()

Whether your push notifications increment the app's badge or set it to a specific value, your app will eventually need to clear its badge. This is covered in Clearing the Badge.

Setting an Expiration Date

When a user's device is turned off or not connected to the internet, push notifications cannot be delivered. If you have a time sensitive notification that is not worth delivering late, you can set an expiration date. This avoids needlessly alerting users of information that may no longer be relevant.

There are two methods provided by the PFPush class to allow setting an expiration date for your notification. The first is expireAtDate: which simply takes an NSDate specifying when Parse should stop trying to send the notification.

// Create date object for tomorrow
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2015];
[comps setMonth:8];
[comps setDay:14];
NSCalendar *gregorian =
  [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];

// Send push notification with expiration date
PFPush *push = [[PFPush alloc] init];
[push expireAtDate:date];
[push setQuery:everyoneQuery];
[push setMessage:@"Season tickets on sale until August 8th!"];
[push sendPushInBackground];
// Create date object for tomorrow
let comps = NSDateComponents()
comps.year = 2015
comps.month = 8
comps.day = 14
let gregorian = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let date = gregorian!.dateFromComponents(comps);

// Send push notification with expiration
let push = PFPush()
push.expireAtDate(date)
push.setQuery(everyoneQuery)
push.setMessage("Season tickets on sale until August 8th!")
push.sendPushInBackground()

There is however a caveat with this method. Since device clocks are not guaranteed to be accurate, you may end up with inaccurate results. For this reason, the PFPush class also provides the expireAfterTimeInterval: method which accepts an NSTimeInterval object. The notification will expire after the specified interval has elapsed.

// Create time interval
NSTimeInterval interval = 60*60*24*7; // 1 week

// Send push notification with expiration interval
PFPush *push = [[PFPush alloc] init];
[push expireAfterTimeInterval:interval];
[push setQuery:everyoneQuery];
[push setMessage:@"Season tickets on sale until next week!"];
[push sendPushInBackground];
// Create time interval
let interval = 60*60*24*7; // 1 week

// Send push notification with expiration interval

let push = PFPush()
push.expireAfterTimeInterval(interval)
push.setQuery(everyoneQuery)
push.setMessage("Season tickets on sale until next week!")
push.sendPushInBackground()

Targeting by Platform

If you build a cross platform app, it is possible you may only want to target devices of a particular operating system. Advanced Targeting allow you to filter which of these devices are targeted.

The following example would send a different notification to Android, iOS, and Windows users.

PFQuery *query = [PFInstallation query];
[query whereKey:@"channels" equalTo:@"suitcaseOwners"];

// Notification for Android users
[query whereKey:@"deviceType" equalTo:@"android"];
PFPush *androidPush = [[PFPush alloc] init];
[androidPush setMessage:@"Your suitcase has been filled with tiny robots!"];
[androidPush setQuery:query];
[androidPush sendPushInBackground];

// Notification for iOS users
[query whereKey:@"deviceType" equalTo:@"ios"];
PFPush *iOSPush = [[PFPush alloc] init];
[iOSPush setMessage:@"Your suitcase has been filled with tiny apples!"];
[iOSPush setChannel:@"suitcaseOwners"];
[iOSPush setQuery:query];
[iOSPush sendPushInBackground];

// Notification for Windows 8 users
[query whereKey:@"deviceType" equalTo:@"winrt"];
PFPush *winPush = [[PFPush alloc] init];
[winPush setMessage:@"Your suitcase has been filled with tiny glass!"];
[winPush setQuery:query];
[winPush sendPushInBackground];

// Notification for Windows Phone 8 users
[query whereKey:@"deviceType" equalTo:@"winphone"];
PFPush *wpPush = [[PFPush alloc] init];
[wpPush setMessage:@"Your suitcase is very hip; very metro."];
[wpPush setQuery:query];
[wpPush sendPushInBackground];
let query = PFInstallation.query()
if let query = query {
    query.whereKey("channels", equalTo: "suitcaseOwners")

    // Notification for Android users
    query.whereKey("deviceType", equalTo: "android")
    let androidPush = PFPush()
    androidPush.setMessage("Your suitcase has been filled with tiny robots!")
    androidPush.setQuery(query)
    androidPush.sendPushInBackground()

    // Notification for iOS users
    query.whereKey("deviceType", equalTo: "ios")
    let iOSPush = PFPush()
    iOSPush.setMessage("Your suitcase has been filled with tiny apples!")
    iOSPush.setChannel("suitcaseOwners")
    iOSPush.setQuery(query)
    iOSPush.sendPushInBackground()

    // Notification for Windows 8 users
    query.whereKey("deviceType", equalTo: "winrt")
    let winPush = PFPush()
    winPush.setMessage("Your suitcase has been filled with tiny glass!")
    winPush.setQuery(query)
    winPush.sendPushInBackground()

    // Notification for Windows Phone 8 users
    query.whereKey("deviceType", equalTo: "winphone")
    let wpPush = PFPush()
    wpPush.setMessage("Your suitcase is very hip; very metro.")
    wpPush.setQuery(query)
    wpPush.sendPushInBackground()
}

Scheduling Pushes

Sending scheduled push notifications is not currently supported by the iOS or OS X SDKs. Take a look at the REST API, JavaScript SDK or the Parse.com push console.

Receiving Pushes

As we saw in the Customizing Your Notification section, it is possible to send arbitrary data along with your notification message. We can use this data to modify the behavior of your app when a user opens a notification. For example, upon opening a notification saying that a friend commented on a user's picture, it would be nice to display this picture.

Due to the package size restrictions imposed by Apple, you need to be careful in managing the amount of extra data sent, since it will cut down on the maximum size of your message. For this reason, it is recommended that you keep your extra keys and values as small as possible.

NSDictionary *data = @{
  @"alert" : @"James commented on your photo!",
  @"p" : @"vmRZXZ1Dvo" // Photo's object id
};
PFPush *push = [[PFPush alloc] init];
[push setQuery:photoOwnerQuery];
[push setData:data];
[push sendPushInBackground];
let data = [
  "alert" : "James commented on your photo!",
  "p" : "vmRZXZ1Dvo" // Photo's object id
]
let push = PFPush()
push.setQuery(photoOwnerQuery)
push.setData(data)
push.sendPushInBackground()

Responding to the Payload

When an app is opened from a notification, the data is made available in the application:didFinishLaunchingWithOptions: methods through the launchOptions dictionary.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  . . .
  // Extract the notification data
  NSDictionary *notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];

  // Create a pointer to the Photo object
  NSString *photoId = [notificationPayload objectForKey:@"p"];
  PFObject *targetPhoto = [PFObject objectWithoutDataWithClassName:@"Photo"   objectId:photoId];

  // Fetch photo object
  [targetPhoto fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    // Show photo view controller
    if (!error) {
      PhotoVC *viewController = [[PhotoVC alloc] initWithPhoto:object];
      [self.navController pushViewController:viewController animated:YES];
    }
  }];
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  . . .
  // Extract the notification data
  if let notificationPayload = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {

      // Create a pointer to the Photo object
      let photoId = notificationPayload["p"] as? NSString
      let targetPhoto = PFObject(withoutDataWithClassName: "Photo", objectId: "xWMyZ4YEGZ")

      // Fetch photo object
      targetPhoto.fetchIfNeededInBackgroundWithBlock {
        (object: PFObject?, error:NSError?) -> Void in
          if error == nil {
              // Show photo view controller
              let viewController = PhotoVC(photo: object);
              self.navController.pushViewController(viewController, animated: true);
          }
      }
  }
}

If your app is already running when the notification is received, the data is made available in the application:didReceiveRemoteNotification:fetchCompletionHandler: method through the userInfo dictionary.

- (void)application:(UIApplication *)application
  didReceiveRemoteNotification:(NSDictionary *)userInfo  fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
  // Create empty photo object
  NSString *photoId = [userInfo objectForKey:@"p"];
  PFObject *targetPhoto = [PFObject objectWithoutDataWithClassName:@"Photo"   objectId:photoId];

  // Fetch photo object
  [targetPhoto fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    // Show photo view controller
    if (error) {
      handler(UIBackgroundFetchResultFailed);
    } else if ([PFUser currentUser]) {
      PhotoVC *viewController = [[PhotoVC alloc] initWithPhoto:object];
      [self.navController pushViewController:viewController animated:YES];
      handler(UIBackgroundFetchResultNewData);
    } else {
      handler(UIBackgroundModeNoData);
    }
  }];
}
func application(application: UIApplication,  didReceiveRemoteNotification userInfo: [NSObject : AnyObject],  fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
  if let photoId: String = userInfo["p"] as? String {
    let targetPhoto = PFObject(withoutDataWithClassName: "Photo", objectId: photoId)
    targetPhoto.fetchIfNeededInBackgroundWithBlock { (object: PFObject?, error: NSError?) -> Void in
      // Show photo view controller
      if error != nil {
        completionHandler(UIBackgroundFetchResult.Failed)
      } else if PFUser.currentUser() != nil {
        let viewController = PhotoVC(withPhoto: object)
        self.navController.pushViewController(viewController, animated: true)
        completionHandler(UIBackgroundFetchResult.NewData)
      } else {
        completionHandler(UIBackgroundFetchResult.NoData)
      }
    }
  }
  handler(UIBackgroundFetchResult.NoData)
}

You can read more about handling push notifications in Apple's Local and Push Notification Programming Guide.

Tracking Pushes and App Opens

To track your users' engagement over time and the effect of push notifications, we provide some hooks in the PFAnalytics class. You can view the open rate for a specific push notification on the Parse.com push console. You can also view overall app open and push open graphs are on the Parse analytics console. Our analytics graphs are rendered in real time, so you can easily verify that your application is sending the correct analytics events before your next release.

This section assumes that you've already set up your application to save the Installation object. Push open tracking only works when your application's devices are associated with saved Installation objects.

First, add the following to your application:didFinishLaunchingWithOptions: method to collect information about when your application was launched, and what triggered it. The extra checks ensure that, even with iOS 7's more advanced background push features, a single logical app-open or push-open event is counted as such.

if (application.applicationState != UIApplicationStateBackground) {
  // 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.
  BOOL preBackgroundPush = ![application respondsToSelector:@selector(backgroundRefreshStatus)];
  BOOL oldPushHandlerOnly = ![self respondsToSelector:@selector(application:didReceiveRemoteNotification:fetchCompletionHandler:)];
  BOOL noPushPayload = ![launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
  if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
    [PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
  }
}
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 oldPushHandlerOnly = !self.respondsToSelector(Selector("application:didReceiveRemoteNotification:fetchCompletionHandler:"))
  let noPushPayload: AnyObject? = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey]?
  if oldPushHandlerOnly || noPushPayload != nil {
    PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
  }
}

Second, if your application is running or backgrounded, the application:didReceiveRemoteNotification: method handles the push payload instead. If the user acts on a push notification while the application is backgrounded, the application will be brought to the foreground. To track this transition as the application being "opened from a push notification," perform one more check before calling any tracking code:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  if (application.applicationState == UIApplicationStateInactive) {
    // The application was just brought from the background to the foreground,
    // so we consider the app as having been "opened by a push notification."
    [PFAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
  }
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    if application.applicationState == .Inactive  {
        // The application was just brought from the background to the foreground,
        // so we consider the app as having been "opened by a push notification."
        PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
    }
}

Finally, if using iOS 7 any of its new push features (including the new "content-available" push functionality), be sure to also implement the iOS 7-only handler:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  if (application.applicationState == UIApplicationStateInactive) {
    [PFAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
  }
}
func application(application: UIApplication,  didReceiveRemoteNotification userInfo: [NSObject : AnyObject],  fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
  if application.applicationState == .Inactive {
    PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
  }
}

Tracking on OS X

If your OS X application supports receiving push notifications and you'd like to track application opens related to pushes, add hooks to the application:didReceiveRemoteNotification: method (as in iOS) and the following to applicationDidFinishLaunching:

- (void)applicationDidFinishLaunching:(NSNotification *)notification {
  // ... other Parse setup logic here
  [PFAnalytics trackAppOpenedWithRemoteNotificationPayload:[notification userInfo]];
}
func applicationDidFinishLaunching(notification: NSNotification) {
  // ... other Parse setup logic here
  PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(notification.userInfo)
}

Tracking Local Notifications (iOS only)

To track analytics around local notifications, note that application:didReceiveLocalNotification: is called in addition to application:didFinishLaunchingWithOptions:, if implemented. Please be careful to prevent tracking duplicate events.

Clearing the Badge

A good time to clear your app's badge is usually when your app is opened. Setting the badge property on the current installation will update the application icon badge number and ensure that the latest badge value will be persisted to the server on the next save. All you need to do is:

- (void)applicationDidBecomeActive:(UIApplication *)application {
  PFInstallation *currentInstallation = [PFInstallation currentInstallation];
  if (currentInstallation.badge != 0) {
    currentInstallation.badge = 0;
    [currentInstallation saveEventually];
  }
  // ...
}
func applicationDidBecomeActive(application: UIApplication) {
  let currentInstallation = PFInstallation.currentInstallation()
  if currentInstallation.badge != 0 {
    currentInstallation.badge = 0
    currentInstallation.saveEventually()
  }
  // ...
}

The UIApplicationDelegate documentation contains more information on hooks into an app’s life cycle; the ones which are most relevant for resetting the badge count are applicationDidBecomeActive:, application:didFinishLaunchingWithOptions:, and application:didReceiveRemoteNotification:.

Push Experiments

You can A/B test your push notifications to figure out the best way to keep your users engaged. With A/B testing, you can simultaneously send two versions of your push notification to different devices, and use each version's push open rates to figure out which one is better. You can test by either message or send time.

A/B Testing

Our web push console guides you through every step of setting up an A/B test.

For each push campaign sent through the Parse web push console, you can allocate a subset of your devices to be in the experiment's test audience, which Parse will automatically split into two equally-sized experiment groups. For each experiment group, you can specify a different push message. The remaining devices will be saved so that you can send the winning message to them later. Parse will randomly assign devices to each group to minimize the chance for a test to affect another test's results (although we still don't recommend running multiple A/B tests over the same devices on the same day).

After you send the push, you can come back to the push console to see in real time which version resulted in more push opens, along with other metrics such as statistical confidence interval. It's normal for the number of recipients in each group to be slightly different because some devices that we had originally allocated to that experiment group may have uninstalled the app. It's also possible for the random group assignment to be slightly uneven when the test audience size is small. Since we calculate open rate separately for each group based on recipient count, this should not significantly affect your experiment results.

If you are happy with the way one message performed, you can send that to the rest of your app's devices (i.e. the “Launch Group”). This step only applies to A/B tests where you vary the message.

Push experiments are supported on all recent Parse SDKs (iOS v1.2.13+, OS X v1.7.5+, Android v1.4.0+, .NET v1.2.7+). Before running experiments, you must instrument your app with push open tracking.

Experiment Statistics

Parse provides guidance on how to run experiments to achieve statistically significant results.

Test Audience Size

When you setup a push message experiment, we'll recommend the minimum size of your test audience. These recommendations are generated through simulations based on your app's historical push open rates. For big push campaigns (e.g. 100k+ devices), this recommendation is usually small subset of your devices. For smaller campaigns (e.g. < 5k devices), this recommendation is usually all devices. Using all devices for your test audience will not leave any remaining devices for the launch group, but you can still gain valuable insight into what type of messaging works better so you can implement similar messaging in your next push campaign.

Confidence Interval

After you send your pushes to experiment groups, we'll also provide a statistical confidence interval when your experiment has collected enough data to have statistically significant results. This confidence interval is in absolute percentage points of push open rate (e.g. if the open rates for groups A and B are 3% and 5%, then the difference is reported as 2 percentage points). This confidence interval is a measure of how much difference you would expect to see between the two groups if you repeat the same experiment many times.

Just after a push send, when only a small number of users have opened their push notifications, the open rate difference you see between groups A and B could be due to random chance, so it might not be reproducible if you run the same experiment again. After your experiment collects more data over time, we become increasingly confident that the observed difference is a true difference. As this happens, the confidence interval will become narrower, allowing us to more accurately estimate the true difference between groups A and B. Therefore, we recommend that you wait until there is enough data to generate a statistical confidence interval before deciding which group's push is better.

Troubleshooting

Setting up Push Notifications is often a source of frustration for developers. The process is complicated and invites problems to happen along the way. We have created a tutorial which covers all the necessary steps to configure your app for push notifications. If you run into issues, try some of the following troubleshooting tips.

It's important to break down the system into components when troubleshooting push notification issues. You can start by asking yourself the following questions:

If the answer is Yes to all of these questions, there may be an operational issue that is affecting the delivery of push notifications. You can see the current status of the platform in our status page. If everything looks green, please create a bug report with more information. Every bug report opened against the push notification category will be redirected to this troubleshooting guide unless it includes evidence of having gone through these steps, so please be as verbose as possible.

If you're unsure about the answer to any of the above questions, read on!

Confirm that the push campaign was created

Having everything set up correctly in your Parse app won't help if your request to send a push notification does not reach Parse. The first step in debugging a push issue is to confirm that the push campaign is listed in your push logs. You can find these logs by visiting your app's Dashboard and clicking on Push.

If the push notification campaign is not showing up on that list, the issue is quite simple to resolve. Go back to your push notification sending code and make sure to check for any error responses. If you're using any of the client SDKs, make sure to listen for and catch any errors that may be returned. For example, you could log errors like so:

[push sendPushInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
  if (success) {
    NSLog(@"The push campaign has been created.");
  } else if (error.code == kPFErrorPushMisconfigured) {
    NSLog(@"Could not send push. Push is misconfigured: %@", error.description);
  } else {
    NSLog(@"Error sending push: %@", error.description);
  }
}];
push.sendPushInBackgroundWithBlock {
    (success: Bool , error: NSError?) -> Void in
    if (success) {
        println("The push campaign has been created.");
    } else if (error!.code == 112) {
        println("Could not send push. Push is misconfigured: \(error!.description).");
    } else {
        println("Error sending push: \(error!.description).");
    }
}

Please note that SDKs that use a Client Key, such as the iOS/OS X SDKs, can only send push notifications if Client Push is enabled in your Parse app's Push Notification settings. Otherwise, you'll only be able to send pushes from the web console, the REST API, or by using the JavaScript SDK from Cloud Code. We strongly encourage developers to turn off Client Push before releasing their app publicly unless your use case allows for any amount of arbitrary pushes to be sent by any of your users. You can read our security guide for more information.

Verify your Targeting

You have confirmed that the push notification is making it to your push logs. Now what? The next step is to verify if your push notification targeting is correct. Say, if you're debugging why notifications are not reaching a specific device, it's important to make sure that this device is actually included in the targeting of this push notification. You can't deliver something that is not addressed correctly.

In order to do this, you'll have to confirm that the device's Installation object is included in your push notification targeting criteria. This is quite straightforward if you're using channels: all you need to verify is that your device's Installation is subscribed to the channel by checking the channels array. If you're using advanced targeting, e.g. you're using a push query with constraints, you'll have to work a bit more to determine if your targeting is on point.

Basically, you will need to run the same push query you're using for your targeting, and verify that your installation of interest is included in the result set. As you can only query the installation class programmatically using the Master Key, you will need to use one of the Master Key capable SDKs (JavaScript SDK, .NET) or the REST API. Ideally, you would use the same SDK that you're currently using to send the push notifications.

Debugging using the REST API

The REST API is quite easy to use for this sort of purpose as you can easily recreate the push query using the information provided in your push notification logs. If you look closely at the “Full Target” value in your push campaign log item, you may notice that it matches the query format for a REST API query. You can grab an example of what a REST API query over Installations would look like from the REST API docs. Don't forget to use the X-Parse-Master-Key header to ensure that the Master Key is used to run this query.

# Query over installations
curl -X GET \
-H "X-Parse-Application-Id: {YOUR_APPLICATION_ID}" \
-H "X-Parse-Master-Key: {YOUR_MASTER_KEY}" \
-G \
--data-urlencode 'limit=1000' \
--data-urlencode 'where={ "city": "San Francisco", "deviceType": { "$in": [ "ios", "android", "winphone", "embedded" ] } }' \
https://api.parse.com/1/installations

If you type the above into a console, you should be able to see the first 1,000 objects that match your query. Note that constraints are always ANDed, so if you want to further reduce the search scope, you can add a constraint that matches the specific installation for your device:

# Query over installations
curl -X GET \
-H "X-Parse-Application-Id: {YOUR_APPLICATION_ID}" \
-H "X-Parse-Master-Key: {YOUR_MASTER_KEY}" \
-G \
--data-urlencode 'limit=1' \
--data-urlencode 'where={ “objectId”: {YOUR_INSTALLATION_OBJECT_ID}, "city": "San Francisco", "deviceType": { "$in": [ "ios", "android", "winphone", "embedded" ] } }' \
https://api.parse.com/1/installations

If the above query returns no results, it is likely that your installation does not meet the targeting criteria for your campaign.

Check your Device Configuration

Your push campaign is created and the device is included in the targeting, but you're still not receiving push notifications. What gives?

This is a good time to go through your project settings and make sure everything is in order.

If everything compiles and runs with no errors, but you are still not receiving pushes:

If your app has been released for a while, it's possible for the recipient estimate on the push composer page to be higher than the pushes sent value on the push results page. The push composer estimate is generated via running your push segment query over your app's installation table. We do not automatically delete installation objects when the users uninstall your app or opt out of push notifications. When we try to send a push, we detect uninstalled installations and do not include them in the pushes sent value on the results page.

Handling Push Notifications

If everything looks great so far, but push notifications are not showing up on your phone, there are a few more things you can check. For example, if your app is in the foreground when the push notification is received, an alert will not be displayed by default. You will need to handle the incoming push notification and perform the necessary action as documented in Responding to the Payload.

If your app is not running in the foreground and the push notification is not showing up, make sure that you're specifying an "alert" key in your payload. Otherwise, the push notification will be treated as a silent push notification.

When using content-available to send silent push notifications, keep in mind that APNS may throttle push notifications sent to the same device token within a short period of time.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Config

Parse Config

PFConfig is a way to configure your applications remotely by storing a single configuration object on Parse. It enables you to add things like feature gating or a simple "Message of the Day". To start using PFConfig you need to add a few key/value pairs (parameters) to your app on the Parse Config Dashboard.

After that you will be able to fetch the PFConfig on the client, like in this example:

[PFConfig getConfigInBackgroundWithBlock:^(PFConfig *config, NSError *error) {
  NSNumber *number = config[@"winningNumber"];
  NSLog(@"Yay! The number is %@!", [number stringValue]);
}];
PFConfig.getConfigInBackgroundWithBlock {
  (config: PFConfig?, error: NSError?) -> Void in
  let number = config?["winningNumber"] as? Int
  println("Yay! The number is \(number)!")
}

Retrieving Config

PFConfig is built to be as robust and reliable as possible, even in the face of poor internet connections. Caching is used by default to ensure that the latest successfully fetched config is always available. In the below example we use getConfigInBackgroundWithBlock to retrieve the latest version of config from the server, and if the fetch fails we can simply fall back to the version that we successfully fetched before via currentConfig.

NSLog(@"Getting the latest config...");
[PFConfig getConfigInBackgroundWithBlock:^(PFConfig *config, NSError *error) {
  if (!error) {
    NSLog(@"Yay! Config was fetched from the server.");
  } else {
    NSLog(@"Failed to fetch. Using Cached Config.");
    config = [PFConfig currentConfig];
  }

  NSString *welcomeMessage = config[@"welcomeMessage"];
  if (!welcomeMessage) {
    NSLog(@"Falling back to default message.");
    welcomeMessage = @"Welcome!";
  }
  NSLog(@"Welcome Messsage = %@", welcomeMessage);
}];
println("Getting the latest config...");
PFConfig.getConfigInBackgroundWithBlock {
  (var config: PFConfig?, error: NSError?) -> Void in
  if error == nil {
    println("Yay! Config was fetched from the server.")
  } else {
    println("Failed to fetch. Using Cached Config.")
    config = PFConfig.currentConfig()
  }

  var welcomeMessage: NSString? = config?["welcomeMessage"] as? NSString
  if let welcomeMessage = welcomeMessage {
    println("Welcome Message = \(welcomeMessage)!")
  } else {
    println("Falling back to default message.")
    welcomeMessage = "Welcome!";
  }
};

Current Config

Every PFConfig instance that you get is always immutable. When you retrieve a new PFConfig in the future from the network, it will not modify any existing PFConfig instance, but will instead create a new one and make it available via [PFConfig currentConfig]. Therefore, you can safely pass around any PFConfig object and safely assume that it will not automatically change.

It might be troublesome to retrieve the config from the server every time you want to use it. You can avoid this by simply using the cached currentConfig object and fetching the config only once in a while.

// Fetches the config at most once every 12 hours per app runtime
const NSTimeInterval configRefreshInterval = 12.0 * 60.0 * 60.0;
static NSDate *lastFetchedDate;
if (lastFetchedDate == nil ||
    [lastFetchedDate timeIntervalSinceNow] * -1.0 > configRefreshInterval) {
  [PFConfig getConfigInBackgroundWithBlock:nil];
  lastFetchedDate = [NSDate date];
}
// Fetches the config at most once every 12 hours per app runtime
let configRefreshInterval: NSTimeInterval  = 12.0 * 60.0 * 60.0
struct DateSingleton {
    static var lastFetchedDate: NSDate? = nil
}
let date: NSDate? = DateSingleton.lastFetchedDate;
if date == nil ||
   date!.timeIntervalSinceNow * -1.0 > configRefreshInterval {
  PFConfig.getConfigInBackgroundWithBlock(nil);
  DateSingleton.lastFetchedDate = NSDate();
}

Parameters

PFConfig supports most of the data types supported by PFObject:

We currently allow up to 100 parameters in your config and a total size of 128KB across all parameters.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Analytics

Parse provides a number of hooks for you to get a glimpse into the ticking heart of your app. We understand that it's important to understand what your app is doing, how frequently, and when.

While this section will cover different ways to instrument your app to best take advantage of Parse's analytics backend, developers using Parse to store and retrieve data can already take advantage of metrics on Parse.

Without having to implement any client-side logic, you can view real-time graphs and breakdowns (by device type, Parse class name, or REST verb) of your API Requests in your app's dashboard and save these graph filters to quickly access just the data you're interested in.

App-Open & Push Analytics

Our initial analytics hook allows you to track your application being launched. By adding the following line to applicationDidFinishLaunching:, you'll begin to collect data on when and how often your application is opened.

// in iOS
[PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];

// in OS X
[PFAnalytics trackAppOpenedWithLaunchOptions:nil];
// in iOS
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)

// in OS X
PFAnalytics.trackAppOpenedWithLaunchOptions(nil)

Graphs and breakdowns of your statistics are accessible from your app's Dashboard.

Further analytics are available around push notification delivery and open rates. Be sure to take a look at the Tracking Pushes and App Opens subsection of our Push Guide for more detailed information on handling remote notification payloads and push-related callbacks.

Custom Analytics

PFAnalytics also allows you to track free-form events, with a handful of NSString keys and values. These extra dimensions allow segmentation of your custom events via your app's Dashboard.

Say your app offers search functionality for apartment listings, and you want to track how often the feature is used, with some additional metadata.

NSDictionary *dimensions = @{
  // Define ranges to bucket data points into meaningful segments
  @"priceRange": @"1000-1500",
  // Did the user filter the query?
  @"source": @"craigslist",
  // Do searches happen more often on weekdays or weekends?
  @"dayType": @"weekday"
};
// Send the dimensions to Parse along with the 'search' event
[PFAnalytics trackEvent:@"search" dimensions:dimensions];
let dimensions = [
  // Define ranges to bucket data points into meaningful segments
  "priceRange": "1000-1500",
  // Did the user filter the query?
  "source": "craigslist",
  // Do searches happen more often on weekdays or weekends?
  "dayType": "weekday"
]
// Send the dimensions to Parse along with the 'search' event
PFAnalytics.trackEvent("search", dimensions:dimensions)

PFAnalytics can even be used as a lightweight error tracker — simply invoke the following and you'll have access to an overview of the rate and frequency of errors, broken down by error code, in your application:

NSString *codeString = [NSString stringWithFormat:@"%d", [error code]];
[PFAnalytics trackEvent:@"error" dimensions:@{ @"code": codeString }];
let codeString = NSString(format:"%@", error.code)
PFAnalytics.trackEvent("error", dimensions:["code": codeString])

Note that Parse currently only stores the first eight dimension pairs per call to trackEvent:dimensions:.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Crash Reporting

Crash Reporting allows you to find out how your app is crashing in the wild. You'll be able to see your most impactful crashes, complete with stack traces, device information, and more. To get started, head over to the Quick Start to instrument your app.

Enabling

To enable Crash Reporting, add this line to your AppDelegate before you initialize your Parse app keys:

// Enable Crash Reporting
[ParseCrashReporting enable];

// Setup Parse
[Parse setApplicationId:@"parseAppId" clientKey:@"parseClientKey"];
// Enable Crash Reporting
ParseCrashReporting.enable();

// Setup Parse
Parse.setApplicationId("parseAppId", clientKey: "parseClientKey")

Once this is enabled, all crashes from your app will be sent to Parse and will show up in the analytics dashboard.

Symbolication

It's important to send Parse the symbol files for each build of your app. This allows Parse to properly aggregate crash incidents together and show these crashes on the dashboard with proper symbols in the stack trace.

There are two ways to upload your symbol files: automatically after each build in Xcode (view instructions in Quick Start) and manually. We highly recommend doing the upload automatically so you don't have to remember every time you cut a release.

To automatically upload symbol files for your application whenever you build your app:

parse new
export PATH=/usr/local/bin:$PATH
cd <path_to_cloudcode_folder>

parse symbols <app_name_from_cloud_code_config_globals> --path="${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}"

Alternatively, you can manually upload symbol files using the command line tool:

parse symbols <app_name_from_cloud_code_config_globals> --path="<dSYM/xcarchive/DWARF path>"

The symbol files for your apps can be found in one of these locations, depending on your deployment workflow:

Manual uploads can be useful when you've forgotten to upload symbol files for a build that has been released. You will see a message to symbolicate the stack traces when you're viewing a crash that hasn't been symbolicated.

Testing

Once you've enabled Crash Reporting, you'll want to test to make sure your crashes are properly being sent to Parse. First, add the following method in one of your view controllers, or the App Delegate:

- (void)crash {
    [NSException raise:NSGenericException format:@"Everything is ok. This is just a test crash."];
}
NSException(name: NSGenericException, reason: "Everything is ok. This is just a test crash.", userInfo: nil).raise()

Then, put this invocation in your main view controllers' viewDidLoad, or in application:didFinishLaunchingWithOptions: if you're using the App Delegate:

[self performSelector:@selector(crash) withObject:nil afterDelay:5.0];
dispatch_after(
    dispatch_time(DISPATCH_TIME_NOW, Int64(5.0 * Double(NSEC_PER_SEC))),
    dispatch_get_main_queue(),
    { () -> Void in
        self.crash()
});

Next, follow these steps:

  1. Build, run, and then stop the app.
  2. Run the app without the debugger, which will catch crashes and prevent them from being sent to Parse. The easiest way to do this is to directly launch the app from the home screen.
  3. Wait for the app to crash.
  4. Run the app again. The app will automatically send the crash report to Parse on startup.

At this point, go to the Crash Reporting dashboard under Analytics for your app and make sure you see the crash in the listing. It can take a few minutes for the crash to show up.

Workflow

By using Crash Reporting, you can dramatically improve the quality of your app by reducing the number of crashes your end users experience. We recommend the following workflow to efficiently fix your crashes:

  1. Identify crashes to fix. The main view of the Crash Reporting dashboard shows all your crashes ordered by the number of occurrences. Typically, you'll want to start by fixing the crashes that are affecting the most users. You can click on each crash and get details such as the stack trace, OS versions, device types, and affected app versions.

  2. Fix a crash. Do some debugging and fix your crash in your client code.

  3. Bump your build version (CFBundleVersion) and build a new release.

  4. Mark the crash as resolved and release a new build to the App Store. Once resolved, the crash will no longer show up on the crash listings page with the default filters. If the crash does occur again in a later version, it will automatically be marked as unresolved, and will show up on the listing again.

  5. Go back to step 1 and continue to improve your app!

Troubleshooting

Why aren't my crashes showing up on the dashboard?

Your app is probably not sending crash reports to Parse. Here are some things to check:

Why aren't my crashes symbolicated?

You probably have not uploaded symbol files for the build of the app associated with the crash. Here are some things to check:

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

User Interface

At the end of the day, users of your app are going to be interacting with UIKit components.

ParseUI is an opensource collection of a handy user interface components aimed to streamline and simplify user authentication, displaying lists of data, and other common app elements.

Please note that ParseUI is not included inside the main Parse iOS SDK.

To learn more on how to install it - follow the instructions on the official GitHub page.

PFLogInViewController

If you are using Parse to manage users in your mobile app, you are already familiar with the PFUser class. At some point in your app, you might want to present a screen to log in your PFUser. ParseUI provides a view controller that does exactly this:

Watch a tutorial on using the login and signup views, which provide a set of built-in views ready to be customized and dropped into your app that uses PFUser.

You use the PFLogInViewController class by instantiating it and presenting it modally:

PFLogInViewController *logInController = [[PFLogInViewController alloc] init];
logInController.delegate = self;
[self presentViewController:logInController animated:YES completion:nil];
var logInController = PFLogInViewController()
logInController.delegate = self
self.presentViewController(logInController, animated:true, completion: nil)

Configuring the Log In Elements

PFLogInViewController can be configured to provide a variety of log in options. By default, PFLogInViewController presents the following UI:

Any of the above features can be turned on or off. The options can be set using the fields property on PFLogInViewController:

  logInController.fields = (PFLogInFieldsUsernameAndPassword
                           | PFLogInFieldsLogInButton
                           | PFLogInFieldsSignUpButton
                           | PFLogInFieldsPasswordForgotten
                           | PFLogInFieldsDismissButton);
  logInController.fields = (PFLogInFields.UsernameAndPassword
                           | PFLogInFields.LogInButton
                           | PFLogInFields.SignUpButton
                           | PFLogInFields.PasswordForgotten
                           | PFLogInFields.DismissButton)

Essentially, you use the bitwise or operator (|) to chain up all the options you want to include in the log in screen, and assign the value to fields.

In addition, there are a number of other options that can be turned on, including:

Similarly, you can turn on Facebook or Twitter log in as such:

logInController.fields = (PFLogInFieldsUsernameAndPassword
                          | PFLogInFieldsFacebook
                          | PFLogInFieldsTwitter);
logInController.fields = (PFLogInFields.UsernameAndPassword
                          | PFLogInFields.Facebook
                          | PFLogInFields.Twitter)

The above code would produce a log in screen that includes username, password, Facebook and Twitter buttons. Facebook log in permissions can be set via the facebookPermissions.

PFLogInViewController *logInController = [[PFLogInViewController alloc] init];
logInController.delegate = self;
logInController.facebookPermissions = @[ @"friends_about_me" ];
[self presentViewController:logInController animated:YES completion:nil];
var logInController = PFLogInViewController()
logInController.delegate = self
logInController.facebookPermissions = [ "friends_about_me" ]
self.presentViewController(logInController, animated:true, completion:nil)

Responding to Log In Success, Failure or Cancellation

When the user signs in or cancels, the PFLogInViewController notifies the delegate of the event. Upon receiving this callback, the delegate should, at a minimum, dismiss PFLogInViewController. Additionally, the delegate could possibly update its own views or forward the message to the other components that need to know about the PFUser.

- (void)logInViewController:(PFLogInViewController *)controller
               didLogInUser:(PFUser *)user {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)logInViewControllerDidCancelLogIn:(PFLogInViewController *)logInController {
    [self dismissViewControllerAnimated:YES completion:nil];
}
func logInViewController(controller: PFLogInViewController, didLogInUser user: PFUser!) -> Void {
  self.dismissViewController(true, completion: nil)
}

func logInViewControllerDidCancelLogIn(controller: PFLogInViewController) -> Void {
  self.dismisViewControllerAnimated(true, completion: nil)
}

Besides the delegate pattern, the PFLogInViewController also supports NSNotifications, which is useful if there are multiple observers of the sign in events.

Customizing the Logo and Background Image

You might want to use your own logo or background image. You can achieve this by subclassing PFLogInViewController and overriding viewDidLoad method:

@interface MyLogInViewController : PFLogInViewController

@end

@implementation MyLogInViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor darkGrayColor];

    UIImageView *logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]];
    self.logInView.logo = logoView; // logo can be any UIView
}
@end
class MyLogInViewController : PFLogInViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = UIColor.darkGrayColor()

    let logoView = UIImageView(image: UIImage(named:"logo.png"))
    self.logInView.logo = logoView
  }

}

If you would like to modify the logo and the background of the associated sign up view, you will need to subclass PFSignUpViewController and create an instance of the subclass and assign it to the signUpController as soon as you instantiate PFLogInViewController:

MyLogInViewController *logInController = [[MyLogInViewController alloc] init];
logInController.signUpController = [[MySignUpViewController alloc] init];
[self presentViewController:logInController animated:YES completion:nil];
let logInController = MyLogInViewController()
logInController.signUpController = MySignUpViewController()
self.presentViewController(logInController, animated: true, completion: nil)

Further View Customization

Occasionally you might want to customize PFLogInViewController further. For example, you might want to change the placeholder text to "Email" or change the size of the login button. In both cases, you need to subclass PFLogInViewController and override either viewDidLoad or viewDidLayoutSubviews. Override the former if the behavior is not related to layout, and override the latter otherwise:

@interface MyLogInViewController : PFLogInViewController

@end

@implementation MyLogInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.logInView.usernameField.placeholder = @"email";
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.logInView.logInButton.frame = CGRectMake(...); // Set a different frame.
}

@end
class MyLogInViewController : PFLogInViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    self.logInView.usernameField.placeholder = "email"
  }

  override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    self.logInView.logInButton.frame = CGRectMake(...) // Set a different frame.
  }

}

Developers interested in this kind of customization should take a look at the interface of PFLogInView, where all customizable properties are documented.

Portrait and Landscape

By default, the PFLogInViewController supports all orientations on iPad and UIInterfaceOrientationPortrait on iPhone.

Resolution Independent

The PFLogInViewController is written to be resolution-independent, meaning it looks great on all iOS device sizes and pixel densities.

PFSignUpViewController

If you are using PFLogInViewController with the PFLogInFieldsSignUpButton option enabled, you do not need to do any additional work to enable the sign up functionality. When your user taps on the sign up button on the log in screen, a sign up screen will appear and allow them to sign up. However, there are occasions where you might want to use the sign up screen independently of the log in screen. This is when the PFSignUpViewController comes in handy.

You use PFSignUpViewController by instantiating it and presenting it modally:

PFSignUpViewController *signUpController = [[PFSignUpViewController alloc] init];
signUpController.delegate = self;
[self presentViewController:signUpController animated:YES completion:nil];
let signUpController = PFSignUpViewController()
signUpController.delegate = self
self.presentViewController(signUpController, animated: true, completion: nil)

That is all you need to do to get a functional sign up screen.

Configuring the Sign Up Elements

PFSignUpViewController can be configured to provide a variety of sign up options. By default, it presents the following UI:

If your sign up screen requires an additional field on top of the default ones, such as "phone number", you can turn on a field called named "additional":

signUpController.fields = (PFSignUpFieldsUsernameAndPassword
                          | PFSignUpFieldsSignUpButton
                          | PFSignUpFieldsEmail
                          | PFSignUpFieldsAdditional
                          | PFSignUpFieldsDismissButton);
signUpController.fields = (PFSignUpFields.UsernameAndPassword
                          | PFSignUpFields.SignUpButton
                          | PFSignUpFields.Email
                          | PFSignUpFields.Additional
                          | PFSignUpFields.DismissButton)

Essentially, you use the bitwise or operator (|) to chain up all the options you want to include in the sign up screen, and assign the value to fields. Similarly, you can turn off any field by omitting it in the assignment to fields.

Responding to Sign Up Success, Failure or Cancellation

When the user signs up or cancels, the PFSignUpViewController notifies the delegate of the event. Upon receiving this callback, the delegate should, at a minimum, dismiss PFSignUpViewController. Additionally, the delegate could update its own views or forward the message to the other components that need to know about the PFUser.

- (void)signUpViewController:(PFSignUpViewController *)signUpController didSignUpUser:(PFUser *)user {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)signUpViewControllerDidCancelSignUp:(PFSignUpViewController *)signUpController {
    [self dismissViewControllerAnimated:YES completion:nil];
}
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) -> Void {
  self.dismissViewControllerAnimated(true, completion: nil)
}

func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) -> Void {
  self.dismissViewControllerAnimated(true, completion: nil)
}

Besides the delegate pattern, the PFSignUpViewController also supports NSNotifications, which is useful when there are multiple listeners of the sign up events.

Customizing the Logo and Background Image

You might want to use your own logo or background image. You can achieve this by subclassing PFSignUpViewController and overriding viewDidLoad:

@interface MySignUpViewController : PFSignUpViewController

@end

@implementation MySignUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor darkGrayColor];

    UIImageView *logoView = [[UIImageView alloc] initWithImage:@"logo.png"];
    self.signUpView.logo = logoView; // logo can be any UIView
}

@end
class MySignUpViewController : PFSignUpViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = UIColor.darkGrayColor()

    let logoView = UIImageView(image: UIImage(named: "logo.png"))
    self.signUpView.logo = logoView // 'logo' can be any UIView
  }
}

Customizing Validation Logic

Often you will want to run some client-side validation on the sign up information before submitting it to the Parse Cloud. You can add your validation logic in the signUpViewController:shouldBeginSignUp: method in the PFSignUpViewControllerDelegate. For example, if you decide any password less than 8 characters is too short, you can achieve the following with:

- (BOOL)signUpViewController:(PFSignUpViewController *)signUpController
           shouldBeginSignUp:(NSDictionary *)info {
    NSString *password = info[@"password"];
    return (password.length >= 8); // prevent sign up if password has to be at least 8 characters long
}
func signUpViewController(signUpController: PFSignUpViewController!,
                          shouldBeginSignUp info: [NSObject : AnyObject]!) -> Bool {
    if let password = info?["password"] as? String {
      return password.utf16Count >= 8
    }
    return false
}

info is a dictionary that contains all sign up fields, such as username, password, email, and additional.

Further View Customization

Occasionally you might want to customize PFSignUpViewController further. For example, you might want to change the "additional" placeholder text to "Phone" or change the size of the signup button. You can always subclass PFSignUpViewController and override UIViewController's various methods. You should override the viewDidLoad if the behavior you want to change is unrelated to view layout, and override viewDidLayoutSubviews otherwise:

@interface MySignUpViewController : PFSignUpViewController

@end

@implementation MySignUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.signUpView.usernameField.placeholder = @"phone";
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.signUpView.signUpButton.frame = CGRectMake(...); // Set a different frame.
}

@end
class MySignUpViewController : PFSignUpViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    self.signUpView.usernameField.placeholder = "phone"
  }

  override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    self.signUpView.signUpButton.frame = CGRectMake(...) // Set a different frame.
  }

}

Developer interested in this kind of customization should take a look at the interface of PFSignUpView, where all customizable properties are documented.

Portrait and Landscape

By default, the PFSignUpViewController supports all orientations on iPad and UIInterfaceOrientationPortrait on iPhone.

Resolution Independent

The PFSignUpViewController is written to be resolution-independent, meaning it looks great on all iOS device sizes and pixel densities.

PFQueryTableViewController

Data oriented iOS applications are mostly a collection of UITableViewControllers and corresponding UITableViews. When using Parse, each cell of a UITableView typically represents data from a PFObject. PFQueryTableViewController is a sub-class of UITableViewController that provides a layer of abstraction that lets you easily display data from one of your Parse classes.

Watch a tutorial on using PFQueryTableViewController to display objects from a Todo class in your Parse application.

You use PFQueryTableViewController much like how you would use UITableViewController:

  1. Make a subclass of PFQueryTableViewController and customize it. Use the template file as a starting point.
  2. It automatically sets itself as the delegate and datasource.
  3. Set the parseClassName instance variable to specify which Parse class should be queried for data.
  4. Override the queryForTable method to construct a custom PFQuery that should be used to get objects for the table.
  5. Override the tableView:cellForRowAtIndexPath:object: method to return a custom cell tailored for each PFObject.
  6. Implement your custom cell class; makes sure it inherits from PFTableViewCell class.
  7. When the view loads, the class automatically grabs the PFObjects via the constructed query and loads it into the table. It even includes pagination and pull-to-refresh out of the box.

The class allows you to think about a one-to-one mapping between a PFObject and a UITableViewCell, rather than having to juggle index paths. You also get the following features out of the box:

The easiest way to understand this class is with an example. This subclass of PFQueryTableViewController displays a series of Todo items and their numeric priorities:

@interface SimpleTableViewController : PFQueryTableViewController

@end

@implementation SimpleTableViewController

- (instancetype)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:style];
    if (self) { // This table displays items in the Todo class
      self.parseClassName = @"Todo";
      self.pullToRefreshEnabled = YES;
      self.paginationEnabled = YES;
      self.objectsPerPage = 25;
    }
    return self;
}

- (PFQuery *)queryForTable {
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];

    // If no objects are loaded in memory, we look to the cache first to fill the table
    // and then subsequently do a query against the network.
    if (self.objects.count == 0) {
      query.cachePolicy = kPFCachePolicyCacheThenNetwork;
    }

    [query orderByDescending:@"createdAt"];

    return query;
}

- (UITableViewCell *)tableView:(UITableView *)tableView  
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
                        object:(PFObject *)object {
    static NSString *cellIdentifier = @"cell";

    PFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
      cell = [[PFTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                    reuseIdentifier:cellIdentifier];
    }

    // Configure the cell to show todo item with a priority at the bottom
    cell.textLabel.text = object[@"text"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"Priority: %@",  object[@"priority"]];

    return cell;
}

@end

This view shows a list of Todo items and also allows the user to pull-to-refresh and load the next page by touching a special pagination cell at the end of the table. It also properly caches the objects such that when the view is no longer in memory, the next time it loads it will use the query cache to immediately show the previously loaded objects while making a network call to update.

Notice all the code that we're not writing. We don't need to handle loading the data into the table, wrangle index paths, or handle tricky pagination code. That's all handled by the PFQueryTableViewController automatically.

A good starting point to learn more is to look at the API for the class and also the template subclass file. We designed the class with customizability in mind, so it should accommodate many instances where you used to use UITableViewController.

Loading Remote Images in Cells

PFQueryTableViewController makes it simple to display remote images stored in the Parse Cloud as PFFiles. All you need to do is to override tableView:cellForRowAtIndexPath:object: and return a PFTableViewCell with its imageView's file property specified. If you would like to display a placeholder image to be shown before the remote image is loaded, assign the placeholder image to the image property of the imageView.

@implementation SimpleTableViewController

- (UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
    static NSString *identifier = @"cell";
    PFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) { cell = [[PFTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.text = object[@"title"];

    PFFile *thumbnail = object[@"thumbnail"];
    cell.imageView.image = [UIImage imageNamed:@"placeholder.jpg"];
    cell.imageView.file = thumbnail;
    return cell;
}
@end

This table shows a list of cute animal photos which are stored in the Parse Cloud, as PFFiles. "placeholder.jpg" is an image included in the application bundle which is shown before the animal photos are downloaded.

The images are downloaded on demand. As you scroll through the table, the images in the currently visible cells are downloaded. This just-in-time behavior is desirable because not only does it conserve bandwidth, it also ensures timely display of visible images. If a more aggressive loading behavior is desired, you can use the loadInBackground method on imageView to download the image.

Customizing the Query

The default query is set to get objects from your class ordered by descending createdAt. To customize, simply override the queryForTable method to return your own PFQuery. The table will use this query when getting objects to display.

Customizing the Cells

To customize the look of your table, override tableView:cellForRowAtIndexPath:object: to return a customized cell. Notice that this method is similar to the typical table data source method, but it includes the PFObject directly as a parameter.

You should no longer override tableView:cellForRowAtIndexPath:.

Important: your table view cells should inherit from PFTableViewCell, rather than UITableViewCell. PFTableViewCell is a subclass of UITableViewCell that supports remote image loading. When used in PFQueryTableViewController, PFTableViewCell's remote images would be automatically loaded.

Lifecycle Methods

Several methods are exposed that are called at major events during the data lifecycle of the table. They are objectsDidLoad: and objectsWillLoad, which are called after the objects have loaded from the query, and right before the query is fired, respectively. You can override these to provide extra functionality during these events.

Pagination

Pagination ensures that the table only gets one page of objects at a time. You can customize how many objects are in a page by setting the objectsPerPage instance variable.

The query is automatically altered to apply pagination, and, when the table first loads, it only shows the first page of objects. A pagination cell appears at the bottom of the table which allows users to load the next page. You can customize this cell by overriding tableView:cellForNextPageAtIndexPath:

Pagination is turned on by default. If you want to turn it off, simply set paginationEnabled to NO.

Pull to Refresh

Pull to Refresh is a feature that allows users to pull the table down and release to reload the data. Essentially, the first page of data is reloaded from your class and the table is cleared and updated with the data.

Pull to Refresh is turned on by default. If you want to turn it off, simply set pullToRefreshEnabled to NO.

Loading View

A loading view is displayed when the table view controller is loading the first page of data. It is turned on by default, and can be turned off via the property loadingViewEnabled.

Offline and Error Messages

When the user is offline or a Parse error was generated from a query, an alert can automatically be shown to the user. By default, this is turned on when using PFQueryTableViewController. If you want to turn this behavior off, you can do so using the methods offlineMessagesEnabled and errorMessagesEnabled on the Parse class.

PFImageView

Many apps need to display images stored in the Parse Cloud as PFFiles. However, to load remote images with the built-in UIImageView involves writing many lines of boilerplate code. PFImageView simplifies this task:

PFImageView *imageView = [[PFImageView alloc] init];
imageView.image = [UIImage imageNamed:@"..."]; // placeholder image
imageView.file = (PFFile *)someObject[@"picture"]; // remote image

[imageView loadInBackground];
let imageView = PFImageView()
imageView.image = UIImage(named: "...") // placeholder image
imageView.file = someObject.picture // remote image

imageView.loadInBackground()

If assigned to, the image property is used to display a placeholder before the remote image is downloaded. Note that the download does not start as soon as the file property is assigned to, but the loading only begins when loadInBackground: is called. The remote image is cached both in memory and on disc. If the image is found in cache, the call to loadInBackground: would return immediately.

PFTableViewCell

Many apps need to display table view cells which contain images stored in the Parse Cloud as PFFiles. However, to load remote images with the built-in UITableViewCell involves writing many lines of boilerplate code. PFTableViewCell simplifies this task by exposing an imageView property of the type PFImageView that supports remote image loading:

@implementation SimpleTableViewController

- (UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
    static NSString *identifier = @"cell";
    PFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) { cell = [[PFTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.text = object[@"title"];

    PFFile *thumbnail = object[@"thumbnail"];
    cell.imageView.image = [UIImage imageNamed:@"placeholder.jpg"];
    cell.imageView.file = thumbnail;
    return cell;
}

@end
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let identifier = "cell"
    var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? PFTableViewCell
    if cell == nil {
        cell = PFTableViewCell(style: .Default, reuseIdentifier: identifier)
    }

    if let title = object["title"] as? String {
        cell!.textLabel.text = title
    }
    if let thumbnail = object["thumbnail"] as? PFFile {
        cell!.imageView.image = UIImage(named: "placeholder.jpg")
        cell!.imageView.file = thumbnail
    }

    return cell!
}

Like UITableViewCell, PFTableViewCell supports the default layout styles. Unlike UITableViewCell, PFTableViewCell's imageView property is of the type PFImageView, which supports downloading remote images in PFFile.

Although it can be used independently, PFTableViewCell really shines when used in PFQueryTableViewController. PFQueryTableViewController knows about PFTableViewCell and loads the images automatically. This behavior is discussed in detail in the documentation for PFQueryTableViewController.

Customizing/Localizing String Resources

All strings in Parse's UI classes are customizable/localizable. The easiest way to customize a string is through the default localization support provided by iOS.

Say, for example, you would like to customize the loading message in the HUD of PFSignUpViewController that says "Loading..." Assume you have followed the localization guide and set up Localizable.strings in the en.lproj directory. In Localizable.strings, you can then enter:

"Loading..." = "In progress";

That would customize the string to "In progress". The key on the left is the original string you want to customize, and the value on the right is the customized value.

Say, you would like to customize the error message in PFSignUpViewController that says "The email address "andrew@x" is invalid. Please enter a valid email." You are not sure how to enter this into Localizable.strings because it contains a variable.

Included in the Parse SDK is a file named Localizable.string which includes all the localizable keys in the Parse framework. Browsing this file, developers can find the key for the string they would like to customize. You notice that the string "The email address \"%@\" is invalid. Please enter a valid email." is a key in the file. In your own Localizable.strings, you can then enter:

"The email address \"%@\" is invalid. Please enter a valid email." = "Wrong email: \"%@\"";

The string is now customized.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

In-App Purchases

Parse provides a set of APIs for working with in-app purchases. Parse makes it easier to work with StoreKit and facilitates delivery of downloadable content with receipt verification in the cloud. Receipt verification is a mechanism that allows you to restrict downloads to only those users that have paid accordingly.

In addition, developers can attach query-able metadata on products to categorize, search, and dynamically manipulate products available for purchase.

Lastly, any content uploaded to Parse is exempt from the Apple review process, and hence can be served as soon as the upload is complete.

Apple Setup

Prior to using in-app purchases on Parse, you'll need to set up your app and products with Apple. This process spans both the provisioning portal and iTunes Connect. We recommend following this step-by-step guide.

Note that this is a tricky setup process so please ensure you follow Apple's documentation precisely.

Simple Purchases

Once the setup above is complete, you can begin working with in-app purchases.

On the main thread, register the handlers for the products:

// Use the product identifier from iTunes to register a handler.
[PFPurchase addObserverForProduct:@"Pro" block:^(SKPaymentTransaction *transaction) {
    // Write business logic that should run once this product is purchased.
    isPro = YES;
}];
// Use the product identifier from iTunes to register a handler.
PFPurchase.addObserverForProduct("Pro") {
    (transaction: SKPaymentTransaction?) -> Void in
    // Write business logic that should run once this product is purchased.
    isPro = YES;
}

Note that this does not make the purchase, but simply registers a block to be run if a purchase is made later. This registration must be done on the main thread, preferably as soon as the app is launched, i.e. in application:didFinishLaunchingWithOptions:. If there are multiple products, we recommend registering all product handlers in the same method, such as application:didFinishLaunchingWithOptions:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ...
    [PFPurchase addObserverForProduct:@"Pro" block:^(SKPaymentTransaction *transaction) {
        isPro = YES;
    }];
    [PFPurchase addObserverForProduct:@"VIP" block:^(SKPaymentTransaction *transaction) {
        isVip = YES;
    }];
}
PFPurchase.addObserverForProduct("Pro") {
    (transaction: SKPaymentTransaction?) -> Void in
    isPro = YES;
}
PFPurchase.addObserverForProduct("Pro") {
    (transaction: SKPaymentTransaction?) -> Void in
    isVip = YES;
}

To initiate a purchase, use the +[PFPurchase buyProduct:block:] method:

[PFPurchase buyProduct:@"Pro" block:^(NSError *error) {
    if (!error) {
        // Run UI logic that informs user the product has been purchased, such as displaying an alert view.
    }
}];
PFPurchase.buyProduct("Pro") {
    (error: NSError?) -> Void in
    if error == nil {
        // Run UI logic that informs user the product has been purchased, such as displaying an alert view.
    }
}

The call to buyProduct:block: brings up a dialogue that asks users to enter their Apple credentials. When the user's identity is verified, the product will be purchased. If the product is non-consumable and has been purchased by the user before, the user will not be charged.

Downloadable Purchases

Many IAP products such as books and movies have associated content files that should be downloaded once the purchase is made. This is very simple to do with Parse:

  1. First, go to the web data browser and create a Product class,
  2. For each product, fill in the required metadata information and upload the content files:
    1. productIdentifier: the product identifier of the product, matching the one in iTunes Connect
    2. icon: the icon to be displayed in PFProductTableViewController
    3. title: the title to be displayed in PFProductTableViewController
    4. subtitle: the subtitle to be displayed in PFProductTableViewController
    5. order: the order this product should appear in PFProductTableViewController. This is used only in PFProductTableViewController; fill in 0 if the order is not important,
    6. download: the downloadable content file. Note that the file uploaded in download is not publicly accessible, and only becomes available for download when a purchase is made. downloadName is the name of the file on disk once downloaded. You don't need to fill this in.
  3. Next, you need to register the product handler:
    [PFPurchase addObserverForProduct:@"Pro" block:^(SKPaymentTransaction *transaction) {
    [PFPurchase downloadAssetForTransaction:transaction completion:^(NSString *filePath, NSError *error) {
        if (!error) {
            // at this point, the content file is available at filePath.
        }
    }];
    }];
    
    PFPurchase.addObserverForProduct("Pro") {
    (transaction: SKPaymentTransaction?) -> Void in
    if let transaction = transaction {
        PFPurchase.downloadAssetForTransaction(transaction) {
            (filePath: String?, error: NSError?) -> Void in
            if error == nil {
                // at this point, the content file is available at filePath.
            }
        }
    }
    }
    
    Note that this does not make the purchase, but simply registers a block to be run if a purchase is made later. The call to downloadAssetForTransaction:completion: passes the receipt of the purchase to the Parse Cloud, which then verifies with Apple that the purchase was made. Once the receipt is verified, the purchased file is downloaded.

To make the purchase:

[PFPurchase buyProduct:@"Pro" block:^(NSError *error) {
    if (!error) {
        // run UI logic that informs user the product has been purchased, such as displaying an alert view.
    }
}];
PFPurchase.buyProduct("Pro") {(error: NSError?) -> Void in
    if error == nil {
        // run UI logic that informs user the product has been purchased, such as displaying an alert view.
    }
}

The call to buyProduct:block: brings up a dialogue that asks users to enter their Apple credentials. When the user's identity is verified, the product will be purchased.

Querying Product Information

You can query the product objects created in the data browser using PFProduct. Like PFUser or PFRole, PFProduct is a subclass of PFObject that contains convenience accessors to various product-specific properties.

For example, here's a simple query to get a product:

PFQuery *productQuery = [PFProduct query];
PFProduct *product = [[productQuery findObjects] lastObject];
NSLog(@"%@, %@", product.productIdentifier, product.title);
let productQuery = PFProduct.query()
if let product = productQuery.findObjects.lastObject as? PFProduct {}
  prinln(product.productIdentifier, product.title)
}

PFProductTableViewController

PFProductTableViewController is a subclass of PFQueryTableViewController that displays all IAP products in a table view. Some content apps, such as an app that sells comic books or video tutorials, may find it handy to use PFProductTableViewController to sell the products. By default, each cell is a product, and tapping on a cell initiates the purchase for the product. If the product has associated downloadable content, the download will start when the cell is selected and a progress bar is displayed to indicate the progress of the download.

Note that in order to use this class, you must enter all product information in the Product class via the data browser.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Cloud Code

What is Cloud Code?

Parse's vision is to let developers build any mobile app without dealing with servers. For complex apps, sometimes you just need a bit of logic that isn't running on a mobile device. Cloud Code makes this possible.

Cloud Code is easy to use because it's built on the same JavaScript SDK that powers thousands of apps. The only difference is that this code runs in the Parse Cloud rather than running on a mobile device. When you update your Cloud Code, it becomes available to all mobile environments instantly. You don't have to wait for a new release of your application. This lets you change app behavior on the fly and add new features faster.

Even if you're only familiar with mobile development, we hope you'll find Cloud Code straightforward and easy to use.

Getting Started

On the computer you use for development, you will need to install Parse's command line tool. This will let you manage your code in the Parse Cloud. You can learn more about the features of the command line tool in the Command Line Tool guide.

Installing the Command Line Tool

Mac/Linux

In Mac OS and Linux/Unix environments, you can get the parse tool by running this command:

curl -s https://www.parse.com/downloads/cloud_code/installer.sh | sudo /bin/bash

This installs a tool named "parse" to /usr/local/bin/parse. There's no other junk, so to uninstall, just delete that file. This will also update your command line tool if you already have it installed.

Windows

The Parse command line tool for Windows is available here.

Setting Up Cloud Code

The next step is to create a directory to store the code that you will run in the cloud. The command parse new sets up this directory, and will prompt you to pick which app you are creating Cloud Code for:

$ parse new MyCloudCode
Email: ninja@gmail.com
Password:
1:MyApp
Select an App: 1
$ cd MyCloudCode

Use the email address and password for your Parse account to log in. If you signed up via OAuth and never set a password, you should now set one by editing your account settings. This will create a directory called MyCloudCode in the current directory. Several files are automatically created for you:

-config/
  global.json
-cloud/
  main.js
-public/
  index.html

The config directory contains a JSON configuration file that you shouldn't normally need to deal with, the cloud directory stores your Cloud Code, and the public directory stores any static content that you want to host on Parse. In the cloud directory, you'll typically just be editing main.js, which stores all of your Cloud Code functions. For now, just check that these files were created successfully. If you're using source control, you can check all of these files in.

We recommend using source control to check in all of these files. If you're not already set up with source control, try this tutorial from GitHub. Keep in mind that these files will contain keys you want to keep private.

A Simple Function

Following ancient tradition, let's see how to run the simplest possible function in the cloud. If you take a look at cloud/main.js, you'll see an example function that just returns a string:

Parse.Cloud.define("hello", function(request, response) {
  response.success("Hello world!");
});

To deploy the code from your machine to the Parse Cloud, run:

$ parse deploy

To run this function once it's deployed, run:

ParseCloud.callFunctionInBackground("hello", new HashMap<String, Object>(), new FunctionCallback<String>() {
  void done(String result, ParseException e) {
    if (e == null) {
      // result is "Hello world!"
    }
  }
});
[PFCloud callFunctionInBackground:@"hello"
                   withParameters:@{}
                            block:^(NSString *result, NSError *error) {
   if (!error) {
     // result is @"Hello world!"
   }
}];
PFCloud.callFunctionInBackground("hello", withParameters: nil) {
  (response: AnyObject?, error: NSError?) -> Void in
  let responseString = response as? String
}
$result = ParseCloud::run("hello", []);
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("hello", new Dictionary<string, object>()).ContinueWith(t => {
  var result = t.Result;
// result is "Hello world!"
});
Parse.Cloud.run('hello', {}, {
  success: function(result) {
    // result is 'Hello world!'
  },
  error: function(error) {
  }
});

You should see this response:

{ "result": "Hello world!" }

Congratulations! You have successfully deployed and run Cloud Code.

This is a good time to play around with the deployment cycle. Try changing "Hello world!" to a different string, then deploy and run the function again to get a different result. The whole JavaScript SDK is available in Cloud Code, so there's a lot you can do. We'll go over some examples in more detail below.

Cloud Functions

Let's look at a slightly more complex example where Cloud Code is useful. One reason to do computation in the cloud is so that you don't have to send a huge list of objects down to a device if you only want a little bit of information. For example, let's say you're writing an app that lets people review movies. A single Review object could look like:

{
  "movie": "The Matrix",
  "stars": 5,
  "comment": "Too bad they never made any sequels."
}

If you wanted to find the average number of stars for The Matrix, you could query for all of the reviews, and average the stars on the device. However, this uses a lot of bandwidth when you only need a single number. With Cloud Code, we can just pass up the name of the movie, and return the average star rating.

Cloud functions accept a JSON parameters dictionary on the request object, so we can use that to pass up the movie name. The entire Parse JavaScript SDK is available in the cloud environment, so we can use that to query over Review objects. Together, the code to implement averageStars looks like:

Parse.Cloud.define("averageStars", function(request, response) {
  var query = new Parse.Query("Review");
  query.equalTo("movie", request.params.movie);
  query.find({
    success: function(results) {
      var sum = 0;
      for (var i = 0; i < results.length; ++i) {
        sum += results[i].get("stars");
      }
      response.success(sum / results.length);
    },
    error: function() {
      response.error("movie lookup failed");
    }
  });
});

The only difference between using averageStars and hello is that we have to provide the parameter that will be accessed in request.params.movie when we call the Cloud function. Read on to learn more about how Cloud functions can be called.

Cloud functions can be called from any of the client SDKs, as well as through the REST API (go back to our list of Platforms to switch SDKs). For example, to call the Cloud function named averageStars with a parameter named movie:

HashMap<String, Object> params = new HashMap<String, Object>();
params.put("movie", "The Matrix");
ParseCloud.callFunctionInBackground("averageStars", params, new FunctionCallback<Float>() {
   void done(Float ratings, ParseException e) {
       if (e == null) {
          // ratings is 4.5
       }
   }
});
[PFCloud callFunctionInBackground:@"averageStars"
                   withParameters:@{@"movie": @"The Matrix"}
                            block:^(NSNumber *ratings, NSError *error) {
  if (!error) {
     // ratings is 4.5
  }
}];
PFCloud.callFunctionInBackground("averageRatings", withParameters: ["movie":"The Matrix"]) {
  (response: AnyObject?, error: NSError?) -> Void in
  let ratings = response as? Float
  // ratings is 4.5
}
$ratings = ParseCloud::run("averageRatings", ["movie" => "The Matrix"]);
// $ratings is 4.5
IDictionary<string, object> params = new Dictionary<string, object>
{
    { "movie", "The Matrix" }
};
ParseCloud.CallFunctionAsync<IDictionary<string, object>>("averageStars", params).ContinueWith(t => {
  var ratings = t.Result;
  // ratings is 4.5
});
Parse.Cloud.run('averageStars', { movie: 'The Matrix' }, {
  success: function(ratings) {
    // ratings should be 4.5
  },
  error: function(error) {
  }
});

In general, two arguments will be passed into cloud functions:

  1. request - The request object contains information about the request. The following fields are set:
    1. params - The parameters object sent to the function by the client.
    2. user - The Parse.User that is making the request. This will not be set if there was no logged-in user.

If the function is successful, the response in the client looks like:

{ "result": 4.8 }

If there is an error, the response in the client looks like:

{
  "code": 141,
  "error": "movie lookup failed"
}

beforeSave Triggers

Implementing validation

Another reason to run code in the cloud is to enforce a particular data format. For example, you might have both an Android and an iOS app, and you want to validate data for each of those. Rather than writing code once for each client environment, you can write it just once with Cloud Code.

Let's take a look at our movie review example. When you're choosing how many stars to give something, you can typically only give 1, 2, 3, 4, or 5 stars. You can't give -6 stars or 1337 stars in a review. If we want to reject reviews that are out of bounds, we can do this with the beforeSave method:

Parse.Cloud.beforeSave("Review", function(request, response) {
  if (request.object.get("stars") < 1) {
    response.error("you cannot give less than one star");
  } else if (request.object.get("stars") > 5) {
    response.error("you cannot give more than five stars");
  } else {
    response.success();
  }
});

If response.error is called, the Review object will not be saved, and the client will get an error. If response.success is called, the object will be saved normally. Your code should call one of these two callbacks.

One useful tip is that even if your mobile app has many different versions, the same version of Cloud Code applies to all of them. Thus, if you launch an application that doesn't correctly check the validity of input data, you can still fix this problem by adding a validation with beforeSave.

If you want to use beforeSave for a predefined class in the Parse JavaScript SDK (e.g. Parse.User), you should not pass a String for the first argument. Instead, you should pass the class itself:

Parse.Cloud.beforeSave(Parse.User, function(request, response) {
  if (!request.object.get("email")) {
    response.error("email is required for signup");
  } else {
    response.success();
  }
});

Modifying Objects on Save

In some cases, you don't want to throw out invalid data. You just want to tweak it a bit before saving it. beforeSave can handle this case, too. You just call response.success on the altered object.

In our movie review example, we might want to ensure that comments aren't too long. A single long comment might be tricky to display. We can use beforeSave to truncate the comment field to 140 characters:

Parse.Cloud.beforeSave("Review", function(request, response) {
  var comment = request.object.get("comment");
  if (comment.length > 140) {
    // Truncate and add a ...
    request.object.set("comment", comment.substring(0, 137) + "...");
  }
  response.success();
});

afterSave Triggers

In some cases, you may want to perform some action, such as a push, after an object has been saved. You can do this by registering a handler with the afterSave method. For example, suppose you want to keep track of the number of comments on a blog post. You can do that by writing a function like this:

Parse.Cloud.afterSave("Comment", function(request) {
  query = new Parse.Query("Post");
  query.get(request.object.get("post").id, {
    success: function(post) {
      post.increment("comments");
      post.save();
    },
    error: function(error) {
      console.error("Got an error " + error.code + " : " + error.message);
    }
  });
});

The client will receive a successful response to the save request after the handler terminates, regardless of how it terminates. For instance, the client will receive a successful response even if the handler throws an exception. Any errors that occurred while running the handler can be found in the Cloud Code log.

If you want to use afterSave for a predefined class in the Parse JavaScript SDK (e.g. Parse.User), you should not pass a String for the first argument. Instead, you should pass the class itself.

beforeDelete Triggers

You can run custom Cloud Code before an object is deleted. You can do this with the beforeDelete method. For instance, this can be used to implement a restricted delete policy that is more sophisticated than what can be expressed through ACLs. For example, suppose you have a photo album app, where many photos are associated with each album, and you want to prevent the user from deleting an album if it still has a photo in it. You can do that by writing a function like this:

Parse.Cloud.beforeDelete("Album", function(request, response) {
  query = new Parse.Query("Photo");
  query.equalTo("album", request.object.id);
  query.count({
    success: function(count) {
      if (count > 0) {
        response.error("Can't delete album if it still has photos.");
      } else {
        response.success();
      }
    },
    error: function(error) {
      response.error("Error " + error.code + " : " + error.message + " when getting photo count.");
    }
  });
});

If response.error is called, the Album object will not be deleted, and the client will get an error. If response.success is called, the object will be deleted normally. Your code should call one of these two callbacks.

If you want to use beforeDelete for a predefined class in the Parse JavaScript SDK (e.g. Parse.User), you should not pass a String for the first argument. Instead, you should pass the class itself.

afterDelete Triggers

In some cases, you may want to perform some action, such as a push, after an object has been deleted. You can do this by registering a handler with the afterDelete method. For example, suppose that after deleting a blog post, you also want to delete all associated comments. You can do that by writing a function like this:

Parse.Cloud.afterDelete("Post", function(request) {
  query = new Parse.Query("Comment");
  query.equalTo("post", request.object.id);
  query.find({
    success: function(comments) {
      Parse.Object.destroyAll(comments, {
        success: function() {},
        error: function(error) {
          console.error("Error deleting related comments " + error.code + ": " + error.message);
        }
      });
    },
    error: function(error) {
      console.error("Error finding related comments " + error.code + ": " + error.message);
    }
  });
});

The afterDelete handler can access the object that was deleted through request.object. This object is fully fetched, but cannot be refetched or resaved.

The client will receive a successful response to the delete request after the handler terminates, regardless of how it terminates. For instance, the client will receive a successful response even if the handler throws an exception. Any errors that occurred while running the handler can be found in the Cloud Code log.

If you want to use afterDelete for a predefined class in the Parse JavaScript SDK (e.g. Parse.User), you should not pass a String for the first argument. Instead, you should pass the class itself.

Resource Limits

Timeouts

Cloud functions will be killed after 15 seconds of wall clock time. beforeSave, afterSave, beforeDelete, and afterDelete functions will be killed after 3 seconds of run time. If a Cloud function or a beforeSave/afterSave/beforeDelete/afterDelete function is called from another Cloud Code call, it will be further limited by the time left in the calling function. For example, if a beforeSave function is triggered by a cloud function after it has run for 13 seconds, the beforeSave function will only have 2 seconds to run, rather than the normal 3 seconds. If you need additional time to perform operations in Cloud Code, consider using a background job.

Network requests

Network requests that are still in progress after success or error are called will be canceled. In general, you should wait for all network requests to finish before calling success. For afterSave functions and afterDelete functions, which don't call success/error, Cloud Code will wait for all network requests to finish.

Here's an example where calling response.success will cancel an outstanding query, leading to unexpected results:

Parse.Cloud.define("ThisFunctionWillNotReturnAllDataAsExpected", function(request, response) {
  var results = "Retrieved all Posts:\n"
  var query = new Parse.Query("Post");

  // This query.find() is unlikely to finish before response.success() is called.
  query.find().then(function(posts) {
    for (var i = 0; i < posts.length; i++) {
      results += posts[i].get('title') + "\n";
    }  
  });

  response.success(results); // Response: "Retrieval all Posts:\n"
});

This is a common mistake that can be easily avoided. Make sure that you only call success once all of your network queries have returned data, such as in the following example:

Parse.Cloud.define("ThisFunctionWillReturnAllData", function(request, response) {
  var results = "Retrieved all Posts:\n"
  var query = new Parse.Query("Post");

  query.find().then(function(posts) {
    for (var i = 0; i < posts.length; i++) {
      results += posts[i].get('title') + "\n";
    }

    // success has been moved inside the callback for query.find()
    response.success(results);
  }, function(error) {
    // Make sure to catch any errors, otherwise you may see a "success/error not called" error in Cloud Code.
    response.error("Could not retrieve Posts, error " + error.code + ": " + error.message);
  });

});

Logging from Cloud Code

If you want to log a message to the log files displayed by parse log, you can use console.log, console.error, or console.warn. Both console.error and console.warn will write to the error log.

Parse.Cloud.define("Logger", function(request, response) {
  console.log(request.params);
  response.success();
});

Cloud functions may log up to 100 messages per request. Log lines are limited to 1KB in size, after which they are truncated.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Advanced Cloud Code

Networking

Cloud Code allows sending HTTP requests to any HTTP Server using Parse.Cloud.httpRequest. This function takes an options object to configure the call. There is a limit of 8 concurrent httpRequests per Cloud Code request, and additional requests will be queued up.

A simple GET request would look like:

Parse.Cloud.httpRequest({
  url: 'http://www.parse.com/'
}).then(function(httpResponse) {
  // success
  console.log(httpResponse.text);
},function(httpResponse) {
  // error
  console.error('Request failed with response code ' + httpResponse.status);
});

Parse.Cloud.httpRequest returns a Promise that will be resolved on a successful http status code; otherwise the Promise will be rejected. In the above example, we use then() to handle both outcomes.

A GET request that specifies the port number would look like:

Parse.Cloud.httpRequest({
  url: 'http://www.parse.com:8080/'
}).then(function(httpResponse) {
  console.log(httpResponse.text);
}, function(httpResponse) {
  console.error('Request failed with response code ' + httpResponse.status);
});

Valid port numbers are 80, 443, and all numbers from 1025 through 65535.

Query Parameters

You can specify query parameters to append to the end of the url by setting params on the options object. You can either pass a JSON object of key value pairs like:

Parse.Cloud.httpRequest({
  url: 'http://www.google.com/search',
  params: {
    q : 'Sean Plott'
  }
}).then(function(httpResponse) {
  console.log(httpResponse.text);
}, function(httpResponse) {
  console.error('Request failed with response code ' + httpResponse.status);
});

or as a raw String like this:

Parse.Cloud.httpRequest({
  url: 'http://www.google.com/search',
  params: 'q=Sean Plott'
}).then(function(httpResponse) {
  console.log(httpResponse.text);
}, function(httpResponse) {
  console.error('Request failed with response code ' + httpResponse.status);
});

Setting Headers

You can send HTTP Headers by setting the header attribute of the options object. Let's say you want set the Content-Type of the request, you can do:

Parse.Cloud.httpRequest({
  url: 'http://www.example.com/',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
}).then(function(httpResponse) {
  console.log(httpResponse.text);
}, function(httpResponse) {
  console.error('Request failed with response code ' + httpResponse.status);
});

Sending a POST Request

You can send a post request by setting the method attribute of the options object. The body of the POST can be set using the body. A simple example would be:

Parse.Cloud.httpRequest({
  method: 'POST',
  url: 'http://www.example.com/create_post',
  body: {
    title: 'Vote for Pedro',
    body: 'If you vote for Pedro, your wildest dreams will come true'
  }
}).then(function(httpResponse) {
  console.log(httpResponse.text);
}, function(httpResponse) {
  console.error('Request failed with response code ' + httpResponse.status);
});

This will send a post to http://www.example.com/create_post with body that is the url form encoded body attribute. If you want the body to be JSON encoded, you can instead do:

Parse.Cloud.httpRequest({
  method: 'POST',
  url: 'http://www.example.com/create_post',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: {
    title: 'Vote for Pedro',
    body: 'If you vote for Pedro, your wildest dreams will come true'
  }
}).then(function(httpResponse) {
  console.log(httpResponse.text);
}, function(httpResponse) {
  console.error('Request failed with response code ' + httpResponse.status);
});

To ensure that your HTTP request body is encoded correctly, please always include the charset in your Content-Type header.

Following Redirects

By default, Parse.Cloud.httpRequest does not follow redirects caused by HTTP 3xx response codes. You can use the followRedirects option to change this behavior to follow redirects:

Parse.Cloud.httpRequest({
  url: 'http://www.example.com/',
  followRedirects: true
}).then(function(httpResponse) {
  console.log(httpResponse.text);
}, function(httpResponse) {
  console.error('Request failed with response code ' + httpResponse.status);
});

The Response Object

The response object passed into the success and error will contain:

Modules

Cloud Code supports breaking up JavaScript code into modules. You can check out this tutorial for an in depth look at creating your own. In order to avoid unwanted side effects from loading modules, Cloud Code's modules work similarly to CommonJS modules. When a module is loaded, the JavaScript file is loaded, the source executed and the global exports object is returned. For example, if cloud/name.js has the following source:

var coolNames = ['Ralph', 'Skippy', 'Chip', 'Ned', 'Scooter'];
exports.isACoolName = function(name) {
  return coolNames.indexOf(name) !== -1;
}

and cloud/main.js contains:

var name = require('cloud/name.js');
name.isACoolName('Fred'); // returns false
name.isACoolName('Skippy'); // returns true;
name.coolNames; // undefined.

name contains a function called isACoolName. The path used by require is relative to the root directory of your Parse project. Only modules in the cloud/ directory can be loaded.

Cloud Code Webhooks

Webhooks allow you to write your server-side logic in your own environment with any tools you wish to use. This can be useful if you want to use a language other than JavaScript, host it yourself for improved testing capabilities, or if you require a specialized library or technology not available in Cloud Code. Webhooks are currently available for beforeSave, afterSave, beforeDelete, afterDelete, and Cloud functions. To specify a new webhook, you can use the Parse Dashboard in the Webhooks section located under Core.

We've written an example Cloud Code Webhooks server, in Express.js, which you can find on Github: CloudCodeWebhooks-Express.

Cloud Function Webhooks

A webhook request for a Cloud function will contain the following parameters:

To respond to this request, send a JSON object with the key error or success set. In the case of success, send back any data your client will expect; or simply true if your client doesn't require any data. In the case of error, the value provided should be the error message you want to return.

To create a webhook for a Cloud function, start by writing the function's code on your own server. Here's the simple hello world function written in a Rails environment.

# We need to disable CSRF protection for webhooks to work. Instead we
# use the webhook key to prove authenticity. protect_from_forgery :except => :index

def index
  # Ensure the request is authorized. You can find this key on your app's settings page
  # and you should ALWAYS validate it in your request.
  if request.headers['X-Parse-Webhook-Key'] !== @webhook_key
    return render :json => { :error => "Request Unauthorized"}
  end

  # Check the function name and return a message if it's correct
  if params[:functionName] == "helloWorld"
    return render :json => { :success => "Hello World!" }
  end

  # Return an error if it's not the function we expected 
  return render :json => { :error => "Unknown function"}
end

Here's an example of the JSON data that would be sent in the request to this webhook:

// Sent to webhook 
{
  "master": false, 
  "user": { 
    "createdAt": "2015-03-24T20:19:00.542Z", 
    "objectId": "lValKpphWN", 
    "sessionToken": "orU3ClA7sqMIN8g4KtmLe7eDM", 
    "updatedAt": "2015-03-24T20:19:00.542Z", 
    "username": "Matt" 
  }, 
  "installationId": "b3ab24c6-2282-69fa-eeea-c1b36ea497c2", 
  "params": {}, 
  "functionName": "helloWorld" 
}

This response would indicate a success in the webhook:

// Returned from the webhook on success
{ "success": "Hello World!" }

This response would indicate an error in the webhook:

// Returned from the webhook on error 
{ "error": "Error message >:(" }

You can activate this webhook from the Dashboard UI.

Once the webhook is set, you can call it from any of our SDKs or from the REST API, the same way you would a normal Cloud function.

Here's a more complex example where we use a webhook to perform some task for our billing pipeline. We'll use the popular resque gem to enqueue a job that handles billing the given user. For this example, the function is named chargeCustomer and it should always be called with the master key.

# We need to disable CSRF protection for webhooks to work. Instead we 
# use the webhook key to prove authenticity. 
protect_from_forgery :except => :index

def index 
  # Ensure the request is validated 
  if request.headers['X-Parse-Webhook-Key'] !== @webhook_key 
    return render :json => { :error => "Request Unauthorized"} 
  end

  # Check the function name 
  if params[:functionName] == "chargeCustomer" && params[:master] == true 
    # extract the custom parameters sent with the function 
    custom_params = params[:params] 
    user_id = custom_params["userObjectId"]

    # enqueue a resque job to bill the user 
    Resque.enqueue(BillingJob, user_id)

    # return a json object of this billing info 
    return render :json => { :success => "User billed!" } 
  end

  return render :json => { :error => "Unknown function"} 
end

Here's an example of the JSON data that would be sent in the request to this webhook:

// Sent to webhook 
{ 
  "master": true, 
  "installationId": "b3ab24c6-2282-69fa-eeea-c1b36ea497c2", 
  "params": { "userObjectId": "6eaI2sTgH6" }, 
  "functionName": "chargeCustomer" 
}

This response would indicate a success in the webhook:

// Returned from the webhook on success 
{ "success": "User billed!" }

Set your webhook from the Dashboard UI. After that, it's available from all SDKs and the REST API the same way you would a normal Cloud function

Webhooks are great when you want to use a specialized technology not available on Parse's Cloud Code. In this case we made use of an open source library and integrated with a separate data source where our billing info might be stored for legacy reasons.

beforeSave Webhooks

Let's write a beforeSave trigger to truncate movie review comments that are more than 140 characters long using our own Rails server and a webhook.

For triggers, the following parameters are sent to your webhook.

To respond to a beforeSave request, send a JSON object with the key error or success set. This is the same as for Cloud functions, but there's an extra capability with beforeSave triggers. By returning an error, you will cancel the save request and the object will not be stored on Parse. You can also return a JSON object in this following format to override the values that will be saved for the object:

{ 
  "className": "AwesomeClass", 
  "existingColumn": "sneakyChange", 
  "newColumn": "sneakyAddition" 
}

Let's recreate our trigger to truncate moview review comments that are longer than 140 characters.

# We need to disable CSRF protection for webhooks to work. Instead we 
# use the webhook key to prove authenticity. 
protect_from_forgery :except => :reviews

def reviews 
  if request.headers['X-Parse-Webhook-Key'] != @webhook_key 
    return render :json => { :error => "Request Unauthorized"} 
  end

  review = params[:object] 
  if params[:triggerName] == "beforeSave" && review["className"] == "Review" 
    # truncate the object and return the new data 
    if review["comment"].length > 140 
      review["comment"] = review["comment"].truncate(140) 
      return render :json => { :success => review } 
    end

    # if the comment is ok we just return a success 
    return render :json => { :success => true } 
  end

  return render :json => { :error => "Unknown trigger"}
end

Here's an example of the JSON data that would be sent in the request to this webhook:

// Sent to webhook 
{ 
  "master": false, 
  "user": { 
    "createdAt": "2015-03-24T20:19:00.542Z", 
    "objectId": "lValKpphWN", 
    "sessionToken": "orU3ClA7sqMIN8g4KtmLe7eDM", 
    "updatedAt": "2015-03-24T20:19:00.542Z", 
    "username": "Matt" 
  }, 
  "installationId": "b3ab24c6-2282-69fa-eeea-c1b36ea497c2", 
  "triggerName": "beforeSave", 
  "object": { 
    "className": "Comment", 
    "comment": "A very long comment that will be truncated to be just 140 characters. I sure love using Parse, it's just so easy to get started :)! Hopefully that part doesn't get truncated :/" 
  } 
}

This response would indicate a success in the webhook:

// Returned from the webhook on success
{ 
  "success": { 
    "className": "Comment", 
    "comment": "A very long comment that will be truncated to be just 140 characters. I sure love using Parse, it's just so easy to get started :)! Hopef..."
  } 
}

afterSave Webhooks

Like we've seen in Cloud Code, it's also possible to run some code after an object has been saved using a webhook. The parameters sent to your webhook are the same as for beforeSave triggers but we'll repeat them here for clarity.

No response is required for afterSave triggers.

Let's take the same example we created in Cloud Code in the last chapter; keeping track of the number of comments on a blog post. But instead of storing the number in our Parse database, we'll store the count in a separate data source accessible by our Rails app. This could be useful if you're storing data that will be used to run custom analysics instead of being served to your users through a client.

# We need to disable CSRF protection for webhooks to work. Instead we 
# use the webhook key to prove authenticity. 
protect_from_forgery :except => :comments

def comments 
  if request.headers['X-Parse-Webhook-Key'] != @webhook_key 
    return render :nothing => true 
  end

  comment = params[:object] 
  if params[:triggerName] == "afterSave" && comment["className"] == "Comment" 
    post = comment["post"] 
    @post_model = Post.where("id = #{post["objectId"]}") 
    @post_model.increment(:comments_count, 1) 
    @post_model.save! 
    return render :nothing => true 
  end 

  render :nothing => true
end

Here's an example of the JSON data that would be sent in the request to this webhook:

// Sent to webhook 
{ 
  "master": false, 
  "user": { 
    "createdAt": "2015-03-24T20:19:00.542Z", 
    "objectId": "lValKpphWN", 
    "sessionToken": "orU3ClA7sqMIN8g4KtmLe7eDM", 
    "updatedAt": "2015-03-24T20:19:00.542Z", 
    "username": "Matt" 
  }, 
  "installationId": "b3ab24c6-2282-69fa-eeea-c1b36ea497c2", 
  "triggerName": "afterSave", 
  "object": { 
    "objectId": "zPnDyvj0vd", 
    "className": "Comment", 
    "createdAt": "2015-03-25T00:00:57.055Z", 
    "updatedAt": "2015-03-25T00:00:57.055Z", 
    "post": { 
      "__type": "Pointer", 
      "className": "Post", 
      "objectId": "jsUd72Sd2l" 
    } 
  } 
}

beforeDelete Webhooks

You also use webhooks for beforeDelete triggers. The parameters sent to your webhook are the same as for beforeSave and afterSave triggers but we'll repeat them here for clarity.

Just like for Cloud functions, to respond to a beforeDelete request, send a JSON object with the key error or success set. Returning an error will cancel the delete and the object will remain in your database.

As an example, let's use this trigger to prohibit a user from deleting or creating a new blog posts if they haven't paid their bill. We'll assume the billing information is currently stored in a SQL database only accessible from our Rails server. We'll use both the beforeDelete and the beforeSave triggers to disable all modifications to this class.

# We need to disable CSRF protection for webhooks to work. Instead we 
# use the webhook key to prove authenticity. 
protect_from_forgery :except => :posts

def posts 
  if request.headers['X-Parse-Webhook-Key'] != @webhook_key 
    return render :json => { :error => "Request Unauthorized"} 
  end

  post = params[:object] 
  if (params[:triggerName] == "beforeDelete" || params[:triggerName] == "beforeSave") && post["className"] == "Post" 
    @user = User.find(post['user']) 
    if !@user.paid_up 
      return render :json => { :error => "You have outstanding charges on your account. Please update your credit card information before proceeding." } 
    end 

    return render :json => { :success => true } 
  end
  return render :json => { :error => "Unknown trigger"}
end

Here's an example of the JSON data that would be sent in the request to this webhook:

// Sent to webhook 
{ 
  "master": false, 
  "user": { 
    "createdAt": "2015-03-24T20:19:00.542Z", 
    "objectId": "lValKpphWN", 
    "sessionToken": "orU3ClA7sqMIN8g4KtmLe7eDM", 
    "updatedAt": "2015-03-24T20:19:00.542Z", 
    "username": "Matt" 
  }, 
  "installationId": "b3ab24c6-2282-69fa-eeea-c1b36ea497c2", 
  "triggerName": "beforeDelete", 
  "object": { 
    "objectId": "jsUd72Sd2l", 
    "className": "Post", 
    "createdAt": "2015-03-25T00:00:57.055Z", 
    "updatedAt": "2015-03-25T00:00:57.055Z"
  } 
}

This response would indicate a success in the webhook:

// Returned from the webhook on success 
{ "success": true }

As with previous examples, for this example to work you would also need to set up the webhooks in the Dashboard for your app.

afterDelete Webhooks

The afterDelete trigger is also accessible via webhooks. The parameters sent to your webhook are the same as for other triggers but we'll repeat them here for clarity.

No response is required for afterDelete triggers.

In our webhooks example for the afterSave trigger, we updated a count in our external SQL database to track the number of comments on a post. In this example, let's decrement this count when a comment is deleted.

# We need to disable CSRF protection for webhooks to work. Instead we 
# use the webhook key to prove authenticity. 
protect_from_forgery :except => :comments

def comments 
  if request.headers['X-Parse-Webhook-Key'] != @webhook_key 
    return render :nothing => true 
  end

  comment = params[:object] 
  if params[:triggerName] == "afterDelete" && comment["className"] == "Comment" 
    @post_model = Post.where("id = #{comment['post']}") 
    @post_model.decrement(:comments_count, 1) 
    @post_model.save! 
    return render :nothing => true 
  end

  render :nothing => true
end

Here's an example of the JSON data that would be sent in the request to this webhook:

// Sent to webhook 
{ 
  "master": false, 
  "user": { 
    "createdAt": "2015-03-24T20:19:00.542Z", 
    "objectId": "lValKpphWN", 
    "sessionToken": "orU3ClA7sqMIN8g4KtmLe7eDM", 
    "updatedAt": "2015-03-24T20:19:00.542Z", 
    "username": "Matt" 
  }, 
  "installationId": "b3ab24c6-2282-69fa-eeea-c1b36ea497c2", 
  "triggerName": "afterDelete", 
  "object": { 
    "objectId": "zPnDyvj0vd", 
    "className": "Comment", 
    "createdAt": "2015-03-25T00:00:57.055Z", 
    "updatedAt": "2015-03-25T00:00:57.055Z", 
    "post": {
      "__type": "Pointer", 
      "className": "Post", 
      "objectId": "jsUd72Sd2l" 
    } 
  } 
}

After setting up your webhook in the Dashboard UI, you'll be acurately decrementing comment counts!

Resource Limits

  1. All webhooks are limited to 30 seconds. Parse will time out the request after this time limit.
  2. Cloud Code Webhooks require an HTTPS connection. Your server must have a valid SSL certificate. Self-signed certificates will not be accepted, for your security.
  3. In cases where you define a webhook for a function or a trigger that you've also implemented in Cloud Code, Parse will only call your defined webhook. Priority will always be given to your webhook over Cloud Code.
  4. In order to secure these requests and prevent others from executing this code on your server, we'll send a secret key known only to you and Parse in the X-Parse-Webhook-Key header. You should always check this value against your WebhookKey to authenticate that the webhook request is coming from Parse. You can find your Webhook key in the Keys section of your app dashboard.

Background Jobs

Parse allows you to set up jobs that run in the background. Background Jobs are useful for long running tasks such as integrating with external sites where the response time could be slow, or sending out batched push notifications. If you commonly encounter timeout errors running Cloud functions then you should consider using a Background Job.

There are a few constraints that you need to keep in mind when using Background Jobs:

Writing a Background Job

Writing a Background Job is similar to writing a Cloud function. Say you want to run a user migration job after adding a plan field to the Parse.User object. Your code would look like this:

Parse.Cloud.job("userMigration", function(request, status) {
  // Set up to modify user data
  Parse.Cloud.useMasterKey();
  var counter = 0;
  // Query for all users
  var query = new Parse.Query(Parse.User);
  query.each(function(user) {
      // Update to plan value passed in
      user.set("plan", request.params.plan);
      if (counter % 100 === 0) {
        // Set the  job's progress status
        status.message(counter + " users processed.");
      }
      counter += 1;
      return user.save();
  }).then(function() {
    // Set the job's success status
    status.success("Migration completed successfully.");
  }, function(error) {
    // Set the job's error status
    status.error("Uh oh, something went wrong.");
  });
});

As with other Cloud Functions, you should handle success and error conditions. For Background Jobs, you do this by calling either status.success() or status.error() when your function completes. Your job execution status will then be set to completed. If you don't call either of these methods, your job will time out in 15 minutes. You can optionally set a progress message while the job is executing by calling status.message(). If you call status.message() after status.success(), your progress message will be ignored.

Once you've deployed your code, you can test the job by running the following command, with your master key. Note that Background Jobs cannot be triggered from the client SDK. It is only available through the REST API.

curl -X POST \
  -H "X-Parse-Application-Id: $PARSE_APPLICATION_ID" \
  -H "X-Parse-Master-Key: $PARSE_MASTER_KEY" \
  -H "Content-Type: application/json" \
  -d '{"plan":"paid"}' \
  https://api.parse.com/1/jobs/userMigration

Setting up a Schedule

Once you've deployed your Background Job code, it can be scheduled in the Dashboard under the Cloud Code tab. The Scheduled Jobs pane lists all currently scheduled jobs and allows you to schedule a new one. To add an entry to the job schedule, select a currently deployed job then specify a description, any required parameters, the start time, and the frequency. Once a job has been scheduled you can run it on demand by clicking Run Now. You may also delete an entry in the job schedule. The Job Status pane lists the results of your job executions. You can see when a job started, its most recent status message, and whether it has completed.

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Cloud Code Hosting

Parse Hosting provides you with the tools to host static and dynamic websites. You can upload arbitraty static web content or create dynamic web apps, using the JavaScript SDK on the client side and Cloud Code plus Express on the server side. This allows you to create companion web apps for your native app, landing pages for your mobile app, or even host Unity Web Player binaries.

On the computer you use for development, you will need to install Parse's command line tool to manage your website in the Parse Cloud. Take a look at the Cloud Code guide or the Command Line Tool guide for help getting started.

You will need at least version 1.1.0 of the command line tool.

A Simple Website

Hosting static content using Parse is easy. Everything in the public directory will be hosted at your-custom-subdomain.parseapp.com. This directory sits alongside the cloud and config directories.

To deploy a Hello World website, simply do:

$ echo "Hello World" > public/index.html
$ parse deploy

To access the website you've deployed you need to set up a subdomain.

Choosing a Subdomain Name

To access your hosted content, you will first need to select a ParseApp subdomain. You can set your subdomain in the "Web Hosting" section of your app's settings. There will be a field for you to enter a ParseApp name. The subdomain name is case-insensitive, and unlike your app name, it must be unique across the entire Parse system. It may consist of 3 to 20 alphanumeric characters and dashes, and may not start or end with a dash. When you select a unique subdomain name, a checkmark is displayed to indicate that is is not yet taken.

Let's say you chose at-the-movies as the subdomain name for your website, you can now access it at the root URL at-the-movies.parseapp.com. If you upload another hosted file from public/images/background.png, then it can be accessed by pointing your browser at at-the-movies.parseapp.com/images/background.png.

Uploading Constraints

There are a few constraints for hosted files:

You are free to upload hosted content of any type you want. Parse will infer the content type from each file's extension.

Custom Domain Names

Users can also host content at a custom domain name. If you have chosen the ParseApp name at-the-movies and want to host your content at www.example.com, it requires three steps:

  1. Demonstrate that you control the DNS entries for www.example.com. You can do this by adding a CNAME to at-the-movies.parseapp.com from either www.example.com or [your_host_name_key].www.example.com. Your host name key is a 12-character string that you can find in the "Web Hosting" section in your app's settings. It can take anywhere from 15 minutes to several hours for a new DNS entry to be propagated, and the next step cannot be completed until this happens. If you are currently hosting a website at www.example.com, you will probably want to use the host name key method, otherwise your website might experience downtime for users who see the new DNS entry before you complete the next step.
  2. After your new DNS entry been propagated, you can set your host name to www.example.com in your app's hosting settings. If the first step was successful, a checkmark should show up. Otherwise, an error message will tell you what went wrong.
  3. If you verified ownership via the host name key, you will still need to add a CNAME from www.example.com to at-the-movies.parseapp.com to begin sending traffic to your hosted app.

After completing these steps, www.example.com will serve the same content as at-the-movies.parseapp.com.

If you want to serve content at an apex domain like example.com then you might have trouble with the steps above, because root domains generally don't support CNAME records. To support this situation, Parse offers a service which will redirect traffic from root domains like example.com to the www.example.com subdomain. To use this service, complete the steps above using a www-prefixed domain like www.example.com, and then create A records from example.com to one or both of the following IP addresses:

A records can be created in the settings page of your domain name service provider. After creating these A records, requests to example.com will result in a 301 (permanent) redirect to www.example.com while preserving the request path.

If you visit your hosted site over HTTPS using your custom domain, you might see a warning that the website is serving content using an SSL certificate belonging to *.parseapp.com. If you have a SSL certificate belonging to your custom domain, you can fix these warnings by uploading the public certificate file and the private key file on the "Web Hosting" section in your app's settings. If your domain's public certificate requires intermediate certificates, then you should append your public certificate, intermediate certificates, and the root certificate into a single file (in that order), and upload it as the "SSL Public Certificate" in your app settings. In 10-30 minutes, your certificate will be propagated to the Parse hosting servers and served to users who visit your hosted site over HTTPS.

Dynamic Websites

You can use Cloud Code and Express to build multi-page dynamic web apps. With the Express framework, you have many powerful tools at your fingertips, such as request routing, cookie handling, and template rendering. With Cloud Code, you have access to functionality such as interacting with Parse data and sending HTTP requests.

With Parse, you have a choice of building either a multi-page web app with Express, or a single-page Backbone app with the Parse JavaScript SDK on the client side. The Express approach has the advantage that your website can be crawled by search engines, while the client-side Backbone approach may result in more responsive apps. You can find details about Express and Cloud Code in our Express API docs.

Express can help you get your app up and running quickly, but if you prefer a lower-level Node.js-like HTTP interface, we have that too. For more details, please see our HTTP interface API docs. If you choose to use Express or Node.js, you'll first need to delete public/index.html so that requests can get through to your custom handler functions.

In this guide, we'll focus on building web apps with the Express API.

Creating a Web App

After you get Parse Hosting set up, you can generate a starter web app by typing the following inside your parse project folder.

$ parse generate express

This command creates the following directory structure inside your cloud folder. It will not touch your existing main.js file.

-cloud/
  app.js
  -views/
    hello.ejs
  main.js (not touched)

Next, you need to add the following line at the top of your main.js. This makes sure that the code in app.js is loaded.

require('cloud/app.js');

Then, run parse deploy to deploy your web app. After deploying, you should find your web app at your-custom-subdomain.parseapp.com/hello. We'll next go over this sample app in detail.

Sample Web App

Let's go over the starter web app to get an idea what Express can do for us. If you haven't created the starter app yet, you can create one using these instructions.

The top-level entry point for an Express app is app.js, where the app is initialized, and the request paths are hooked up to corresponding logic through the Express routing API. You must require this file from main.js because Cloud Code starts at main.js when it loads your JavaScript. We recommend that you put your Cloud Functions in main.js, and put all Express-related code in app.js.

In your sample app, app.js should look like this:

// These two lines are required to initialize Express.
var express = require('express');
var app = express();

// Global app configuration section
app.set('views', 'cloud/views');  // Specify the folder to find templates
app.set('view engine', 'ejs');    // Set the template engine
app.use(express.bodyParser());    // Middleware for reading request body

// This is an example of hooking up a request handler with a specific request
// path and HTTP verb using the Express routing API.
app.get('/hello', function(req, res) {
  res.render('hello', { message: 'Congrats, you just set up your app!' });
});

// This line is required to make Express respond to http requests.
app.listen();

In the global app configuration section at the top, we specify some app settings and initialize the Express middleware. App settings include specifying a templating engine for rendering your web pages, and where to find your template source files. Express middleware are optional components that preprocess the incoming request. The middleware specified in this section apply to all request paths.

The sample app also has a cloud/views folder, containing an EJS template file (hello.ejs). In this template, the message variable will be replaced by the value specified in the res.render() line in app.js.

Handling Requests

Let's look at a simple request handler that reads the request text, and responds with a message including the request text.

app.post('/echo', function(req, res) {
  res.set('Content-Type', 'text/plain');
  res.send('echoing: ' + req.body.message);
});

Every request handler starts with app.VERB, where the VERB could be any of the standard HTTP verbs, such as get, post, put, or delete. This tells Express what type of HTTP request this handler should respond to.

Next, the '/echo' parameter specifies what url path (also known as route) that this request handler should respond to. Then, we specify a function that takes in a request and response object to perform the request handling logic. As long as we include the express.bodyParser middleware, the req.body should be populated with input data. For example, if the raw request body is { "message": "hi" }, then req.body.message above will have the value 'hi'. Finally, the res.send() tells Express to populate the response object with the specified string.

Express Middleware

Middleware are modules that process the request before it reaches your request handler. These components convert a raw HTTP request into a request object that you can easily work with in your request handler. Cloud Code supports the following Express-provided middleware:

In addition, we've provided the following custom middleware:

You can add middleware to your app with app.use(). The standard Express middleware are functions, so make sure you call them accordingly (e.g. app.use(express.csrf()). You should add your app's middleware before registering any request handlers with app.VERB().

Please follow the above order when configuring Express middleware in the global app configuration section. You may leave out any middleware that you don't need. The order is important because later middleware may depend on the data created by earlier ones.

Rendering Templates

Templates are a great way to dynamically generate web content, and reduce code duplication. Cloud Code provides modules for the EJS and Jade template engines.

You specify the template engine in the global app configuration section with app.set('view engine', ENGINE_NAME), where ENGINE_NAME can be either 'ejs' or 'jade'. The template file in the cloud/views folder should have an extension matching ENGINE_NAME. The sample app's template looks like this in EJS (hello.ejs) or Jade (hello.jade):

// Using EJS syntax
<!DOCTYPE html>
<html>
  <head>
    <title>Sample App</title>
  </head>
  <body>

# Hello World

<%%= message %>

  </body>
</html>
// Using Jade syntax
doctype 5
html
  head
    title Sample App
  body
    h1 Hello World
    p= message

You can find more information about the syntax for each template engine at the homepages for EJS and Jade.

You render templates by calling res.render(). The first argument is the template file name. If it does not have a file extension, Express will look for the file with the extension matching your app's template engine setting. The second argument is a JSON object that contains all the variables in the template and their corresponding values. Each variable in the template serves as a placeholder, and is replaced by its actual value when you render the template.

Getting User Input

Getting user input is easy with Express in Cloud Code. You can create a form element in a template to allow the user to type some text, and then add a request handler for the request issued by submitting the form.

Let's add a simple form to our sample app template. Please replace hello.ejs or hello.jade with the following code:

// Using EJS syntax
<!DOCTYPE html>
<html>
  <head>
    <title>Sample App</title>
  </head>
  <body>

# Hello World

    <p><%%= message %>

    <form method="post" action="/hello">

        <input name="message"></input>
        <input class="button" type="submit" value="Update Greeting">

    </form>
  </body>
</html>
// Using Jade syntax
doctype 5
html
  head
    title Sample App
  body
    h1 Hello World
    p= message
    form(method="post", action="/hello")
      p
        input(type="text", name="message")
        input(type="submit", name="submit", value="Update Greeting")

Then, we need to add a request handler for the HTTP post request in app.js.

app.post('/hello', function(req, res) {
  res.render('hello', { message: req.body.message });
});

Suppose the user types "hi" into the text box, and then clicks the "Update Greeting" button. The form will send an HTTP post request to the url http://example.parseapp.com/hello, with the request body message=hi. The express.bodyParser middleware will read the request body and set req.body.message to 'hi'. The request then triggers the above request handler because the HTTP verb and url path both match. Finally, the request handler renders the hello.ejs template by inserting 'hi' into the placeholder for the message variable.

User Session Management

You can add Parse.User authentication and session management to your Express app using the parseExpressCookieSession middleware. You just need to call Parse.User.logIn() in Cloud Code, and this middleware will automatically manage the user session for you.

You can use a web form to ask for the user's login credentials, and log in the user in Cloud Code when you receive data from this form. After you call Parse.User.logIn(), this middleware will automatically set a cookie in the user's browser. During subsequent HTTP requests from the same browser, this middleware will use this cookie to automatically set the current user in Cloud Code. This will make ACLs work properly in Cloud Code, and allow you to retrieve the entire current user object if needed. Finally, when you log out a user in Cloud Code by calling Parse.User.logOut(), this middleware will automatically remove the browser cookie. For sample app code, please see the documentation for this middleware.

When you work with user data, you should use HTTPS whenever possible. To protect your app and your users, the parseExpressCookieSession middleware requires you to use HTTPS. For your convenience, we also provide a parseExpressHttpsRedirect middleware for redirecting all HTTP requests to HTTPS. Please see its documentation for details.

Static Content

Your Express app can sit side-by-side with any static content you deployed from your public folder. When a request goes to a URL of your subdomain, Parse will first look for a matching file in the public directory. If there is no match, then Parse will invoke any Express request handlers that you have registered in Cloud Code. If there is still no match, Parse will render a "404 Not Found" page.

If you are using Express with static content, we recommend the following directory structure for your project.

-cloud/
  main.js            Cloud Code functions, require cloud/app.js here
  app.js             Express app configuration and request handling logic
  -views/            View template files that Express needs to render
    hello.ejs
-public/
  example.html       Static HTML files
  favicon.ico        Your favicon logo
  -stylesheets/      CSS stylesheets
    style.css

Logging

If you want to log a message to the log files displayed by parse log, you can use console.log, console.error, or console.warn. Both console.error and console.warn will write to the error log.

app.post('/hello', function(req, res) {
  console.log("New message: " + req.body.message);
  res.render('hello', { message: req.body.message });
});

Development vs Production

You can use your development app to try out new code, and the production app to run your app that you distribute to the public.

Adding a New App to a Project

You will need to have multiple apps linked to your project. parse new will link the first app to the project. You can add more apps by running parse add [alias], like so:

$ parse add production
Email: pirate@gmail.com
Password:
1:PiecesOfEightCounterProd
2:PiecesOfEightCounterDev
Select an App: 1

The example above links the PiecesOfEightCounterProd app to your project. It also creates an alias to new app called production that provides a shorthand way to reference the app.

Developing your Website

While developing new code, you can use the develop command to have the Parse command line tool continuously check for updates to your project and upload your changes. The command looks like:

$ parse develop development
E2013-11-21T01:05:56.257Z] Deploy failed with error:Error: Uncaught SyntaxError: Unexpected token ; in app.js:30
    at main.js:1:1
I2013-11-21T01:06:21.504Z] Deployed v172 with triggers:
  Cloud Functions:
    hello

Note that for the develop command you need to be explicit about the app that you are going to push new changes to. This avoids accidentally running develop on your production app, potentially deploying untested code to it. The command line tool will upload code changes and display new log messages, until you hit Ctrl-C.

Deploying Code to Production

After you are done testing and updating your code, you can deploy the code to production by passing the production app to the the deploy command, like so:

$ parse deploy production
New release is named v2
Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Cloud Code Modules

Cloud Modules are the easiest way to integrate your Parse app with third-party services and libraries. Read on to learn how to add amazing features to your Parse app, from text messaging to email.

Cloud Modules work just like the JavaScript modules you can create yourself but they are readily available to everyone. You just add require('cloudModuleName') to your Cloud Code and you are ready to go! This guide will help you get started with the current set of available Cloud Modules. If you don't see the service you're interested in, you can take a look at our tutorial on how to create your own modules to integrate with your favorite APIs.

App Links

We provide Express middleware for generation of App Link metadata, which allows other apps to deep link into your app based on content on your website. You can check out the full documentation of App Links here. To use App Links, you require both express and applinks-metatag modules and create an Express app.

var Express = require('express');
var AppLinks = require('applinks-metatag');
var app = Express();

The middleware accepts an array of JavaScript objects that must contain a platform name (e.g. "ios", "iphone", "android", or "windows_phone") and a set of fields relevant to the platform as specified on the App Links official website. You can also provide a function that will generate the same metadata based upon the request, so that you can provide different app links data for each page.

app.use(AppLinks([{
  platform: "ios",
  url: "anypic://",
  app_name: "AnyPic"
}, {
  platform: "android",
  url: "anypic://",
  package: "com.parse.anypic"
}]));

The code snippet above will inject the following code into the content of your page's head tag:

<meta property="al:ios">
<meta property="al:ios:url" content="anypic://">
<meta property="al:ios:app_name" content="AnyPic">
<meta property="al:android">
<meta property="al:android:url" content="anypic://">
<meta property="al:android:package" content="com.parse.anypic">

You can also inject the App Links metadata into individual pages:

app.use(AppLinks([{
  platform: "ios",
  url: "anypic://",
  app_name: "AnyPic"
}, {
  platform: "android",
  url: "anypic://",
  package: "com.parse.anypic"
}]));

app.get('/home', AppLinks({
  platform: "ipad",
  url: "anypic2://",
  app_name: "AnyPic for iPad"
}), yourRenderFunction);

This will include the global iOS and Android metadata, but will also add iPad App Link metadata when rendering /home:

<meta property="al:ipad">
<meta property="al:ipad:url" content="anypic2://">
<meta property="al:ipad:app_name" content="AnyPic for iPad">
<meta property="al:ios">
<meta property="al:ios:url" content="anypic://">
<meta property="al:ios:app_name" content="AnyPic">
<meta property="al:android">
<meta property="al:android:url" content="anypic://">
<meta property="al:android:package" content="com.parse.anypic">

You can also generate App Link metadata based on request parameters by supplying a function:

app.get('/image/:imageId', AppLinks(function(req, res) {
  return {
    platform: "ipad",
    url: "anypic://image/" + req.params.imageId,
    app_name: "AnyPic for iPad"
  };
}), yourRenderFunction);

This will inject the following code when rendering /image/parsaritas:

<meta property="al:ipad">
<meta property="al:ipad:url" content="anypic://image/parsaritas">
<meta property="al:ipad:app_name" content="AnyPic for iPad">

Mailgun

Mailgun is a set of powerful APIs that allow you to send, receive, track and store email effortlessly. You can check out their service at www.mailgun.com. To use this Cloud Module, you will need to head over to the Mailgun website and create an account.

The current version of the Mailgun Cloud Module supports sending emails. To use it in your Cloud Code functions, start by requiring the module and initializing it with your credentials.

var Mailgun = require('mailgun');
Mailgun.initialize('myDomainName', 'myAPIKey');

You can then use the sendEmail function to fire off some emails. This function takes two parameters. The first is a hash with the Mailgun parameters you want to include in the request. The typical ones are from, to, subject and text, but you can find the full list on their documentation page. The second parameter to this function is an object with a success and an error field containing two callback functions.

Mailgun.sendEmail({
  to: "email@example.com",
  from: "Mailgun@CloudCode.com",
  subject: "Hello from Cloud Code!",
  text: "Using Parse and Mailgun is great!"
}, {
  success: function(httpResponse) {
    console.log(httpResponse);
    response.success("Email sent!");
  },
  error: function(httpResponse) {
    console.error(httpResponse);
    response.error("Uh oh, something went wrong");
  }
});

For additional information about the Mailgun Cloud Module, take a look at the API Reference.

Mandrill

Mandrill provides a great platform for sending transactional email. It runs on the delivery infrastructure that powers MailChimp. You can check out their service on their website. To use this Cloud Module, you will need to head over to the Mandrill website and create an account.

The current version of the Mandrill Cloud Module supports sending emails. To use it in your Cloud Code functions, start by requiring the module and initializing it with your credentials.

var Mandrill = require('mandrill');
Mandrill.initialize('myAPIKey');

You can then use the sendEmail function to fire off some emails. This function takes two parameters. The first is a hash with the Mandrill parameters you want to include in the request. A full list is available on their documentation page, but here is an example of the common ones. The message object is required with every request and contains the email's data such as the text, the subject and an array of recipients. Optionally, the async boolean value can be provided to ensure the request returns once the email is queued instead of waiting until it is sent. If you are sending an email to multiple recipients, you should set async to true to ensure your cloud function does not timeout. The second parameter to this function is an object with a success and an error field containing two callback functions for the request.

Mandrill.sendEmail({
  message: {
    text: "Hello World!",
    subject: "Using Cloud Code and Mandrill is great!",
    from_email: "parse@cloudcode.com",
    from_name: "Cloud Code",
    to: [
      {
        email: "you@parse.com",
        name: "Your Name"
      }
    ]
  },
  async: true
},{
  success: function(httpResponse) {
    console.log(httpResponse);
    response.success("Email sent!");
  },
  error: function(httpResponse) {
    console.error(httpResponse);
    response.error("Uh oh, something went wrong");
  }
});

For additional information about the Mandrill Cloud Module, take a look at the API Reference.

Moment

Moment.js is a small JavaScript date library for parsing, validating, manipulating, and formatting dates. You can learn more about Moment on their website. To use it, you simply need to require it.

var moment = require('moment');

For additional information about the Moment.js Cloud Module, take a look at their API reference.

Note that the version of Moment.js that Parse offers is 1.7.2. If you require a newer version, download moment.js to your cloud/ folder and require it like this:

var moment = require('cloud/moment');

Parse Image

Images are the most common kind of Parse.File. The parse-image module provides an Image class that makes working with images in Cloud Code easier.

Reading Images from Files

To get started, create an Image using a Buffer with image file data. Usually, this data comes from a Parse.File. To read in the data from a file and create the image object, you can use our networking functions.

var Image = require("parse-image");

Parse.Cloud.httpRequest({
  url: object.get("profilePhoto").url(),
  success: function(response) {
    // The file contents are in response.buffer.
    var image = new Image();
    return image.setData(response.buffer, {
      success: function() {
        console.log("Image is " + image.width() + "x" + image.height() + ".");
      },
      error: function(error) {
        // The image data was invalid.
      }
    })
  },
  error: function(error) {
    // The networking request failed.
  }
});

Cropping Images

To extract a particular rectangle of an image, use the crop method. This lets you specify the area of the image you want to keep.

// Crop the image to the rectangle from (10, 10) to (30, 20).
image.crop({
  left: 10,
  top: 10,
  right: 30,
  bottom: 20,
  success: function(image) {
    // The image was cropped.
  },
  error: function(error) {
    // The image could not be cropped.
  }
});

Alternatively, you can supply a width and height instead of right and bottom.

// Crop the image to the rectangle from (10, 10) to (30, 20).
image.crop({
  left: 10,
  top: 10,
  width: 20,
  height: 10,
  success: function(image) {
    // The image was cropped.
  },
  error: function(error) {
    // The image could not be cropped.
  }
});

Scaling Images

You can also resize an image, scaling the graphic using interpolation. Images can be made either smaller or larger. Just specify the new width and height. If you leave either off, it will assume the current image size.

// Resize the image to 64x64.
image.scale({
  width: 64,
  height: 64,
  success: function(image) {
    // The image was scaled.
  },
  error: function(error) {
    // The image could not be scaled.
  }
});

Sometimes it's more convenient to specify a ratio to resize to, instead of absolute dimensions.

// Resize the image to 25% of its original size.
image.scale({
  ratio: 0.25,
  success: function(image) {
    // The image was scaled.
  },
  error: function(error) {
    // The image could not be scaled.
  }
});

Changing Image Formats

You can even change the file format of an image file. For example, you may want to convert a file to a JPEG to reduce file size and bandwidth usage.

// Change the image to be a JPEG.
image.setFormat("JPEG", {
  success: function(image) {
    // The image was changed to a JPEG.
  },
  error: function(error) {
    // The image could not be reformatted.
  }
});

Image Thumbnail Example

Every Image method returns a Parse.Promise in addition to having callbacks. This makes it easy to chain together multiple operations. Consider the common case where a user supplies an image to use for their profile. It's nice to be able to automatically generate a thumbnail of that photo to use in some of your UI. This can be done using a beforeSave handler.

var Image = require("parse-image");

Parse.Cloud.beforeSave("_User", function(request, response) {
  var user = request.object;
  if (!user.get("profilePhoto")) {
    response.error("Users must have a profile photo.");
    return;
  }

  if (!user.dirty("profilePhoto")) {
    // The profile photo isn't being modified.
    response.success();
    return;
  }

  Parse.Cloud.httpRequest({
    url: user.get("profilePhoto").url()

  }).then(function(response) {
    var image = new Image();
    return image.setData(response.buffer);

  }).then(function(image) {
    // Crop the image to the smaller of width or height.
    var size = Math.min(image.width(), image.height());
    return image.crop({
      left: (image.width() - size) / 2,
      top: (image.height() - size) / 2,
      width: size,
      height: size
    });

  }).then(function(image) {
    // Resize the image to 64x64.
    return image.scale({
      width: 64,
      height: 64
    });

  }).then(function(image) {
    // Make sure it's a JPEG to save disk space and bandwidth.
    return image.setFormat("JPEG");

  }).then(function(image) {
    // Get the image data in a Buffer.
    return image.data();

  }).then(function(buffer) {
    // Save the image into a new file.
    var base64 = buffer.toString("base64");
    var cropped = new Parse.File("thumbnail.jpg", { base64: base64 });
    return cropped.save();

  }).then(function(cropped) {
    // Attach the image file to the original object.
    user.set("profilePhotoThumbnail", cropped);

  }).then(function(result) {
    response.success();
  }, function(error) {
    response.error(error);
  });
});

SendGrid

SendGrid is a cloud-based email service that delivers email on behalf of companies to increase deliverability and improve customer communications. If you do not already have a SendGrid account, you can do so (here)[http://www.sendgrid.com].

SendGrid provides reliable delivery, scalability and real-time analytics along with flexible APIs that make custom integration simple. Access advanced metrics and reporting with our powerful APIs to customize, measure and automate your email program.

Sending Email

The SendGrid module allows you to send attachments to multiple recipients and all the features of the SMTPAPI Header. For a more comprehensive documentation and examples, please visit the official repository for this library.

var sendgrid = require("sendgrid");

sendgrid.initialize("sendgrid_username", "sendgrid_password");
SendGrid.sendEmail({
  to: ["email@example.com (mailto:email@example.com)", "email+1@example.com"],
  from: "SendGrid@CloudCode.com (mailto:SendGrid@CloudCode.com)",
  subject: "Hello from Cloud Code!",
  text: "Using Parse and SendGrid is great!",
  replyto: "reply@example.com (mailto:reply@example.com)"
}).then(function(httpResponse) {
  console.log(httpResponse);
  response.success("Email sent!");
},function(httpResponse) {
  console.error(httpResponse);
  response.error("Uh oh, something went wrong");
});

Email Webhooks

SendGrid offers two webhooks, one for events and another for incoming email. Here are some cool things you can do with these webhooks.

With the Event Webhook, SendGrid allows you to monitor all stats with your SendGrid account in real-time and drill down to individual recipients to see who is opening and clicking your important messages. The Event Webhook will notify a URL of your choice via HTTP POST with information about these events as SendGrid processes your email. Common uses of this data are to remove unsubscribes, react to spam reports, determine unengaged recipients, identify bounced email addresses or create advanced analytics of your email program.

Enabling the SendGrid Event Webhook requires simply adding the endpoint in your Parse app to your settings:

The SendGrid Parse Webhook allows you to manage inbound email with as a smarter alternative to no-reply addresses. SendGrid can parse the attachments and contents of incoming emails enabling users to post content to an app (blog entries, photo uploads, etc.) via email. The SendGrid Parse API will POST the parsed email to a URL that you specify.

You can enable the SendGrid Parse Webhook by adding the following settings to your account:

Stripe

Stripe provides a very easy-to-use API for processing credit cards on the web or in your mobile app. You can take a look at their service at www.stripe.com. To use this Cloud Module, you will need to head over to the Stripe website and create an account. The current version of the Stripe Cloud Module supports the majority of their REST API.

To use this module in your Cloud Code functions, start by requiring and initializing it with your credentials.

var Stripe = require('stripe');
Stripe.initialize('mySecretKey');

Charging a Credit Card

Charging a credit card using Stripe and Parse will usually follow this flow.

  1. Getting a Credit Card Token

The first step to charging a credit card is to generate a token using the Stripe API. You should do this from your mobile or web client using your "publishable key". This will ensure that only Stripe manipulates the sensitive credit card information. If you are using iOS, you can use the Stripe iOS SDK, otherwise take a look at the Creating a Token section of their REST API documentation.

  1. Calling your Cloud Code Function

After successfully creating a token, you can send the card token to a Cloud Code function. For more on creating and calling Parse Cloud Functions from the client SDKs or REST API, take a look at the Cloud Code Guide.

  1. Charging the Credit Card

From a Cloud Code function, you can then use the Stripe Cloud Module to charge the credit card token. Using the Stripe.Charges.create function you can specify the amount, currency, and card token to use for the purchase. The full list of available parameters can be found in Stripe's API documentation, but the following example demonstrates the basic use case.

Stripe.Charges.create({
  amount: 100 * 10, // $10 expressed in cents
  currency: "usd",
  card: "tok_3TnIVhEv9P24T0" // the token id should be sent from the client
},{
  success: function(httpResponse) {
    response.success("Purchase made!");
  },
  error: function(httpResponse) {
    response.error("Uh oh, something went wrong");
  }
});

Available Functionality

There are many more functions available from the Stripe Cloud Module. Please consult the Stripe Cloud Module API reference for the full list of available functions and consult Stripe's own REST documentation for more information on how their platform works.

Twilio

Parse provides the full functionality of the Twilio-node module including SMS, Voice, and Twiml features. Please refer to the documentation here: Twilio-node module documentation. You do not need to install the module, as it is already installed and hosted on Parse.

Usage Example

// Require and initialize the Twilio module with your credentials
var client = require('twilio')('ACCOUNT_SID', 'AUTH_TOKEN');

// Send an SMS message
client.sendSms({
    to:'+16515556677', 
    from: '+14506667788', 
    body: 'Hello world!' 
  }, function(err, responseData) { 
    if (err) {
      console.log(err);
    } else { 
      console.log(responseData.from); 
      console.log(responseData.body);
    }
  }
);

Inbound Requests

With Express in Cloud Code, you can define routes to handle incoming requests. The following is an example Custom Webhook that receives requests from Twilio.

var express = require('express');
var app = express();

// Global app configuration section
app.use(express.bodyParser());  // Populate req.body

app.post('/receiveSMS',
         function(req, res) {

  console.log("Received a new text: " + req.body.From);
  res.send('Success');
});

app.listen();

After creating the route and deploying, configure the URL with Twilio and your webhook will begin handling requests from Twilio. You will have access to all of the request data through req.body in your Custom Webhook. The full list of available data can be found in the Twilio documentation.

For additional information about the Twilio Cloud Module, take a look at the twilio-node Reference.

Underscore

Underscore.js is a utility-belt library for JavaScript that provides a lot of the functional programming support. You can learn more about Underscore on their website. The Parse SDK uses this library internally but it is also available in Cloud Code using the underscore Cloud Module. To use it, you simply need to require it.

var _ = require('underscore');

For additional information about the Underscore.js Cloud Module, take a look at their API reference

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Command Line Tool

The Parse command line tool allows you to interact with your Cloud Code from your terminal. Some of the topics here are also covered in the Cloud Code guide, but they are repeated here for clarity.

Installation

Mac and Linux

In Mac OS and Linux/Unix environments, you can get the parse tool by running this command:

curl -s https://www.parse.com/downloads/cloud_code/installer.sh | sudo /bin/bash

This installs a tool named "parse" to /usr/local/bin/parse. There's no other junk, so to uninstall, just delete that file. This will also update your command line tool if you already have it installed.

Windows

The Parse command line tool for Windows is available here. Note that this is not an installer, it is just a plain windows executable. The downloaded executable is named like: parse-windows-x.xx.xx.exe. You can rename it to parse.exe and move it to an accessible location, so that you can run it by typing parse at your command prompt.

Updating

You can update the command line tool using parse update. It will automatically update your Parse command line tool to the latest version.

$ parse update
Fetching latest version ...
####################################################################### 100%
Installing ...

Setting Up Your App

The next step is to create a directory to store the code that you will run in the cloud. The command parse new sets up this directory, and will prompt you to pick which app you are creating Cloud Code for:

$ parse new MyCloudCode
Email: ninja@gmail.com
Password:
1:MyApp
Select an App: 1
$ cd MyCloudCode

Use the email address and password for your Parse account to log in. If you signed up via OAuth and never set a password, you should now set one by editing your account settings. This will create a directory called MyCloudCode in the current directory. Several files are automatically created for you:

.
├── cloud
│   └── main.js
├── config
│   └── global.json
└── public
    └── index.html

The config directory contains a JSON configuration file that you shouldn't normally need to deal with, the cloud directory stores your Cloud Code, and the public directory stores any static content that you want to host on Parse. In the cloud directory, you'll typically just be editing main.js, which stores all of your Cloud Code functions. For now, just check that these files were created successfully. If you're using source control, you can check all of these files in.

We recommend using source control to check in all of these files. If you're not already set up with source control, try this tutorial from GitHub. Keep in mind that these files will contain keys you want to keep private.

The same code can be deployed to multiple different applications. This is useful so that you can have separate "development" and "production" applications. Then you test the code on a development application before launching it in production.

The first application that is added (by the new command) will be the default application for all command line operations. All commands except for new take an optional application that the command will be performed on.

Deploying

To deploy a new release, run parse deploy from the command line:

$ parse deploy
Uploading source files
Uploading recent changes to scripts...
The following files will be uploaded:
.....
Uploading recent changes to hosting...
The following files will be uploaded:
.....
Finished uploading files
New release is named v1 (using Parse JavaScript SDK vx.x.x)

This pushes the new code (in cloud/main.js) to the Parse Cloud and deploys this code for the default target which is the first app that was added or the one you set using parse default. You can choose to deploy to a different target by adding the target as an argument to deploy like so:

$ parse deploy "My Other App"
Uploading source files
Uploading recent changes to scripts...
The following files will be uploaded:
.....
Uploading recent changes to hosting...
The following files will be uploaded:
.....
Finished uploading files
New release is named v2 (using Parse JavaScript SDK vx.x.x)

You can add release notes to the deploy with the -d or --description= option

If the contents of your parse project remain unchanged then we skip deploy. You will see an output like

$ parse deploy
Uploading source files
Finished uploading files
Not creating a release because no files have changed

You can override this behavior with the -f or --force flag. Providing this flag forces a deploy despite no changes to your project.

When embedding parse deploy within other scripts (such as in an automated testing/deploy environment) you can rely on the exit code from the Parse command line tool to indicate whether the command succeded. It will have an exit code of 0 on success and a non-zero exit code when the deploy failed.

Developing Cloud Code

You can also run the Parse command line tool in development mode using the develop command. This will make the tool watch the source directory for any updates and deploy them to Parse, as well as providing a live stream of the logs.

$ parse develop development
E2013-03-19:20:17:01.423Z] beforeSave handler in release 'v1' ran for GameScore with the input:
  {"original": null, "update":{"score": 1337}}
 and failed validation with Each GamesScore must have a playerName
New release is named v58
I2013-03-19T20:17:10.343Z] Deployed v58 with triggers:
  GameScore:
    before_save

Unlike the other commands, for develop you must specify the Parse App to push updates to. This is to avoid accidentally running develop on your production app causing you to run untested code in your production app.

Adding a New Target

You can add a new parse application as a target by running the add command. This prompts you for your Parse.com email and password and provides you a list of applications to choose from:

$ parse add
Email: pirate@gmail.com
Password(will be hidden):
1:PiecesOfEightCounter
2:BootyDivider
Select an App: 1

The add command takes an optional argument which is an alias to assign to the application that can be used instead of the app name.

Typically, all of this configuration data gets stored in the global.json. However, you might have an app that you use for development that you do not want to share with the rest of your team. You can use the --local flag to add this configuration instead to a separate local.json file. This way, you can check global.json into source control, while keeping local.json just on your own machine.

Setting the Default App

parse deploy, parse log, parse rollback, and parse releases use the default app to be run against the commands. parse default allows you to change this default app.

$ parse default MyApp
Default app set to MyApp.
$ parse default
Current default app is MyApp

Rolling Back

You can roll back a release using parse rollback. Just like with parse deploy, you can specify an optional target argument.

$ parse rollback
Rolled back to v1

This rolls back to the previous version of the code. You can also specify the release name to roll back to by using the -r or --release= option.

Reading the Logs

Every deploy, rollback, and activation of Cloud Code is logged. You can retrieve the end of logs using the parse log command. There are two types of logs:

The log command takes an optional target as well as two options:

$ parse log -n 1
I2012-07-10:13:37:00] beforeSave handler in release 'v1' ran for GameScore with the input:
  {"original": null, "update":{"score": 1337}}
 and failed validation with Each GamesScore must have a playerName

Listing Releases

You can list the known set of releases on the Parse Cloud with the releases command. Parse only tracks the last 10 releases.

$ parse releases
Name                            Description                     Date
v14                             Add background job              2015-03-11T18:17:52Z
v15                             No release notes given          2015-03-11T18:45:32Z
v16                             Moved to webhooks               2015-03-16T21:32:02Z
...

To view all files uploaded in a given release you can use the -v or --version option.

$ parse releases -v v14
Deployed cloud code files:
main.js

Deployed public hosting files:
index.html

Setting the SDK version

The default Parse JavaScript SDK version that is used for the Cloud Code in this directory is the latest version at the time the new command was run for this directory. If you want to change this use parse jssdk. You can see all available Parse JavaScript SDKs using parse jssdk -a. You can also use parse jssdk to check which Parse JavaScript SDK version is currently being used.

$ parse jssdk
Current JavaScript SDK version is 1.2.13
$ parse jssdk -a
  1.2.18
  1.2.17
  1.2.16
  1.2.15
  1.2.14
* 1.2.13
  1.2.12
  1.2.11
$ parse jssdk 1.2.18
Current JavaScript SDK version is 1.2.18
$ parse jssdk -a
* 1.2.18
  1.2.17
  1.2.16
  1.2.15
  1.2.14
  1.2.13
  1.2.12
  1.2.11
Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Performance

As your app scales, you will want to ensure that it performs well under increased load and usage. There are parts of optimizing performance that Parse takes care of but there are some things you can do. This document provides guidelines on how you can optimize your app's performance. While you can use Parse for quick prototyping and not worry about performance, you will want to keep our performance guidelines in mind when you're initially designing your app. We strongly advise that you make sure you've followed all suggestions before releasing your app.

Parse provides services out of the box to help your app scale auto-magically. On top of our MongoDB datastore, we have built an API layer that seamlessly integrates with our client-side SDKs. Our cloud infrastructure uses online learning algorithms to automatically rewrite inefficient queries and generate database indexes based on your app’s realtime query stream.

In addition to what Parse provides, you can improve your app's performance by looking at the following:

Keep in mind that not all suggestions may apply to your app. Let's look into each one of these in more detail.

Write Efficient Queries

Parse objects are stored in a database. A Parse query retrieves objects that you are interested in based on conditions you apply to the query. To avoid looking through all the data present in a particular Parse class for every query, the database can use an index. An index is a sorted list of items matching a given criteria. Indexes help because they allow the database to do an efficient search and return matching results without looking at all of the data. Indexes are typically smaller in size and available in memory, resulting in faster lookups.

Smart Indexing

The key to writing efficient queries is understanding our indexing strategy. If your data is not indexed, every query will have to go through the the entire data for a class to return a query result. On the other hand, if your data is indexed appropriately, the number of documents scanned to return a correct query result should be low.

One of the advantages to using Parse if that you don't have to worry about managing your own database and maintaining indexes. We've built an abstraction to manage all that complexity. However, you do have to organize your data model and use performant queries to take advantage of this. To better understand how to go about doing this, you need to understand how our systems are operating behind the abstraction. The key strategy you will want to understand here is our use of smart indexing.

Smart indexing means that we algorithmically generate indexes for the apps that we host. The sheer number of apps hosted on Parse means that we cannot manually generate indexes for each app. This would not scale well as developers can change their schemas or query patterns at any time. This is why we rely on smart indexes.

We perform two types of index creation logic. The first generates simple (single field) indexes for each API request, and the second does offline processing to pick good compound indexes based on real API traffic patterns. In each case the goal is to pick indexes that result in the smallest search space for the query, that is, there will be less data to scan to find results.

The simple indexing strategy looks at every API request and attempts to pick good indexes based on the following:

The order of a query constraint's usefulness is:

Take a look at the following query to retrieve GameScore objects:

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("score", 50);
query.containedIn("playerName",
    ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]);
PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query whereKey:@"score" equalTo:@50];
[query whereKey:@"playerName"
    containedIn:@[@"Jonathan Walsh", @"Dario Wunsch", @"Shawn Simon"]];
let query = PFQuery.queryWithClassName("GameScore")
query.whereKey("score", equalTo: 50)
query.whereKey("playerName", containedIn: ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"])

Creating an index query based on the score field would yield a smaller search space in general than creating one on the playerName field.

When examining data types, booleans have a very low entropy and and do not make good indexes. Take the following query constraint:

query.equalTo("cheatMode", false);
[query whereKey:@"cheatMode" equalTo:@NO];
query.whereKey("cheatMode", equalTo: false)

The two possible values for cheatMode are true and false. If an index was added on this field it would be of little use because it's likely that 50% of the records will have to be looked at to return query results.

We also throw out relations and join tables, since no values are stored for these keys. We heavily promote GeoPoints since MongoDB won’t run a geo query without a geo index. Other data types are ranked by their expected entropy of the value space for the key:

We score each query according to the above metrics, and make sure we create a unique index on the three top-scoring fields for each query. For a compound query that consists of an OR of subqueries, we compute the top three indexes for each subquery.

Even the best indexing strategy can be defeated by suboptimal queries. You will need to design queries that work hand in hand with smart indexing to deliver performant apps.

Efficient Query Design

Writing efficient queries means taking full advantage of indexes. Let's take a look at some query constraints that negate the use of indexes:

Additionally, the following queries under certain scenarios may result in slow query responses if they can't take advantage of indexes:

Not Equal To

For example, let's say you're tracking high scores for a game in a GameScore class. Now say you want to retrieve the scores for all players except a certain one. You could create this query:

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.notEqualTo("playerName", "Michael Yabuti");
query.find().then(function(results) {
  // Retrieved scores successfully
});
PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query whereKey:@"playerName" notEqualTo:@"Michael Yabuti"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    // Retrieved scores successfully
  }
}];
let query = PFQuery.queryWithClassName("GameScore")
query.whereKey("playerName", notEqualTo: "Michael Yabuti")
query.findObjectsInBackgroundWithBlock {
  (objects, error) in
  if !error {
    // Retrieved scores successfully
  }
}

This query can't take advantage of indexes. The database has to look at all the objects in the GameScore class to satisfy the constraint and retrieve the results. As the number of entries in the class grows, the query takes longer to run.

Luckily, most of the time a “Not Equal To” query condition can be rewritten as a “Contained In” condition. Instead of querying for the absence of values, you ask for values which match the rest of the column values. Doing this allows the database to use an index and your queries will be faster.

For example if the User class has a column called state which has values “SignedUp”, “Verified”, and “Invited”, the slow way to find all users who have used the app at least once would be to run the query:

var query = new Parse.Query(Parse.User);
query.notEqualTo("state", "Invited");
PFQuery *query = [PFUser query];
[query whereKey:@"state" notEqualTo:@"Invited"];
var query = PFUser.query()
query.whereKey("state", notEqualTo: "Invited")

It would be faster to use the “Contained In” condition when setting up the query:

query.containedIn("state", ["SignedUp", "Verified"]);
[query whereKey:@"state"
    containedIn:@[@"SignedUp", @"Verified"]];
query.whereKey("state", containedIn: ["SignedUp", "Verified"])

Sometimes, you may have to completely rewrite your query. Going back to the GameScore example, let's say we were running that query to display players who had scored higher than the given player. We could do this differently, by first getting the given player's high score and then using the following query:

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
// Previously retrieved highScore for Michael Yabuti
query.greaterThan("score", highScore);
query.find().then(function(results) {
  // Retrieved scores successfully
});
PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
// Previously retrieved highScore for Michael Yabuti
[query whereKey:@"score" greaterThan:highScore];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    // Retrieved scores successfully
  }
}];
let query = PFQuery.queryWithClassName("GameScore")
// Previously retrieved highScore for Michael Yabuti
query.whereKey("score", greaterThan: highScore)
query.findObjectsInBackgroundWithBlock {
  (objects, error) in
  if !error {
    // Retrieved scores successfully
  }
}

The new query you use depends on your use case. This may sometimes mean a redesign of your data model.

Not Contained In

Similar to “Not Equal To”, the “Not Contained In” query constraint can't use an index. You should try and use the complementary “Contained In” constraint. Building on the User example, if the state column had one more value, “Blocked”, to represent blocked users, a slow query to find active users would be:

var query = new Parse.Query(Parse.User);
query.notContainedIn("state", ["Invited", "Blocked"];
PFQuery *query = [PFUser query];
[query whereKey:@"state" notContainedIn:@[@"Invited", @"Blocked"]];
var query = PFUser.query()
query.whereKey("state", containedIn: ["Invited", "Blocked"])

Using a complimentary “Contained In” query constraint will always be faster:

query.containedIn("state", ["SignedUp", "Verified"]);
query whereKey:@"state" containedIn:@[@"SignedUp", @"Verified"]];
query.whereKey("state", containedIn: ["SignedUp", "Verified"])

This means rewriting your queries accordingly. Your query rewrites will depend on your schema set up. It may mean redoing that schema.

Regular Expressions

Most regular expression queries in Parse are heavily throttled due to performance considerations. MongoDB is not efficient for doing partial string matching except for the special case where you only want a prefix match. Queries that have regular expression constraints are therefore very expensive, especially for classes with over 100,000 records. Parse restricts how many such operations can be run on a particular app at any given time.

You should avoid using regular expression constraints that don't use indexes. For example, the following query looks for data with a given string in the playerName field. The string search is case insensitive:

query.matches("playerName", "Michael", “i”);
[query whereKey:@"playerName" matchesRegex:@"Michael" modifiers:@"i"];
query.whereKey("playerName", matchesRegex: "Michael", modifiers: "i")

A similar query looks for any occurrence of the string in the field, however the search is case sensitive:

query.contains("playerName", "Michael");
[query whereKey:@"playerName" containsString:@"Michael"];
query.whereKey("playerName", containsString: "Michael")

These queries are both slow. Depending on your use case, you should switch to using the following constraint that uses an index:

query.startsWith("playerName", "Michael");
[query whereKey:@"playerName" hasPrefix:@"Michael"];
query.whereKey("playerName", hasPrefix: "Michael")

This looks for data that starts with the given string. This query will use the backend index, so it will be faster even for large datasets.

As a best practice, when you use regular expression constraints, you'll want to ensure that other constraints in the query reduce the result set to the order of hundreds of objects to make the query efficient. If you must use the matches()constraint for legacy reasons, then use case sensitive, anchored queries where possible, for example:

query.matches("playerName", "^Michael");
[query whereKey:@"playerName" matchesRegex:@"^Michael"];
query.whereKey("playerName", matchesRegex: "^Michael")

Most of the use cases around using regular expressions involve implementing search. A more performant way of implementing search is detailed later.

Write Restrictive Queries

Writing restrictive queries allows you to return only the data that the client needs. This is critical in a mobile environment were data usage can be limited and network connectivity unreliable. You also want your mobile app to appear responsive and this is directly affected by the objects you send back to the client. The Querying Guide shows the types of constraints you can add to your existing queries to limit the data returned. When adding constraints, you want to pay attention and design efficient queries.

You can limit the number of query results returned. The limit is 100 by default but anything from 1 to 1000 is a valid limit:

query.limit(10); // limit to at most 10 results
query.limit = 10; // limit to at most 10 results
query.limit = 10 // limit to at most 10 results

If you're issuing queries on GeoPoints, make sure you specify a reasonable radius:

var query = new Parse.Query(PlaceObject);
query.withinMiles("location", userGeoPoint, 10.0);
query.find().then(function(placesObjects) {
  // Get a list of objects within 10 miles of a user's location
});
PFQuery *query = [PFQuery queryWithClassName:@"Place"];
[query whereKey:@"location" nearGeoPoint:userGeoPoint withinMiles:10.0];
[query findObjectsInBackgroundWithBlock:^(NSArray *places, NSError *error) {
  if (!error) {
    // List of objects within 10 miles of a user's location
  }
}];
let query = PFQuery.queryWithClassName("Place")
query.whereKey("location", nearGeoPoint: userGeoPoint, withinMiles: 10.0)
query.findObjectsInBackgroundWithBlock {
  (places, error) in
  if !error {
    // List of places within 10 miles of a user's location
  }
}

You can further limit the fields returned by calling select:

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.select("score", "playerName");
query.find().then(function(results) {
  // each of results will only have the selected fields available.
});
PFQuery *query = [PFQuery queryWithClassName:@"GameScore"];
[query selectKeys:@[@"score", @"playerName"]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    // each of results will only have the selected fields available.
  }
}];
let query = PFQuery.queryWithClassName("GameScore")
query.selectKeys(["score", "playerName"])
query.findObjectsInBackgroundWithBlock {
  (objects, error) in
  if !error {
    // each of results will only have the selected fields available.
  }
}

Client-side Caching

For queries run from iOS and Android, you can turn on query caching. See the iOS and Android guides for more details. Caching queries will increase your mobile app's performance especially in cases where you want to display cached data while fetching the latest data from Parse.

Use Cloud Code

Cloud Code allows you to run custom JavaScript logic on Parse instead of on the client.

You can use this to off load processing to the Parse servers thus increasing your app's perceived performance. You can create hooks that run whenever an object is saved or deleted. This is useful if you want to validate or sanitize your data. You can also use Cloud Code to modify related objects or kick off other processes such as sending off a push notification. There are time limits to how long Cloud Code can run, for example an afterSave hook only has 3 seconds to run. You can use Background Jobs if you need to run more time consuming processes such as data migrations.

We saw examples of limiting the data returned by writing restrictive queries. You can also use Cloud Functions to help limit the amount of data returned to your app. In the following example, we use a Cloud Function to get a movie's average rating:

Parse.Cloud.define("averageStars", function(request, response) {
  var Review = Parse.Object.extend("Review");
  var query = new Parse.Query(Review);
  query.equalTo("movie", request.params.movie);
  query.find().then(function(results) {
    var sum = 0;
    for (var i = 0; i < results.length; ++i) {
      sum += results[i].get("stars");
    }
    response.success(sum / results.length);
  }, function(error) {
    response.error("movie lookup failed");
  });
});

You could have ran a query on the Review class on the client, returned only the stars field data and computed the result on the client. As the number of reviews for a movie increases you can see that the data being returned to the device using this methodology also increases. Implementing the functionality through a Cloud Function returns the one result if successful.

As you look at optimizing your queries, you'll find that you may have to change the queries - sometimes even after you've shipped your app to the App Store or Google Play. The ability to change your queries without a client update is possible if you use Cloud Functions. Even if you have to redesign your schema, you could make all the changes in your Cloud Functions while keeping the client interface the same to avoid an app update. Take the average ratings Cloud Function example from before, calling it from a client SDK would look like this:

[PFCloud callFunctionInBackground:@"averageStars"
                  withParameters:@{@"movie": @"The Matrix"}
                           block:^(NSNumber *ratings, NSError *error) {
  if (!error) {
    // ratings is 4.5
  }
}];
PFCloud.callFunctionInBackground("averageStars", withParameters: ["movie": "The Matrix"]) {
  (ratings, error) in
  if !error {
    // ratings is 4.5
  }
}

If later on, you need to modify the underlying data model, your client call can remain the same, as long as you return back a number that represents the ratings result.

Avoid Count Operations

For classes with over 1,000 objects, count operations are limited by timeouts. They may routinely yield timeout errors or return results that are only approximately correct. Thus, it is preferable to architect your application to avoid this count operation.

Suppose you are displaying movie information in your app and your data model consists of a Movie class and a Review class that contains a pointer to the corresponding movie. You might want to display the review count for each movie on the top-level navigation screen using a query like this:

var Review = Parse.Object.extend("Review");
var query = new Parse.Query("Review");
// movieId corresponds to a given movie's id
query.equalTo(“movie”, movieId);
query.count().then(function(count) {
  // Request succeeded
});
PFQuery *query = [PFQuery queryWithClassName:@"Review"];
// movieId corresponds to a given movie's id
[query whereKey:@"movie" equalTo:movieId];
[query countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
  if (!error) {
    // Request succeeded
  }
}];
let query = PFQuery.queryWithClassName("Review")
// movieId corresponds to a given movie's id
query.whereKey("movie", equalTo: movieId)
query.countObjectsInBackgroundWithBlock {
  (number, error) in
  if !error {
    // Request succeeded
  }
}

If you run the count query for each of the UI elements, they will not run efficiently on large data sets. One approach to avoid using the count() operator could be to add a field to the Movie class that represents the review count for that movie. When saving an entry to the Review class you could increment the corresponding movie's review count field. This can be done in an afterSave handler:

Parse.Cloud.afterSave("Review", function(request) {
  // Get the movie id for the Review
  var movieId = request.object.get("movie").id;
  // Query the Movie represented by this review
  var Movie = Parse.Object.extend("Movie");
  var query = new Parse.Query(Movie);
  query.get(movieId).then(function(movie) {
    // Increment the reviews field on the Movie object
    movie.increment("reviews");
    movie.save();
  }, function(error) {
    throw "Got an error " + error.code + " : " + error.message;
  });
});

Your new optimized query would not need to look at the Review class to get the review count:

var Movie = Parse.Object.extend("Movie");
var query = new Parse.Query(Movie);
query.find().then(function(results) {
  // Results include the reviews count field
}, function(error) {
  // Request failed
});
PFQuery *query = [PFQuery queryWithClassName:@"Movie"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    // Results include the reviews count field
  }
}];
let query = PFQuery.queryWithClassName("Movie")
query.findObjectsInBackgroundWithBlock {
  (objects, error) in
  if !error {
    // Results include the reviews count field
  }
}

You could also use a separate Parse Object to keep track of counts for each review. Whenever a review gets added or deleted, you can increment or decrement the counts in an afterSave or afterDelete Cloud Code handler. The approach you choose depends on your use case.

Implement Efficient Searches

As mentioned previously, MongoDB is not efficient for doing partial string matching. However, this is an important use case when implementing search functionality that scales well in production.

Simplistic search algorithms simply scan through all the class data and executes the query on each entry. The key to making searches run efficiently is to minimize the number of data that has to be examined when executing each query by using an index as we've outlined earlier. You’ll need to build your data model in a way that it’s easy for us to build an index for the data you want to be searchable. For example, string matching queries that don’t match an exact prefix of the string won’t be able to use an index leading to timeout errors as the data set grows.

Let's walk through an example of how you could build an efficient search. You can apply the concepts you learn in this example to your use case. Say your app has users making posts, and you want to be able to search those posts for hashtags or particular keywords. You’ll want to pre-process your posts and save the list of hashtags and words into array fields. You can do this processing either in your app before saving the posts, or you can use a Cloud Code beforeSave hook to do this on the fly:

var _ = require("underscore");
Parse.Cloud.beforeSave("Post", function(request, response) {
  var post = request.object;
  var toLowerCase = function(w) { return w.toLowerCase(); };
  var words = post.get("text").split(/\b/);
  words = _.map(words, toLowerCase);
  var stopWords = ["the", "in", "and"]
  words = _.filter(words, function(w) {
    return w.match(/^\w+$/) && !   _.contains(stopWords, w);
  });
  var hashtags = post.get("text").match(/#.+?\b/g);
  hashtags = _.map(hashtags, toLowerCase);
  post.set("words", words);
  post.set("hashtags", hashtags);
  response.success();
});

This saves your words and hashtags in array fields, which MongoDB will store with a multi-key index. There are some important things to notice about this. First of all it’s converting all words to lower case so that we can look them up with lower case queries, and get case insensitive matching. Secondly, it’s filtering out common words like ‘the’, ‘in’, and ‘and’ which will occur in a lot of posts, to additionally reduce useless scanning of the index when executing the queries.

Once you've got the keywords set up, you can efficiently look them up using “All” constraint on your query:

var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.containsAll("hashtags", [“#parse”, “#ftw”]);
query.find().then(function(results) {
  // Request succeeded
}, function(error) {
  // Request failed
});
PFQuery *query = [PFQuery queryWithClassName:@"Post"];
[query whereKey:@"hashtags" containsAllObjectsInArray:@[@"#parse", @"#ftw"]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    // Request succeeded
  }
}];
let query = PFQuery.queryWithClassName("Post")
query.whereKey("hashtags", containsAllObjectsInArray: ["#parse", "#ftw"])
query.findObjectsInBackgroundWithBlock {
  (objects, error) in
  if !error {
    // Request succeeded
  }
}

Limits and Other Considerations

There are some limits in place to ensure the API can provide the data you need in a performant manner. We may adjust these in the future. Please take a moment to read through the following list:

Objects

Files

Queries

Cloud Code

Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.

Error Codes

The following is a comprehensive list of all the error codes that can be returned by the Parse API.

Name Code Description
OtherCause -1 An unknown error or an error unrelated to Parse occurred.
InternalServerError 1 Internal server error. No information available.
ConnectionFailed 100 The connection to the Parse servers failed.
ObjectNotFound 101 The specified object doesn't exist.
InvalidQuery 102 You tried to find values matching a datatype that doesn't support exact database matching, like an array or a dictionary.
InvalidClassName 103 Missing or invalid classname. Classnames are case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the only valid characters.
MissingObjectId 104 An unspecified object id.
InvalidKeyName 105 An invalid key name. Keys are case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the only valid characters.
InvalidPointer 106 A malformed pointer. You should not see this unless you have been mucking about changing internal Parse code.
InvalidJSON 107 Badly formed JSON was received upstream. This either indicates you have done something unusual with modifying how things encode to JSON, or the network is failing badly.
CommandUnavailable 108 The feature you tried to access is only available internally for testing purposes.
NotInitialized 109 You must call Parse.initialize before using the Parse library. Check the Quick Start guide for your platform.
IncorrectType 111 A field was set to an inconsistent type.
InvalidChannelName 112 Invalid channel name. A channel name is either an empty string (the broadcast channel) or contains only a-zA-Z0-9_ characters and starts with a letter.
InvalidSubscriptionType 113 Bad subscription type.
InvalidDeviceToken 114 The provided device token is invalid.
PushMisconfigured 115 Push is misconfigured in your app. See error details to find out how.
ObjectTooLarge 116 The object is too large. PFObjects have a max size of 128 kilobytes.
InvalidLimitError 117 An invalid value was set for the limit. A limit must be a non-negative integer.
InvalidSkipError 118 An invalid value was set for skip.
OperationForbidden 119 The operation isn't allowed for clients.
CacheMiss 120 The result was not found in the cache.
InvalidNestedKey 121 An invalid key was used in a nested JSONObject.
InvalidFileName 122 An invalid filename was used for PFFile. A valid file name contains only a-zA-Z0-9_. characters and is between 1 and 128 characters.
InvalidACL 123 An invalid ACL was provided.
Timeout 124 The request timed out on the server. Typically this indicates that the request is too expensive to run.
InvalidEmailAddress 125 The email address was invalid.
MissingContentType 126 Missing content type.
MissingContentLength 127 Missing content length.
InvalidContentLength 128 Invalid content length.
FileTooLarge 129 File that was too large. Files are limited to 10 MB.
FileSaveError 130 Error saving a file.
FileDeleteError 131 File could not be deleted.
InvalidInstallationIdError 132 Invalid installation id.
InvalidDeviceTypeError 133 Invalid device type.
InvalidChannelsArrayError 134 Invalid channels array value.
MissingRequiredFieldError 135 Required field is missing.
ChangedImmutableFieldError 136 An immutable field was changed.
DuplicateValue 137 Unique field was given a value that is already taken.
InvalidExpirationError 138 Invalid expiration value.
InvalidRoleName 139 Role's name is invalid.
ExceededQuota 140 An application quota was exceeded. Upgrade to resolve.
ScriptFailed 141 Cloud Code script failed. Usually points to a JavaScript error in your script.
ValidationFailed 142 Cloud Code validation failed.
ReceiptMissing 143 Product purchase receipt is missing.
InvalidPurchaseReceipt 144 Product purchase receipt is invalid.
PaymentDisabled 145 Payment is disabled on this device.
InvalidProductIdentifier 146 The product identifier is invalid.
ProductNotFoundInAppStore 147 The product is not found in the App Store.
InvalidServerResponse 148 The Apple server response is not valid.
ProductDownloadFilesystemError 149 The product fails to download due to file system error.
InvalidImageData 150 Invalid image data.
UnsavedFileError 151 An unsaved file.
InvalidPushTimeError 152 An invalid push time.
FileDeleteFailed 153 A file deletion failed.
InefficientQueryError 154 An inefficient query was rejected by the server.
RequestLimitExceeded 155 An application has exceeded its request limit. Upgrade to resolve.
MissingPushIdError 156 A push id is missing.
MissingDeviceTypeError 157 The device type field is missing.
TemporaryRejectionError 159 An application's requests are temporary rejected by the server. File a bug report for further instructions.
InvalidEventName 160 The provided event name is invalid.
UsernameMissing 200 The username is missing or empty.
PasswordMissing 201 The password is missing or empty.
UsernameTaken 202 The username has already been taken.
UserEmailTaken 203 Email has already been taken.
UserEmailMissing 204 The email is missing, and must be specified.
UserWithEmailNotFound 205 A user with the specified email was not found.
SessionMissing 206 A user object without a valid session could not be altered.
MustCreateUserThroughSignup 207 A user can only be created through signup.
AccountAlreadyLinked 208 An account being linked is already linked to another user.
InvalidSessionToken 209 The device's session token is no longer valid. The developer should ask the user to log in again.
LinkedIdMissing 250 A user cannot be linked to an account because that account's id could not be found.
InvalidLinkedSession 251 A user with a linked (e.g. Facebook or Twitter) account has an invalid session.
UnsupportedService 252 A service being linked (e.g. Facebook or Twitter) is unsupported.
InvalidAuthDataError 253 An invalid authData value was passed. It must be a Hash, not String.
AggregateError 600 There were multiple errors. Aggregate errors have an "errors" property, which is an array of error objects with more detail about each error that occurred.
XDomainRequest A real error code is unavailable because we had to use an XDomainRequest object to allow CORS requests in Internet Explorer, which strips the body from HTTP responses that have a non-2XX status code.
Unauthorized Unauthorized request. Are you missing an authentication header?
Want to contribute to this doc? Edit this section.
Was this section helpful? NO YES Thanks for your feedback, we’re always working to make our docs better.