ios - facebook 解析快速注册

标签 ios iphone facebook swift

我一直在努力快速创建 facebook 登录/注册功能。我一直在寻找教程,但找不到任何东西。所以我一直在尝试自己做。它似乎有效,但为什么它不在数据库中保存我的 facebookName、性别和图像?它是将它保存在模拟器中,但当我使用我的 ios 8 设备时却没有?

我收到这条日志消息“用户注册并通过 Facebook 登录!”,一个新用户被添加到解析类中,但不是姓名、图像和性别...

@IBAction func login(sender: UIButton!) {




    var permissionArray = ["user_about_me", "user_relationships", "user_birthday", "user_location"]

    PFFacebookUtils.initializeFacebook()

    PFFacebookUtils.logInWithPermissions(permissionArray, block:  { (user: PFUser!, error: NSError!) in
        println(user)
        if user == nil {
            println(error.localizedDescription)


        } else {



            if user.isNew {



                var userQuery = PFUser.query()
                userQuery.getObjectInBackgroundWithId(PFUser.currentUser().objectId) {
                    (userObject: PFObject!, error: NSError!) -> Void in


                    var fbRequest = FBRequest.requestForMe()
                    fbRequest.startWithCompletionHandler { (connection: FBRequestConnection!, result:AnyObject!, error: NSError!) in


                        if error == nil {

                            //FACEBOOK DATA IN DICTIONARY
                            var userData = result as NSDictionary
                            var faceBookId = userData.objectForKey("id") as NSString
                            var faceBookName = userData.objectForKey("first_name") as NSString
                            var faceBookMiddle = userData.objectForKey("middle_name") as NSString
                            var faceBookGender = userData.objectForKey("gender") as NSString

                            var url:NSURL = NSURL.URLWithString(NSString(format:"https://graph.facebook.com/%@/picture?width=320", faceBookId))
                            var err: NSError?
                            var imageData :NSData = NSData.dataWithContentsOfURL(url, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)

                            var imageFile = PFFile(name: "image.jpg", data: imageData) as PFFile

                            println(userData)

                            userObject.setObject(faceBookName, forKey: "name")
                            userObject.setObject(imageFile, forKey: "file")
                            userObject.setObject(faceBookGender, forKey: "gender")

                            userObject.saveInBackground()



                            var sharedInstance:userSingleton = userSingleton.sharedInstance

                            sharedInstance.userName = (userObject.objectForKey("name") as NSString)
                            sharedInstance.userGender = (userObject.objectForKey("gender") as NSString)


                            (userObject.objectForKey("file") as PFFile).getDataInBackgroundWithBlock {
                                (theImageData: NSData!, error: NSError!) -> Void in

                                println(error)
                                if error == nil {

                                    sharedInstance.userImage = UIImage(data:theImageData)
                                }
                                self.performSegueWithIdentifier("LoginSegue", sender: self)
                            }


                        }
                    }
                }





                println("User signed up and logged in through Facebook!")
            } else {



                println("User logged in through Facebook!")
            }


        }

    })

}

}

最佳答案

假设您使用 Parse,下面是我是如何做到的。我个人创建了一个 Utils.swift 类,我把所有我想重用的东西(或者我不想在我的 ViewController 中包含的东西)放在里面:

class Utils {

    class func notLoggedIn() -> Bool {
        let user = PFUser.currentUser()
        // here I assume that a user must be linked to Facebook
        return user == nil || !PFFacebookUtils.isLinkedWithUser(user)
    }
    class func loggedIn() -> Bool {
        return !notLoggedIn()
    } 


    class func logInWithFacebook() {
        PFFacebookUtils.logInWithPermissions(["public_profile", "user_friends"]) {
            (user: PFUser!, error: NSError!) -> Void in
            if user == nil {
                NSLog("The user cancelled the Facebook login (user is nil)")
            } else {
                NSLog("The user successfully logged in with Facebook (user is NOT nil)")
                // HERE I SET A USER POINTER TO THE INSTALLATION
                // That way we can send push notifications to specific users
                if let installation = PFInstallation.currentInstallation() {
                    installation["user"] = PFUser.currentUser()
                    installation.saveEventually()
                }
                // THEN I GET THE USERNAME AND fbId
                Utils.obtainUserNameAndFbId()
            }
        }
    }


    class func obtainUserNameAndFbId() {
        if notLoggedIn() {
            return
        }
        let user = PFUser.currentUser() // Won't be nil because is logged in
        // RETURN IF WE ALREADY HAVE A USERNAME AND FBID
        // Note that we check the fbId because Parse automatically fills in the username with random numbers
        if let fbId = user["fbId"] as? String {
            if !fbId.isEmpty {
                println("we already have a username and fbId -> return")
                return
            }
        }
        // REQUEST TO FACEBOOK
        println("performing request to FB for username and IDF...")
        if let session = PFFacebookUtils.session() {
            if session.isOpen {
                println("session is open")
                FBRequestConnection.startForMeWithCompletionHandler({ (connection: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
                    println("done me request")
                    if error != nil {
                        println("facebook me request - error is not nil :(")
                    } else {
                        println("facebook me request - error is nil :)")
                        println(result)
                        // You have 2 ways to access the result:
                        // 1)
                        println(result["name"])
                        println(result["id"])
                        // 2)
                        println(result.name)
                        println(result.objectID)
                        // Save to Parse:
                        PFUser.currentUser().username = result.name
                        PFUser.currentUser().setValue(result.objectID, forKey: "fbId")
                        PFUser.currentUser().saveEventually() // Always use saveEventually if you want to be sure that the save will succeed
                    }
                })
            }
        }
    }

}

然后您可以在需要执行登录时简单地调用 Utils.logInWithFacebook()

请注意,由于 facebook me 请求可能会失败,因此无法保证您会成功将用户名和 facebook ID 保存到 Parse。这就是我创建方法 Utils.obtainUserNameAndFbId() 的原因,我在 application(_: didFinishLaunchingWithOptions) 中调用它(它可以在每次启动时调用,因为它只会执行请求到 FB,直到成功)。

关于ios - facebook 解析快速注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25917774/

相关文章:

iphone - iOS4如何重启 View Controller

ios - Gif使用UIImage+animtedGif类

ios - ios中是否只需要时区的位置服务提示

ios - 未定义不是对象(评估“RCTToastAndroid.SHORT”)

ios - UIButton 没有正确定位自己并且没有出现在某些设备中 - Objective C

Facebook 分享和点赞按钮显示相同的计数 - 这是不对的

java - 如何将signed_request参数获取到GWT MainEntryPoint客户端类中?

ios - 如何以编程方式更改单元格中 UIImageView 中显示的图像?

ios - XCTest:点击 navigationItem 返回按钮

facebook - 通用模板 image_url 未在 Messenger 中加载 - Facebook Messenger Platform