【问题标题】:How to take cover_photo from Facebook in swift 2.0如何在 swift 2.0 中从 Facebook 获取cover_photo
【发布时间】:2015-10-14 19:23:38
【问题描述】:

我正在尝试从 Facebook 获取用户的封面照片,但我遇到了一些问题...这是我的代码

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit

class ViewController: UIViewController, FBSDKLoginButtonDelegate {
    @IBOutlet weak var  name : UILabel!
    @IBOutlet weak var sesso: UILabel!
    @IBOutlet weak var immagineProfilo : UIImageView!
    @IBOutlet weak var immagineCopertina: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        if (FBSDKAccessToken.currentAccessToken() == nil)
        {
            print("Not logged in..")
        }
        else
        {
            print("Logged in..")
        }

        let loginButton = FBSDKLoginButton()
        loginButton.readPermissions = ["public_profile", "email"]
        loginButton.center = CGPointMake(80, 100)
        loginButton.delegate = self
        self.view.addSubview(loginButton)

    }

    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
    {
        if error == nil
        {
            print("Login complete.")
             /*  let protectedPage = self.storyboard?.instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController
            let protectedPageNav = UINavigationController(rootViewController: protectedPage)

            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

            appDelegate.window?.rootViewController = protectedPageNav*/

            if let _ = result.token{
                //Get user acces token
                let _:FBSDKAccessToken=result.token

                print("Token = \(FBSDKAccessToken.currentAccessToken().tokenString)")

                print("User ID = \(FBSDKAccessToken.currentAccessToken().userID)")


            }

            //Show user information
            let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"name,picture, email, gender, pic_cover"])

            graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

                if ((error) != nil)
                {
                    // Process error
                    print("Error: \(error)")
                }
                else
                {
                    let imgURLCoverPhoto = "https://graph.facebook.com/\(FBSDKAccessToken.currentAccessToken().userID)/pic_cover?
                    let imgURLCover = NSURL(string: imgURLCoverPhoto)
                    let imageDataCoverPhoto = NSData(contentsOfURL: imgURLCover!)
                    let imageCoverPhoto = UIImage(data: imageDataCoverPhoto!)
                    self.immagineCopertina.image = imageCoverPhoto
                    let imgURLString = "https://graph.facebook.com/\(FBSDKAccessToken.currentAccessToken().userID)/picture?width=10000"
                    let imgURL = NSURL(string: imgURLString)
                    let imageData = NSData(contentsOfURL: imgURL!)
                    let image = UIImage(data: imageData!)
                    self.immagineProfilo.image = image

                    print("fetched user: \(result)")
                     self.name.text = result.valueForKey("name") as! NSString as String
                    self.name.text = result.valueForKey("gender") as! NSString as String


                }
            })


        }
        else
        {
            print(error.localizedDescription)
        }
    }

    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!)
    {
        print("User logged out...")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

谢谢

【问题讨论】:

  • 你有一些问题......哪些问题?
  • 在控制台中出现-错误在展开可选值时意外发现 nil

标签: ios facebook


【解决方案1】:

查看文档有时会有所帮助:

正确的字段是cover,而不是代码中的pic_cover

【讨论】:

  • 我试图在字段中添加封面,但没有任何改变...我认为问题出在 let imgURLCoverPhoto
  • 好吧,如果您阅读文档,您会发现它不能是 UIImage 恕我直言类型,因为返回了一个对象。您可以在 cover.source 字段中找到图像的 URL。而且,如果您更改了代码但仍然遇到问题,您应该更新问题。否则只是猜测。
  • 所以在字段中我必须放置cover_source 或只是source?
【解决方案2】:

这是一个在 swift 中使用 fb sdk 的工作示例。文档确实有帮助,但它们不是复制粘贴的示例。 我需要获取页面的封面照片,因此在 graphPath 中我使用了页面 ID。可以轻松更改此参数以适合用户/事件/等...

let request = FBSDKGraphRequest(graphPath: "\\(page.id)?fields=cover", parameters: [
  "access_token": "your_access_token"
], HTTPMethod: "GET")
request.startWithCompletionHandler({(connection , result , error) in
  if ((error) != nil) {
    print("Error in fetching cover photo for \\(page.id): \(error)", terminator: "")
  }
  else {
    if let data = result["cover"] as? NSDictionary {
      self.fetchImageFromUrl(data["source"] as! String, cb: {(image: UIImage) -> Void in
        //do something with image
      })
    }
  })

func fetchImageFromUrl(url: String, cb: (UIImage) -> Void) {
  let urlObj = NSURL(string: url)!
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    let data = NSData(contentsOfURL: urlObj)
    dispatch_async(dispatch_get_main_queue(), {
      let image = UIImage(data: data!)!
      cb(image)
    });
  }
}

P.S - 我是 swift / ios 的新手,所以这段代码可能不是最好的。评论将不胜感激。

【讨论】:

    猜你喜欢
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    相关资源
    最近更新 更多