Get game request ID / Access Facebook game request notification content - ios

I am trying to send requests with data to Facebook friends in my app. The requests are successfully sent and I do get notifications. However the message on the notifications is not what I specify (the notification I get is xxxxx sent you a request. I specified Please help me with 5 lives). Also, I can't access any data of the request received.
This is how I'm sending the request:
func sendLifeRequest(index: Int) {
let content = FBSDKGameRequestContent()
content.message = "Please help me with 5 lives"
content.data = "5lives"
let id = facebookFriends[index].id as NSString
var to: [NSString] = [NSString]()
to.append(id)
content.recipients = to
FBSDKGameRequestDialog.show(with: content, delegate: self)
}
This is how I'm trying to get it in the other end:
FBSDKGraphRequest(graphPath: "https://graph.facebook.com/me/apprequests?access_token=" + FBSDKAccessToken.current().tokenString, parameters: nil).start(completionHandler: { (connection, user, requestError) -> Void in
print(requestError) // prints nil
print(user)
})
print(user) prints:
Optional({
id = "https://graph.facebook.com/me/apprequests";
"og_object" = {
id = xxxxxxxxxxxxx;
type = website;
"updated_time" = "2016-10-19T05:32:20+0000";
};
share = {
"comment_count" = 0;
"share_count" = 0;
};
Update: I found out that if I copy the request ID and copy it for graph path it works. Does anyone knows how to get this ID from receivers end
func gameRequestDialog(_ gameRequestDialog: FBSDKGameRequestDialog!, didCompleteWithResults results: [AnyHashable : Any]!) {
print("request sent")
print(results) // copied ID from here
}
and pasted...
FBSDKGraphRequest(graphPath: THE ID HERE, parameters: nil).start(completionHandler: { (connection, user, requestError) -> Void in
print(requestError) // prints nil
print(user)
})
now print user prints:
Optional({
application = {
category = Games;
id = xxxxxxxxxxxx;
link = "https://www.facebook.com/games/?app_id=1841299476156545";
name = "Crazy Traffic Saga";
};
"created_time" = "2016-10-24T21:25:34+0000";
data = 5lives;
from = {
id = xxxxxxxxxxxx;
name = "xxxxxxxxxxxxxx";
};
id = xxxxxxxxxxxx;
message = "Please help me with 5 lives";
})
The problem is I copied when I log in with the user sending and copied to the user receiving. I still can't just access it just by code from the receiver.
Facebook documentation on Game request says:
"In order to read all the requests for a recipient for you can query the graph as shown below using the recipient's USER ACCESS TOKEN. This will return a list of request ids for that user in the app.
GET https://graph.facebook.com/me/apprequests?access_token=[USER ACCESS TOKEN]"
But thats what I was doing at first...

I found it. the request should be "/me/apprequests"
so:
FBSDKGraphRequest(graphPath: "/me/apprequests", parameters: nil).start(completionHandler: { (connection, user, requestError) -> Void in
})

Related

Get User's friends user ID for app leaderboard scores

So, i'm creating a leaderboard where users can see global scores, regional scores and friends scores who have used the app before. all these scores are fetched and written to the fire store database in firebase along with the user's unique id when they log in with facebook.
I need to get a list of the users friends and their user ids from facebook so I can search the fire store database for their scores using the Facebook id. But I don't know how to get the id out of my result below when getting the list of friends:
func getFriendsFromFB() {
let params = ["fields": "id, first_name, last_name, name, email, picture"]
let graphRequest = FBSDKGraphRequest(graphPath: "/me/friends", parameters: params)
let connection = FBSDKGraphRequestConnection()
connection.add(graphRequest, completionHandler: { (connection, result, error) in
if error == nil {
if let userData = result as? [String:Any] {
print(userData)
}
} else {
print("Error Getting Friends \(error)");
}
})
connection.start()
}
Can someone suggest how I get the user id out of my result in the code above?
Also I do ask for the user_friends permission when asking the user to login.
You're casting the result as a Dictionary, this means the results are stored as key values. You can retrieve values by using dictionary["keyHere"]. I'm not sure how the FB graph result is structured, but you will have to do something like this:
// Don't continue if the result is not a dictionary
guard let userData = result as? [String: Any] else {
return
}
// Now, you can get values from the dictionary
// Let's say the userID is a String
if let userID = userData["id"] as? String {
print(userID)
}

Facebook all_mutual_friends not working

I'm building an iOS app that connects to Facebook's all_mutual_friends API
https://developers.facebook.com/docs/graph-api/reference/user-context/all_mutual_friends/
The app has been reviewed and approved to connect to this API.
When I make the graph call per the documentation:
let params = ["fields":"context.fields(all_mutual_friends.fields(picture.width(500).height(200)))"]
FBSDKGraphRequest(graphPath: "/\(facebookID)", parameters: params, HTTPMethod: "GET").startWithCompletionHandler { (connection, result, error) in
print("result: \(result)")
print("error: \(error)")
}
I get the following result:
result: {
context = {
id = dXNlcl9jb250ZAXh0OgGQ8qbGU5YUiZAKn8g4zuCb1LCMGj3PiCXfe7B72X5DoKkbMpHZA395xRT0iV8D84NQIZBCjJ3VRKC9uNUrMZCiwIeZBOSTRndZCQKi4pgiIgLoxI3xAZD;
};
id = 10208913134493418;
}
The above response is when we have a mutual friend who has the app installed.
Does anyone know how to get the list of mutual friends?
If I am Facebook friends with the person, I successfully receive a list of mutual friends making the same graph call. This is the response:
context = {
"all_mutual_friends" = {
data = (
{
"first_name" = Mary;
picture = {
data = {
height = 200;
"is_silhouette" = 0;
url = "https://...";
width = 200;
};
};
}, //... 24 more results
This is great because there is data, but it is limited to 25 mutual friends. Is there a way to increase the limit above 25?
According to the Facebook documentation you referred above :
The All Mutual Friends API must be called from your server to obtain the full list of mutual friends. Calling this API in JavaScript, Android, or iOS client code will omit some of the results.
This explains the limit you are facing. :)

PubNub message text returning nil?

When I send a message using iOS to a PubNub channel, I can use the didReceiveMessage function to get that message and put it in my tableView. However, if I send a message via a client in the Dev Dashboard, message.data.message returns nil after I try to cast it as a String. Here's the function in question:
func client(client: PubNub, didReceiveMessage message: PNMessageResult) {
print("Received: %", message.data.message)
let newMessage:String? = message.data.message as? String
print(newMessage) // returns nil
self.messagesArray.append(newMessage!)
dispatch_async(dispatch_get_main_queue()) {
self.messageTableView.reloadData()
}
}
I get the following response in console from print("Received: %", message.data.message):
Received: % Optional({
text = test;
})
However, print(newMessage) is returning nil. What am I doing wrong?
Thanks!
EDIT: I'm getting the same thing when I try to get messages from the historyForChannel function.
//get history
pubNub.historyForChannel("channelname" as String, withCompletion: { (result, status) -> Void in
print(status)
if status == nil {
if result!.data.messages.count > 0 {
let historyMessages = result!.data.messages.description as? [String]
print(result)
for item in historyMessages!{
self.messagesArray.append(item)
}
}
}
})
historyMessages is nil, even though result prints:
Optional({
Operation = History;
Request = {
Authorization = "not set";
Method = GET;
Origin = "pubsub.pubnub.com";
"POST Body size" = 0;
Secure = YES;
URL = "...redacted";
UUID = "...redacted";
};
Response = {
"Processed data" = {
end = 14609023551682481;
messages = (
"technically ",
{
text = "Well..ok then";
},
hi,
"really ",
{
text = "Well..ok then";
},
How do I get the text from these returned messages?
From behaviour and fact what history fetch printed out status object means what you probably configured your client with cipherKey. That status object which you receive probably has category set to decryption error.
If you want to use encryption - you should use same key for all clients, or they won't be able to decrypt sent messages. If cipherKey is set, client automatically try to decrypt data and it will fail if regular text has been received.
Make sure both (console and iOS client) configured with same cipherKey or if you don't need it, make sure what it not set on any of clients.
Best regards,
Sergey.

get all facebook contacts with swift

I'm trying to get all my facebook contacts. With this code managed to catch however I can not bring the phone information and email contacts. This is my code:
let params = ["fields": "first_name, last_name, name, email, picture, phone"]
let request = FBSDKGraphRequest(graphPath:"/me/taggable_friends", parameters: params);
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
self.appDelegate.dismissHUD()
let resultdict = result as! NSDictionary
self.fbContact = resultdict.objectForKey("data") as! NSArray
print(self.fbContact)
self.loadData()
} else {
self.appDelegate.showError("Time Out")
}
it returns this dictionary:
(
{
"first_name" = xxxx;
id = "AaJRSpI-fYgIaPMaJCHEgCHB59aRecZbRSx0BrvDR_bZV-1W873iXn34kU940C_hc-TaoPnuFDfsJbBYtDSAFWiBfGWBXbxOja0c3NIHhyFqoQ";
"last_name" = xxxx;
name = "xxxx xxxx";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/p50x50/10351160_1463351673922060_1213695234585630315_n.jpg?oh=4c3b52137fc70b5743c7d00c2d=56ECD8DC&__gda__=1456979546_a879ab411cdf61e9293f27f70cd43bdd";
};
};
}
)
This is a facebook Graph API limitation. There is some limitations on the data you can get depending on the role you are. You cannot get your friends email or phone using Graph API.
taggable_friends can ONLY be used for tagging, it does not include any other data. You can only get additional data of friends who authorized your App too.
Btw, you can´t even get the phone of the authorized user, there´s no way to get it at all. And for the email, you have to authorize a user with the email permission.
In general, you can´t get any data of users who did not authorize your App, for privacy reasons.

Mailcore 2 iOS How to retrieve Reply email address

Mailcore 2 integration:
I am working on "Reply", "Reply All" , "Forward" and Move To features. When I started up with "Reply", I could able to get the Reply mail body full message from MCOMessageView class -> content = [(MCOIMAPMessage *) _message htmlRenderingWithFolder:_folder delegate:self]; and displayed in reply compose view.
Now, I need pre-populate "Reply" (Recipient To) email in the compose view. When I tried "_message.header.replyTo", it is giving me like "mailcore::Address:0x17df0c70 getsy sandriya getsypri8796#gmail.com"
But I need to retrieve the mail address(es) alone from this "_message.header.replyTo", it is giving me like "mailcore::Address:0x17df0c70 getsy sandriya getsypri8796#gmail.com"
How to retrieve Reply email address from "mailcore:.........", please advise.
The definitive answer for me is like the following, i made a quick Swift v2.3 example and it run like the following :
let imapsession = MCOIMAPSession()
imapsession.hostname = "YOUR SERVER"
imapsession.port = 993
imapsession.username = "EMAIL"
imapsession.password = "PASS"
imapsession.connectionType = MCOConnectionType.TLS
let requestKind : MCOIMAPMessagesRequestKind = MCOIMAPMessagesRequestKind.Headers
let folder : String = "INBOX"
let uids : MCOIndexSet = MCOIndexSet(range: MCORangeMake(1, UINT64_MAX))
let fetchOperation : MCOIMAPFetchMessagesOperation = imapsession.fetchMessagesOperationWithFolder(folder, requestKind: requestKind, uids: uids)
fetchOperation.start { (err, msg, vanished) -> Void in
print("error from server \(err)")
print("fetched \(msg?[0]) messages")
let msgs = msg
if msgs?.count > 0 {
for m in msgs! {
let MSG: MCOIMAPMessage = m as! MCOIMAPMessage
let op = imapsession.fetchMessageByUIDOperationWithFolder(folder, uid: MSG.uid)
op.start { (err, data) -> Void in
let msgParser = MCOMessageParser(data: data)
let html: String = msgParser.plainTextBodyRendering()
print("*********************")
print("Mail body\(html)")
print("mail sender:\(MSG.header.sender)")
print("mail recipient:\(MSG.header.to)")
print("mail subject:\(MSG.header.subject)")
print("*********************")
}
}
}
}
In the example above i went a bit far and i gather the mail content as text. you can do it in HTML also.
Hope this answer will help you and help other people who fall in the same issue !

Resources