简体   繁体   English

Facebook 图 api。 从相册中获取照片

[英]Facebook graph api. Get photos from albums

Please help me to make a correct request to Facebook api.请帮助我向 Facebook api 提出正确的请求。 Now i've got:现在我有:

https://graph.facebook.com/me/albums?fields=photos

As the result I get very big Json with a lot of unnecessary info.结果我得到了非常大的 Json,里面有很多不必要的信息。 I tried to do something like this:我试图做这样的事情:

https://graph.facebook.com/me/albums?fields=photos?fields=source,name,id

or like this:或者像这样:

https://graph.facebook.com/me/albums?fields=photos&fields=source,name,id

But graph api explorer , returned the same big response, or i caught an error.但是图形 api explorer返回了相同的大响应,或者我发现了一个错误。 Any ideas how to do more compact response with only necessary info?任何想法如何只用必要的信息做更紧凑的响应?

Actually there is a better way to achieve this, nesting the request实际上有更好的方法来实现这一点,嵌套请求

Passing albums as a parameter, and then filter the fields from the connection photos that you want to, for example here I got just everything I need from albums and photos, also this results can be limited将相册作为参数传递,然后从您想要的连接照片中过滤字段,例如这里我从相册和照片中获得了我需要的一切,而且这个结果可能是有限的

me?fields=albums.fields(id,name,cover_photo,photos.fields(name,picture,source))

You may only use fields with properties that exists for objects.您只能使用具有对象存在的属性的fields

By issuing GET request to next URL you'll get list of albums ids only:通过向下一个 URL 发出 GET 请求,您将仅获得专辑 ID 列表:

https://graph.facebook.com/me/albums?fields=id&access_token=...

Same can be achieved by running next FQL query on album table:同样可以通过在album表上运行下一个FQL查询来实现:

SELECT aid FROM album WHERE owner=me()

Actually albums connection of user doesn't really contain list ofphoto objects butalbum (which have photos connection).实际上user albums连接并不真正包含photo对象列表,而是album (具有photos连接)。 So to get photos owned by user you'll need iterate over all of his object and getting photos for every album.因此,要获取用户拥有的照片,您需要遍历他的所有对象并获取每个相册的照片。 Again you may use fields argument to limit resulting data.同样,您可以使用fields参数来限制结果数据。 This can be done faster if using batch requests .如果使用批处理请求,这可以更快地完成。

Or With FQL it may be done like this (two tables photo and album involved):或者使用FQL可以这样做(涉及两张表photoalbum ):

SELECT pid FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner=me())

Another possible solution is getting album ids first and then iterate over them making this API call:另一个可能的解决方案是首先获取专辑 ID,然后通过此 API 调用迭代它们:

<ALBUM-ID>/photos?fields=name,source,id

I tested this in graph explorer and it retrieved a reasonable (and readable) json object我在图形资源管理器中对此进行了测试,它检索了一个合理(且可读)的 json 对象

For photo urls:对于照片网址:

  1. Ensure that you are an Admin of the Facebook Page.确保您是 Facebook 主页的管理员。

  2. go to : http://developers.facebook.com/tools/explorer去: http : //developers.facebook.com/tools/explorer

  3. In the API Navigator, you can see "/me" will bring up the basic information of yourself.在API Navigator中,可以看到“/me”会调出自己的基本信息。

  4. Try typing in "/me/accounts" to see if you can see anything.尝试输入“/me/accounts”以查看是否可以看到任何内容。 It should give you an error.它应该给你一个错误。

  5. Click on "Get Access Token"点击“获取访问令牌”

  6. a window will pop-up.会弹出一个窗口。 Navigate to "Extended Permissions"导航到“扩展权限”

  7. Select "manage_pages"选择“管理页面”

  8. Click "Get Access Token"点击“获取访问令牌”

  9. Now try "/me/accounts" again.现在再次尝试“/me/accounts”。 You should see a list of Groups inside the viewing window.您应该在查看窗口中看到一个组列表。

  10. Select the Page you want, and click on the "id" field选择您想要的页面,然后单击“id”字段

  11. Next, on the left window, you can see "Node: " and a + sign.接下来,在左侧窗口中,您可以看到“节点:”和一个 + 号。 Click on the + sign to see what are the options you have.单击 + 号以查看您有哪些选项。

  12. Click on the + sign and scroll down to "connections" and select "Albums"单击 + 号并向下滚动到“连接”并选择“相册”

  13. The child-level, select "Photos"子级,选择“照片”

  14. The "Photos" child-level, select "source"在“照片”子级,选择“来源”

  15. Now click "Submit" on the right hand side.现在点击右侧的“提交”。 You will see a JSON returned with the url of all the photos in your Facebook Page.您将看到一个 JSON 返回,其中包含您 Facebook 页面中所有照片的网址。

  16. Copy the URL - https://graph.facebook.com/ ?fields=albums.fields(photos.fields(source)) and plug it into your browser.复制 URL - https://graph.facebook.com/ ?fields=albums.fields(photos.fields(source)) 并将其插入浏览器。 You should see a JSON of all your photos.您应该会看到所有照片的 JSON。

每个相册都是一个类似于 facebook 中的用户对象的对象,要获取该特定相册中的照片,您必须请求以下内容

http://graph.facebook.com/{ALBUM_ID}?fields=photos&access_token="xxxxx"

to get the album list type :获取专辑列表类型:

me?fields=albums

after that type :在该类型之后:

album_id/photos?fields=source

to get the photos of that particular album获取该特定相册的照片

GETTING ALBUM_ID正在获取专辑_ID

    if((FBSDKAccessToken.current()) != nil)
    {
        FBSDKGraphRequest(graphPath: "me/albums", parameters: ["fields" : "id"], httpMethod: "GET").start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil)
            {
                let data:[String:AnyObject] = result as! [String : AnyObject]
                self.arrdata = data["data"]?.value(forKey: "id") as! [String ]
            }
        })
    }

with above code you will get album_Id and then with that id we can get image like this : GETTING IMAGES FROM ALBUM_ID使用上面的代码,您将获得专辑 ID,然后使用该 ID,我们可以获得这样的图像:从 ALBUM_ID 获取图像

    FBSDKGraphRequest(graphPath: "\(album_Id)/photos", parameters: ["fields": "source"], httpMethod: "GET").start(completionHandler: { (connection, result1, error) -> Void in
       if (error == nil)
       {
           let data1:[String:AnyObject] = result1 as! [String : AnyObject]
           let arrdata:[String] = data1["data"]?.value(forKey: "source") as! [String ]
           for item in arrdata
           {
               let url = NSURL(string: item )
               let imageData = NSData(contentsOf: url! as URL)
               let image = UIImage(data: imageData! as Data)
               self.imgArr.append(image!)
           }
        }
     })
request('GET', '/me/albums?fields=id,name,cover_photo,photos{images{source}},description')

it will show the albums with description and photos with different resolution of that album.它将显示带有描述的相册和该相册不同分辨率的照片。
This will need access token这将需要访问令牌

for Swift 5 Swift 5

first get albums id like this首先像这样获取专辑ID

func getAlbumsData()
{

        GraphRequest.init(graphPath: "me", parameters: ["fields":"id,name,albums{name,picture}"]).start(completionHandler: { (connection, userResult, error) in

            if error != nil {

                print("error occured \(String(describing: error?.localizedDescription))")
            }
            else if userResult != nil {
                print("Login with FB is success")
                print()



                let fbResult:[String:AnyObject] = userResult as! [String : AnyObject]

                self.albumsPhotos = (fbResult["albums"] as! [String:AnyObject])["data"] as? [[String:AnyObject]]
                self.tblFbAlbums.reloadData()




            }
        })
    }

then get albums image with this method然后使用此方法获取相册图像

func fetchalbumsPhotosWithID() {


        let graphRequest : GraphRequest  = GraphRequest(graphPath: "\(album_Id)/photos", parameters: ["fields": "source"] )

        graphRequest.start(completionHandler: { (connection, result, error) -> Void in

            if ((error) != nil)
            {
                // Process error
                print("Error: \(error)")
            }
            else
            {
                print("fetched user: \(result)")

                let data =  result as! [String:Any]


            }
        })

    }

album_Id is a number you get from getAlbumsData()相册_Id 是您从 getAlbumsData() 获得的数字

loginButton.setReadPermissions("public_profile", "email","user_friends","user_photos"); loginButton.setReadPermissions("public_profile", "email","user_friends","user_photos");

this permistion required需要这个许可

Why is the data unnecessary?为什么数据是不必要的? Did it return something like this:它是否返回了这样的东西:

{
   "data": [
      {
         "id": "ID",
         "from": {
            "name": "Hadrian de Oliveira",
            "id": "100000238267321"
         },
         "name": "Cover Photos",
         "link": "https://www.facebook.com/album.php?fbid=FBID&id=ID&aid=AID",
         "cover_photo": "ID",
         "privacy": "everyone",
         "count": 2,
         "type": "normal",
         "created_time": "2011-10-06T01:31:24+0000",
         "updated_time": "2012-02-22T17:29:50+0000",
         "can_upload": false
      },

? ?

for android
        new GraphRequest(
                facebookToken,
                String.format("/%s/photos", idAlbum),
                parameters,
                HttpMethod.GET,
                response -> {
                    try {
                        JSONArray photoArray = response.getJSONObject().getJSONArray("data");
                        photosAlbumAfterPagination = response.getJSONObject().getJSONObject("paging").getJSONObject("cursors").getString("after");
                        Gson gson = new Gson();
                        Type type = new TypeToken<List<FacebookPhotoResponse>>() {
                        }.getType();
                        List<FacebookPhotoResponse> list = gson.fromJson(photoArray.toString(), type);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
        ).executeAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM