我听说 Facebook 的聊天 API 几年前就被弃用了,但我想知道通过使用新的 messenger API 是否可以通过 Facebook 向朋友发送消息。用户使用登录按钮登录并通过图形请求获取他们的信息,现在我想发送一条测试消息。
这是登录代码(有效)
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
var currentUserIDString : String?
override func viewDidLoad() {
super.viewDidLoad()
let facebookLoginButton = FBSDKLoginButton()
facebookLoginButton.delegate = self
facebookLoginButton.center = self.view.center
self.view.addSubview(facebookLoginButton)
let button : UIButton = FBSDKMessengerShareButton.circularButtonWithStyle(FBSDKMessengerShareButtonStyle.Blue, width: 80)
button.addTarget(self, action: "shareTest", forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(self.view.frame.size.width/2 - 40, 390, 80, 80)
self.view.addSubview(button)
}
// other methods
}
登录委托,获取用户信息(也可以)
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, gender, email"])
graphRequest.startWithCompletionHandler { (connection, result, error) -> Void in
if error != nil {
print(error.localizedDescription)
}
else if let result = result {
self.currentUserIDString = result["id"] as? String
print(self.currentUserIDString)
}
}
}
分享方法,这里有一些麻烦......参数字典和字段中的代码可能不正确,但Facebook文档很差,所以很难找到好的例子。
func shareTestGraphRequest() {
if FBSDKAccessToken.currentAccessToken() != nil {
if FBSDKAccessToken.currentAccessToken().hasGranted("read_page_mailbox") {
//establish param dictionary here
let parameterDictionary = NSMutableDictionary()
parameterDictionary.setObject("This is a test message, I'm building an app!", forKey: "message")
parameterDictionary.setObject(self.currentUserIDString!, forKey: "from")
parameterDictionary.setObject([], forKey: "to")
let graphRequest = FBSDKGraphRequest.init(graphPath: "/{message-id}", parameters: parameterDictionary as [NSObject : AnyObject], HTTPMethod: "POST")
graphRequest.startWithCompletionHandler { (connection, result, error) -> Void in
}
}
}
else {
let loginManager = FBSDKLoginManager()
loginManager.logInWithPublishPermissions(["read_page_mailbox"], fromViewController: self, handler: { (result, error) -> Void in
if error != nil {
print(error)
}
else if let result = result {
print(result)
}
})
}
}
谢谢您的帮助!