Parse Update Object - ios

I have the following code:
//start the update
var query2 = PFQuery(className:"\(selectedShow)_schedule")
query2.getObjectInBackgroundWithId(idOfObject) {
(objectSend: PFObject!, error: NSError!) -> Void in
if error != nil {
NSLog("%#", error)
} else {
objectSend["student"] = "test"
objectSend.saveEventually()
println("ran")
}
}
And when I try to run it, it gives me the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
and highlights this line:
objectSend["student"] = "test"
What could be going wrong?

The variable was not wrapped with an optional.

Related

Check if PFObject is nil

I want to check if a PFObject is nil
I retrieve the object
var userLibrary: PFObject?
func getUserLibrary(user: PFUser) {
self.libraryQuery = PFQuery(className: "Library")
self.libraryQuery?.whereKey("owner", equalTo: user)
self.libraryQuery?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if objects!.count > 0 {
self.userLibrary = objects![0]
} else {
print(self.userLibrary)
}
}
})
}
The last line with the print statement prints out nil.
However when I check :
if userLibrary != nil {
}
Xcode tells me
Binary operator '!=' cannot be applied to operands of type 'PFObject' and 'NilLiteralConvertible'
How do I fix this ?
I'm not 100% sure that this will work, but did you try.
if let lib = userLibrary {
//do whatever
}
Let me know.
Also, if you are just using the first object of your query. It would better to use getFirstObjectInBackground

Parse save pointer

This is my code that tries to save the table/Class inscricoes
view.showHUD(view)
var inscricaoClass = PFObject(className: INSCRICAO_CLASS_NAME)
inscricaoClass[INSCRICAO_SORTEIO_ID] = self.eventObj.objectId
inscricaoClass.saveInBackgroundWithBlock { (success, error) -> Void in
if error == nil {
self.view.hideHUD()
} else { errorAlert.show(); self.view.hideHUD() }
}
This is my class / table where sorteioId is a pointer to my table/class sorteios
when I try to save an error of warning that can not save as a string pointer.
[Error]: invalid type for key sorteioId, expected Sorteios, but got string (Code: 111, Version: 1.7.5)
How do I send a pointer to table / class using parse?
You first need an instance of PFObject of type Sorteios. Revise your code like so:
view.showHUD(view)
var query = PFQuery(className: "Sorteios")
query.getObjectInBackgroundWithId(self.eventObj.objectId) {
(object: PFObject?, error: NSError?) -> Void in
if error == nil && object != nil {
// after finding Sorteios, you can assign it to inscricaoClass
var inscricaoClass = PFObject(className: INSCRICAO_CLASS_NAME)
inscricaoClass[INSCRICAO_SORTEIO_ID] = object
inscricaoClass.saveInBackgroundWithBlock { (success, error) -> Void in
if error == nil {
self.view.hideHUD()
} else {
errorAlert.show(); self.view.hideHUD() }
}
}
}

'AnyObject' is not convertible to 'String' while unwrapping optional

The code below is giving me the error " 'AnyObject' is not convertible to 'String' " at the line where I put my "if let" statement to unwrap the optional productData pulled from Parse. I'm just trying to pull a String from an object in Parse. I've checked everywhere and all the standard answers/solutions aren't working. Any thoughts?
Most of this code is taken straight from the Parse iOS docs Here
import Foundation
import Parse
func getDataFromParse () {
var productDataFromParse = PFQuery(className:"Product")
productDataFromParse.getObjectInBackgroundWithId("uyeXHufDgq") {
(productData: PFObject?, error: NSError?) -> Void in
if error == nil && productData != nil {
if let productTitle = productData["productTitle"] as! String {
self.productTitle = productTitle
}
} else {
println(error)
}
}
}
productData: PFObject? object is an optional itself. You can't subscript over it yet, because it needs to be unwrapped before. You can replace the productData != nil check with optional chaining.
In Swift 1.2 you can do that and your error checking in the same statement:
if let productTitle = productData?["productTitle"] as? String
where error == nil {
self.productTitle = productTitle
}
Note the additional ? between the productData and the square brackets.

Twitter.sharedInstance().APIClient is nil

I'm trying to use TwitterKit framework for my iOS app (in Swift). But when I use Twitter.sharedInstance().APIClient, it occurs an error saying fatal error: unexpectedly found nil while unwrapping an Optional value.
Here is my code:
import TwitterKit
func getUserInfo () {
let twUserID = "my twitter user_id" // This is not nil
let client = Twitter.sharedInstance() // This is not nil
let apiClient = Twitter.sharedInstance().APIClient // This is nil
// This occurs an error
// fatal error: unexpectedly found nil while unwrapping an Optional value
Twitter.sharedInstance().APIClient.loadUserWithID (twUserID, completion: {
(user, error) in
if let validUser = user {
println("Success!")
}
else {
println("Failed...")
}
})
}
Any help?
Even on old Objective-C frameworks that haven't been updated with nullability attributes, you can use Optional binding to ensure that force-unwrapped Optionals have a value before using them.
In the example listed above, you can optionally bind to the value of Twitter.sharedInstance().APIClient, like this:
if let apiClient = Twitter.sharedInstance().APIClient {
apiClient.loadUserWithID (twUserID, completion: {
(user, error) in
if let validUser = user {
println("Success!")
}
else {
println("Failed...")
}
})
}

How do I retrieve a score from a leaderboard in iOS?

I want to display the highest scores of a GKPlayer with a GKLeaderboard in Swift.
func login() {
if (GKLocalPlayer.localPlayer().authenticated) {
var leaderboardRequest: GKLeaderboard!
leaderboardRequest.identifier = "Best_Score"
// Error: fatal error: unexpectedly found nil while unwrapping an Optional value
func loadLeaderboardsWithCompletionHandler(completionHandler: (([AnyObject]!,
NSError!) -> Void)!) {
var localPlayerScore: GKScore = leaderboardRequest.localPlayerScore
}
}
}
Though, func loadLeaderboardsWithCompletionHandler returns this error message: fatal error: unexpectedly found nil while unwrapping an Optional value because I'm forcing unwrapping an Optional that contains nil.
Where's the error with my code?
You're declaring GKLeaderboard, but not initializing it. Note also that loadLeaderboardWithCompletionHandler is a class function of GKLeaderBoard. Do this instead:
if (GKLocalPlayer.localPlayer().authenticated) {
GKLeaderboard.loadLeaderboardsWithCompletionHandler { objects, error in
if let e = error {
println(e)
} else {
if let leaderboards = objects as? [GKLeaderboard] {
for leaderboard in leaderboards {
if let localPlayerScore = leaderboard.localPlayerScore {
println(localPlayerScore)
}
}
}
}
}
}
As a sidenote, it's not safe to use implicitly unwrapped optionals, i.e., anything declared with a !. Take for example your program here: you can compile it and have to dig through your code to find where the runtime error actually occurred. If you would have declared var leaderBoardRequest: GKLeaderBoard?, you would have been able to identify the source of your problem immediately without having to compile and run.

Resources