Contacts/Friends list functionality in Swift - ios

I am working on an iOS application that allows users to send their location to a handful of their friends. Where I'm having difficulty is the actual friends list functionality. All my research just results in getting your friends list from Facebook. This is a proprietary friends list within my app, similarly to Snapchat. I do not want to get friends through another party. Users are stored using Parse so it would be preferred to have my friends list logic using Parse. Any help is appreciated. Thank you.

So you want people using your app to be able to send friend requests and become friends?
I did this with a Relation column in Parse named "Friends", in the User class.
To send and receive requests, I made a class "FriendReqeust" with two Pointer columns, "fromUser" and "toUser", and a String, "status".
Display the friend request properly and add buttons for accept and decline. It's easy to create a new relation for the accepting user, and add that one in to his/hers Relation column, but to add it to the FriendRequestSender you need to use Cloud Code.
Example Code for accepting request (friend added to currentUser if Cloud Code succeeds):
PFCloud.callFunctionInBackground("addFriendToFriendsRelation", withParameters: ["friendRequest":friendRequestId]) {
(response: AnyObject?, error: NSError?) -> Void in
if error == nil {
var friendsRelation = self.toUser!.relationForKey("friendRelations")
friendsRelation.addObject(self.fromUser!)
self.toUser!.saveInBackground()
} else {
println(error)
}
}
If you know how to translate Objective-C to Swift, I recommend the answer to this question.
https://teamtreehouse.com/forum/parsecom-swift-how-do-you-add-pfusercurrentuser-to-another-users-relations-using-cloud-code-the-master-key
Then you can query Friends from any user.

Related

Realm Swift: Question about Query-based public database

I’ve seen all around the documentation that Query-based sync is deprecated, so I’m wondering how should I got about my situation:
In my app (using Realm Cloud), I have a list of User objects with some information about each user, like their username. Upon user login (using Firebase), I need to check the whole User database to see if their username is unique. If I make this common realm using Full Sync, then all the users would synchronize and cache the whole database for each change right? How can I prevent that, if I only want the users to get a list of other users’ information at a certain point, without caching or re-synchronizing anything?
I know it's a possible duplicate of this question, but things have probably changed in four years.
The new MongoDB Realm gives you access to server level functions. This feature would allow you to query the list of existing users (for example) for a specific user name and return true if found or false if not (there are other options as well).
Check out the Functions documentation and there are some examples of how to call it from macOS/iOS in the Call a function section
I don't know the use case or what your objects look like but an example function to calculate a sum would like something like this. This sums the first two elements in the array and returns their result;
your_realm_app.functions.sum([1, 2]) { sum, error in
if let err = error {
print(err.localizedDescription)
return
}
if case let .double(x) = result {
print(x)
}
}

Get firebase message from sender and receiver

I am using firebase for simple chat application. I am looking to fetch messages of user 1 and user 2. My database structure look like this.
I am using queryOrdered to fetch messages but it will filter with either sender or receiver.
Database.database().reference().child("Chats").queryOrdered(byChild: "receiver")
.queryEqual(toValue: "2WCS7T8dzzNOdhEtsa8jnlbhrl12")
.observe(.value, with: { snapshot in
})
But using this code I got messages of receiver only. How can I receive messages of sender as well. Can I use AND condition to query sender child?
There is no way in your current data structure to with a single query get both the messages that a specific user sent and received.
Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to filter on into a single (synthetic) property.
For example, you could combine the sender and receiver UID into a single properties "sender_receiver": "2WCS7T8dzzNOdhEtsa8jnlbhrl12_Sl91z...." and then query for that combined value.
For a longer example of this and other approaches, see my answer here: Query based on multiple where clauses in Firebase
For most chat applications however I recommend creating a database structure that models chat "rooms". So instead of having one long list of all messages, store the messages in rooms/threads, which is also what you show in the UI of your app.
"-RoomId1": {
"msg1": { ... },
"msg2": { ... }
}, "-RoomId2": {
"msg3": { ... },
"msg4": { ... }
}
That way you have the most direct mapping from the database, to what you show on the screen.
For a good way to name the "rooms", see Best way to manage Chat channels in Firebase
You'd then still store a mapping for each user of what rooms they're a part of, which might also be useful in securing access.

iOS: Firebase realtime database sub child querying

I work on iOS app that use firebase real time database, my structure as , I want to write a query that retrieve all users of a group, each user have multiple groups, and each groups have multiple users, I capable of showing all groups of one user and I want to show all other users they are belong to that group, i.e, when user choose of his groups,
How can achieve that?
In my opinion, the best way to deal with this is to duplicate your data. If you definitely need the structure you posted above, you can keep it and create also another one as such:
"groupUsers": {
"123" : { //groupId
"235" : { //uniqueKey for record
userId: "567",
userName: "Jack"
}
}
}
To get all users in a certain group use the firebase reference:
`/groupUsers/${groupId}/`
You loop over the returned list to show values from each list item.

Parse.com Get User Who Like an Object

So I've set up my relations correctly in Parse using the following code:
var user = PFUser.currentUser()
var relation = user.relationForKey("likes")
relation.addObject(self.post)
user.saveInBackgroundWithBlock({ (Bool, error) -> Void in
println("user likes this post")
// Used for tracking in the PFTableCell for UI parts
self.userLikes = true
})
When the view loads, I need to change the buttons to Liked and the colour etc. I'd like to get all the users who liked this particular post but cannot figure out the query? It will give me some other useful info (e.g. I could display usernames of people who liked the post).
As a workaround I can get all the posts the user likes by doing:
var user = PFUser.currentUser()
var relation = user.relationForKey("likes")
relation.query().findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error != nil {
// There was an error
println(error)
} else {
// objects has all the Posts the current user liked and do something.
println(objects)
}
}
But that's not what I'm after? I'm using Swift and the Parse SDK, but will happily have the answer in Obj C and I'll translate. The Parse docs suggestion is wrong: https://www.parse.com/docs/ios_guide#objects-pointers/iOS I could store the like against the post rather than the user, but that would mean I'd have to open up access rights to the post which is a no-no
There is an issue with your database structure. You should not just have User objects, but you should have Post objects as well. The Post can have a likes relation that points to all the Users who liked the post. When a User likes the Post, then the User is added to the Post's likes relation. Thus, to get the info you need, you just need to look at the Post's relation.
What do you mean about open access rights to the Post? Do you want the post to be read only for all users except the User who posted it?
Or is the issue with giving access to the User objects? I am not sure if it really an issue, since you could just be running a quick count on the User objects in the relation without actually looking at the data in the User objects. You could create Like objects, but I don't think it's necessary.

updating many users at once in parse

I'd like to update user's column which presents related posts that the user might like,
my code is like that:
let users = query.findObjects() as [PFUser]
for user in users{
let rel = user.relationForKey("posts")
rel.addObject(post, forKey: "relatedPosts")
rel.saveInBackground()
}
I really don't know why, but I tried to do that in many versions (not only by relation, also by arrays and other methods) and it always updates just one user (the one who logged in)..
how can I get this done?
You can't update user that is not currently authenticated in your app.
The way I see it you have 2 options:
1) You can set some Cloud Code to run using the master key, so it can modify users.
2) You can add a new custom column to your Parse User class that will link to another class DB that has the related posts for the user.
take a look here: Parse.com Relations Guide
I would choose #2.

Resources