获取并显示用户';iOS Facebook SDK中的个人资料图片
我正在使用Facebook的SDK允许用户登录到我的应用程序,我希望该应用程序显示用户的个人资料图片。我有以下故事板和Swift文件:获取并显示用户';iOS Facebook SDK中的个人资料图片,ios,swift,facebook-graph-api,facebook-sdk-4.0,Ios,Swift,Facebook Graph Api,Facebook Sdk 4.0,我正在使用Facebook的SDK允许用户登录到我的应用程序,我希望该应用程序显示用户的个人资料图片。我有以下故事板和Swift文件: Main.storyboard和ViewController.swift HomeAfterLogIn.storyboard和HomeAfterLogInViewController.swift “Main”包含用户登录时使用的视图控制器,用户登录时使用的代码如下: import UIKit import FacebookLogin class Vie
- Main.storyboard和ViewController.swift
- HomeAfterLogIn.storyboard和HomeAfterLogInViewController.swift
import UIKit
import FacebookLogin
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
if AccessToken.current != nil
{
// Already logged-in
// Redirect to Home View Controller
goToHome()
}
// Add LoginButton
let loginButton = FBLoginButton(permissions: [ .publicProfile, .email, .userFriends ])
let screenSize:CGRect = UIScreen.main.bounds
let screenHeight = screenSize.height // real screen height
//let's suppose we want to have 10 points bottom margin
let newCenterY = screenHeight - loginButton.frame.height - 20
let newCenter = CGPoint(x: view.center.x, y: newCenterY)
loginButton.center = newCenter
view.addSubview(loginButton)
// Triggered after every successfully login / logout
NotificationCenter.default.addObserver(forName: .AccessTokenDidChange, object: nil, queue: OperationQueue.main) { [weak self] _ in
if AccessToken.current != nil {
// Successfully just Logged in
// Redirect to Home View Controller
self?.goToHome()
} else {
// Successfully just Logged out
}
}
}
func goToHome() {
let storyboard = UIStoryboard(name: "HomeAfterLogIn", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "HomeAfterLogInViewController") // I called mine like that (check screenshot below)
self.navigationController?.pushViewController(vc, animated: true)
}
}
此代码显示“使用Facebook登录”按钮,以及用户是否成功登录
func goToHome()
将用户发送到HomeAfterLogIn.storyboard,我希望在这里显示用户的个人资料图片
我在Facebooks Graph API网站上找到了以下代码:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:@"/100046232170264/picture"
parameters:@{ @"redirect": @"false",}
HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
}];
以上值与我的应用程序相关。当我将此代码插入HomeAfterLogInViewController.swift文件时,只会产生以下错误:
我输入的代码错了吗?它是以前版本的Swift,我的是Swift 4还是5?这是我第一次使用Facebook SDK
在发表评论后
(克苏右)将obj-c转换为Swift:
let request = FBSDKGraphRequest(graphPath: "/100046232170264/picture", parameters: [
"redirect": "false"
], httpMethod: "GET")
request.start(withCompletionHandler: { connection, result, error in
// Insert your code here
})
(Karol Zmysłowski)代码错误:
(Keshu R.)HomeAfterLogIn.storyboard中的UI项:
我建议创建一个自定义按钮并向其添加操作
// import
import FBSDKCoreKit
import FBSDKLoginKit
class LoginVC : UIViewController {
// create an IBAction and call the function inside it
@IBAction func facebookLoginBtnPressed(_ sender : Any) {
fetchFacebookFields()
}
// this function will return all the details and you can store it in userdefaults
func fetchFacebookFields() {
LoginManager().logIn(permissions: ["email","public_profile"], from: nil) {
(result, error) -> Void in
if let error = error {
print(error.localizedDescription)
return
}
guard let result = result else { return }
if result.isCancelled { return }
else {
GraphRequest(graphPath: "me", parameters: ["fields" : "first_name, last_name, email"]).start() {
(connection, result, error) in
if let error = error {
print(error.localizedDescription)
return
}
if
let fields = result as? [String:Any],
let userID = fields["id"] as? String,
let firstName = fields["first_name"] as? String,
let lastName = fields["last_name"] as? String,
let email = fields["email"] as? String
{
let facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
print("firstName -> \(firstName)")
print("lastName -> \(lastName)")
print("email -> \(email)")
print("facebookProfileUrl -> \(facebookProfileUrl)")
APPDELEGATEOBJ.makeRootVC(vcName : "MainTabBarVC")
}
}
}
}
}
}
这不是以前版本的Swift。你复制的代码是目标C:)啊,好的!这是一个巨大的帮助,有没有办法将其转换为swift?您是否将响应数据保存在任何地方?显示代码我所有的代码都显示在上面。我还添加了从obj-c转换为swift的代码,您认为如何?这给了我1个错误和1个警告。错误是:不允许在顶层使用表达式,并且该表达式位于以Profile.load开头的行上。。。警告是:从未使用过不可变值“imageURL”的初始化;考虑将赋值替换为“y”或移除它,这是从让IvaveL.WHW开始的行。是HomeAfterLogInViewController.swift吗?我是否必须添加任何UI元素,例如UIImageView?我将更新我的问题以显示我的HomeAfterLogIn.Storyboard您需要将其添加到loginViewController中。你需要添加一个按钮,然后将
facebook登录按钮连接到你的按钮上。你是否能够编辑图像以便我能完全理解?谢谢你的帮助
// import
import FBSDKCoreKit
import FBSDKLoginKit
class LoginVC : UIViewController {
// create an IBAction and call the function inside it
@IBAction func facebookLoginBtnPressed(_ sender : Any) {
fetchFacebookFields()
}
// this function will return all the details and you can store it in userdefaults
func fetchFacebookFields() {
LoginManager().logIn(permissions: ["email","public_profile"], from: nil) {
(result, error) -> Void in
if let error = error {
print(error.localizedDescription)
return
}
guard let result = result else { return }
if result.isCancelled { return }
else {
GraphRequest(graphPath: "me", parameters: ["fields" : "first_name, last_name, email"]).start() {
(connection, result, error) in
if let error = error {
print(error.localizedDescription)
return
}
if
let fields = result as? [String:Any],
let userID = fields["id"] as? String,
let firstName = fields["first_name"] as? String,
let lastName = fields["last_name"] as? String,
let email = fields["email"] as? String
{
let facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
print("firstName -> \(firstName)")
print("lastName -> \(lastName)")
print("email -> \(email)")
print("facebookProfileUrl -> \(facebookProfileUrl)")
APPDELEGATEOBJ.makeRootVC(vcName : "MainTabBarVC")
}
}
}
}
}
}