I'm trying to find which user commented on the blog post. but it always returns nil and total objects 0, i'm not sure what am i doing wrong. This is my code to get the user's username
var finduser:PFQuery = PFUser.query()
finduser.whereKey("ObjectId", equalTo: commentclass.objectForKey("byuser").objectId)
finduser.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
if error == nil {
if let aobjects = objects {
let puser = (aobjects as NSArray).lastObject as? PFUser
cell.userName.text = puser?.username
println(puser) // returns nil
println(aobjects.count) // returns 0
}
}
}
It should be objectId and not ObjectId, also make sure there is no ACL set for the user object that might prohibit the requesting user from seeing this object.
Related
I have a UITableViewController which is basically a news feed. I have also implemented a pull to refresh feature. However sometimes when I pull to refresh it gives me the error
'Array index out of range'.
I know this means an item it is trying to get does not exist but can you tell me why? Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
tableView.delegate = self
tableView.dataSource = self
}
and the refresh() function:
func refresh() {
//get username and match with userId
let getUser = PFUser.query()
getUser?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
//clean arrays and dictionaries so we don't get indexing error
self.messages.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
//make userId = username
self.users[user.objectId!] = user.username!
}
}
}
})
let getPost = PFQuery(className: "Posts")
getPost.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
self.messages.removeAll(keepCapacity: true)
self.users.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
for object in objects {
self.messages.append(object["message"] as! String)
self.usernames.append(self.users[object["userId"] as! String]!)
self.tableView.reloadData()
}
}
}
self.refresher.endRefreshing()
}
It appears you are removing everything from users and then trying to access it in getPost.findObjectsInBackgroundWithBlock.
Specifically, self.users.removeAll(keepCapacity: true) is called just before self.usernames.append(self.users[object["userId"] as! String]!).
Also, be aware that the two queries execute asynchronously. You have no guarantee that users has been populated when the second query's completion block is reached. You will most likely want to restructure your two queries into one compound query or nest them (not recommended).
Lastly, from the looks of it, you may want to use removeAll(keepCapacity: false) rather than keeping the capacity with removeAll(keepCapacity: true).
func reloadFriendList() {
var query = PFQuery(className:"userFriendClass")
query.whereKey("username", equalTo:user!.username!)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
for object in objects! {
self.friendList = object["friends"] as! [String]
print(self.friendList)
self.reloadTableView()
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
i want to save object["friends"] that is an array from parse with usernames into
var friendList = [String]()
but i get the error: "fatal error: unexpectedly found nil while unwrapping an Optional value",
when the array is empty which means the user doesn't have any friends yet it works fine when the user have at least 1 or more friends.
You need to have your code ready to handle nil cases and cases where "objects" is an empty array.
If this were my code, I would do something like:
for object in objects {
if let friendList = object["friends"]
{
self.friendList = friendList
} else {
// make sure that your class's `friendList` var is declared as an optional
self.friendList = [String]()
}
}
Since objects is optional and may be nil, you need to unwrap it safely. One way to do that is to use the nil coalescing operator to unwrap it or to substitute an empty array if objects is nil. You can use it again to safely unwrap the list of friends:
for object in objects ?? [] {
self.friendList = (object["friends"] as? [String]) ?? []
You can also use optional binding if let to safely unwrap things:
if let unwrappedObjects = objects {
for object in unwrappedObjects {
if let friends = object["friends"] as? [String] {
self.friendsList = friends
} else {
// no friends :-(
self.friendsList = []
}
}
}
I am new to Parse. I am trying to update a object already saved on the parse backend. I use the getObjectInBackgroundWithID and supply the object ID. When I try and update with new data the app tells me it successfully save a new record and when i look on the backend, I now have two records with different object ID's. Below is my code in the update button. In my app it passes in the object ID, but I have tried hard coding the object ID with the same result.
#IBAction func updateAccountPressed(sender: AnyObject) {
let query = PFQuery(className:"Accounts")
query.getObjectInBackgroundWithId("dS7fHCoabI") {
(accountInfo: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let accountInfo = accountInfo {
accountInfo["Type"] = self.pickedAccontType
accountInfo["NumberOrNickname"] = self.accountNumNickname.text
accountInfo["InitialBalance"] = self.initialBalance.text
accountInfo.saveInBackground()
}
}
When you do
...
} else if let accountInfo = accountInfo {
...
You are actually creating a new variable called accountInfo and assigning the object you fetched to it. You are then calling the saveInBackground() method on a new PFObject you just created, thus creating a new record in Parse. Just change your if statement:
if error != nil {
print(error)
} else {
accountInfo["Type"] = self.pickedAccountType
accountInfo["NumberOrNickname"] = self.accountNumNickname.text
accountInfo["InitialBalance"] = self.initialBalance.text
accountInfo.saveInBackground()
}
It turns out I had somehow linked my updated button with both my update and the add func. After removing the link it updates fine with no new objectID.
I want to convert the friend list ids that I am getting from facebook as an array to save in parse. My code is as below but I am getting a "unexpectedly found nil while unwrapping an Optional value" error. What should I do to save the result to parse and retrieve it as array when required?
let fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
print("Friends are : \(result)")
if let dict = result as? Dictionary<String, AnyObject>{
let profileName:NSArray = dict["name"] as AnyObject? as! NSArray
let facebookID:NSArray = dict["id"] as AnyObject? as! NSArray
print(profileName)
print(facebookID)
}
}
else {
print("Error Getting Friends \(error)");
}
}
When I use the code below in print() I get the result below:
Friends are : {
data = (
{
id = 138495819828848;
name = "Michael";
},
{
id = 1105101471218892;
name = "Johnny";
}
);
The issue is that you are trying to access the name and id elements from the top-level dictionary, where you need to be accessing data.
When you call the FB Graph API for friends it will return an array of dictionaries (one per friend).
Try this:
let fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil)
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
print("Friends are : \(result)")
if let friendObjects = result["data"] as? [NSDictionary] {
for friendObject in friendObjects {
println(friendObject["id"] as NSString)
println(friendObject["name"] as NSString)
}
}
} else {
print("Error Getting Friends \(error)");
}
}
You should also check out this SO post with more information on the FB Graph API. Here's a brief snippet.
In v2.0 of the Graph API, calling /me/friends returns the person's
friends who also use the app.
In addition, in v2.0, you must request the user_friends permission
from each user. user_friends is no longer included by default in every
login. Each user must grant the user_friends permission in order to
appear in the response to /me/friends. See the Facebook upgrade guide
for more detailed information, or review the summary below.
So I am trying to get a String that is saved within an object from Parse.com. Here is the code that I am using to do so:
var query: PFQuery = PFQuery(className: "Replys")
query.getObjectInBackgroundWithId("ipmdKB0N1N") {
(object: PFObject?, error: NSError?) -> Void in
if error == nil && object != nil {
println(object)
self.replyField.text = object["Replys"]
} else {
println(error)
}
}
I want to make this string the text of the label called "replyField" but when I try to do that, Xcode gives an error like "Cannot assign value "AnyObject?" to type "String?"" Even when I add as! String, it still gives a similar (though not exactly the same) error. Any ideas why?
You should unwrap optional of object. Such as object!["Replys"] or object?["Replys"]
Like below:
self.replyField.text = object!["Replys"] as! String
or
self.replyField.text = object?["Replys"] as! String
let replysString = object["Replys"] as! NSString
self.replyField.text = replysString as String