Reputation: 607
I am new to programming and am trying to develop an iOS app using Swift. However, I ran into a problem trying to retrieve previously saved information from Parse to use in my app.
To save the information I use the following code:
var user = PFUser.currentUser()
var number = self.phoneNumber.text as String
var insta = self.instagramUsername.text as String
var snapp = self.snapchatName.text as String
var twitter = self.twitterHandle.text as String
var bio = self.profileBio.text as String
var socialData = PFObject(className: "socialData")
socialData["phoneNumber"] = number
socialData["instagram"] = insta
socialData["snapchat"] = snapp
socialData["twitter"] = twitter
socialData["bio"] = bio
socialData["user"] = user
socialData.save()
This saves the information on Parse correctly but then when I try to retrieve the Instagram name or anything else specifically using a query I get an error. Here is how I have been trying to retrieve it:
var user = PFUser.currentUser()
var query = PFQuery(className:"socialData")
query.whereKey("user", equalTo: user)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
// The find succeeded.
// Do something with the found objects
var socialData = PFObject(className: "socialData")
let instaUsername = socialData["instagram"] as String
println(instaUsername)
} else {
// Log details of the failure
NSLog("Error: %@ %@", error, error.userInfo!)
}
}
The logs say fatal error: unexpectedly found nil while unwrapping an Optional value. After the app crashes. Yet, the information is correctly displayed on Parse. Any help is greatly appreciated, thanks!
Upvotes: 0
Views: 512
Reputation: 37300
Remove this line within your findObjectsInBackgroundWithBlock
block entirely:
var socialData = PFObject(className: "socialData")
and replace this line:
let instaUsername = socialData["instagram"] as String
with this:
let instaUsername = objects[0]["instagram"] as String
so you're actually utilizing the object array retrieved from the query, accessing the first object which matches the current user, then getting the "instagram" key's stored value from that PFObject dictionary.
Upvotes: 3