Xylus Sand
Xylus Sand

Reputation: 21

Parse + Swift + Anonymous

In an effort to create the easiest user experience possible, I am on a mission to accept a user as an anonymous user using Parse + Swift. I had thought to use the Anonymous user functions in Parse to accomplish that. As a result, I created the following code:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    self.setupParse()
    // self.setupAppAppearance()

This first section is to create a user and see if at this point in the process - I have a nil objectId (typically true for the user when first they attempt to open the application).

    var player = PFUser.currentUser()
    if player?.objectId == nil {

    }
    else
    {
        println(player!.objectId)
    }

If I have an objectId (indicating that I've been down this road before and saved an anonymous user object) - throw that to the console so I can see what it is and check it in the Parse user object. Cool - good so far.

Next - Check to see if the Object is nil again - this time to decide whether or not to attempt to perform an anonymous login - there's not a thing to use to generate an anonymous user other than this anonymous login action.

    if player?.objectId == nil {
        PFAnonymousUtils.logInWithBlock({
            (success, error) -> Void in
            if (error != nil)
            {
                println("Anonymous login failed.")
            }
            else
            {
                println("Anonymous login succeeded.")

If anonymous Login succeeded (still considering doing a network available check before trying to run these bits...but assuming network is valid) save a Bool to "isAnonymous" on the server to make sure that we have identified this user as anonymous - I may want that information later, so it seemed worth throwing this action.

Question 1: Do I need to re-query PFUser.currentUser() (known as player) to make sure that I have a valid anon user object that is connected to the server, or will the player object that I allocated earlier recognize that I've logged in and thereby recognize that I can throw other info into the associated record online? I think this is working as is - but I've been getting weird session token errors:

[Error]: invalid session token (Code: 209, Version: 1.7.5)

                player!["isAnonymous"] = true as AnyObject
                player!.saveInBackgroundWithBlock {
                    (success, error) -> Void in
                    if (error != nil)
                    {
                        println("error updating user record with isAnonymous true")
                    }
                    else
                    {
                        println("successfully updated user record with isAnonymous true")
                    }
                }
            }
        })
    }
    else
    {

    }

    return true
}

func setupParse()
{
    Parse.setApplicationId("dW1UugqmsKkQCoqlKR3hX8dISjvOuApcffGAWR2a", clientKey: "BtXxjTjBRZVnCZbJODhd3UBUU8zuoPU1HBckXh4t")

    enableAutomaticUserCreateInParse()

This next bit is just about trying to figure out some way to deal with those token problems. No idea whether it's doing me any good at all or not. It said to turn this on right after instantiating the Parse connection.

    PFUser.enableRevocableSessionInBackgroundWithBlock({
        (error) -> Void in
        if (error != nil) {
            println(error?.localizedDescription)
        }
    })

Next - just throwing around objects because I keep struggling with being connected and storing stuff or not being connected or losing session tokens. So - til I get this worked out - I'm creating more test objects than I can shake a stick at.

    var testObject = PFObject(className: "TestObject")

    testObject["foo"] = "barnone"

    testObject.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
        println("Object has been saved.")
    }
}

Question2: it appears to me that PFUser.enableAutomaticUser() while very handy - causes some headaches when trying to figure out whether I'm logged in/online/whatever. Anyone have any solid experience with this and able to guide me on how you'd check whether you were connected or not - I need to know that later to be able to decide whether to save more things to the user object or not.

func enableAutomaticUserCreateInParse() {
    if PFUser.currentUser()?.objectId == nil
    {
        myHumanGamePlayer.playerDisplayName = "Anonymous Player"
        PFUser.enableAutomaticUser()
    }
}

Anyone out there who's an expert on using anonymous users in Parse with Swift, let's get in touch and post a tutorial - because this has cost me more hours than I'd like to think about.

Thank you! Xylus

Upvotes: 2

Views: 753

Answers (1)

Fallah
Fallah

Reputation: 125

For player!["isAnonymous"] = true as AnyObject, don't save it as any object. Save it as a bool and look at your parse to see if it's a bool object. Try querying for current user in a different view controller and print to the command line. I hope this helped

Upvotes: 1

Related Questions