Contents

Develop
2017.02.27 11:23

[ios] Facebook Cache 갱신하는 함수

조회 수 1165 댓글 0
Atachment
첨부 '1'
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

페이스북에 URL을 공유할 경우 페이스북은 해당 URL에 대한 OpenGraph 정보들을 캐싱한다.

메타 정보가 수시로 바뀌는 컨텐츠의 경우 Facebook의 URL 공유시 잘못된 정보가 매핑될 수 있다.

(이전에 캐싱됐던 내용이 적용되는 것)


이를 갱신하기 위한 방법이 여러 가지가 있다.


1. Facebook for Developers (개발자도구) 사이트를 이용하여 요청

Facebook의 개발자 사이트에서 OG 캐시의 동작을 확인하고 갱신하는 웹페이지를 제공한다.

다음 URL을 이용해 확인할 수 있다.

-> https://developers.facebook.com/tools/debug/


2. Facebook API 이용

Facebook에서 OG 캐시를 갱신할 수 있는 HTTP 기반의 API를 제공하고 있다.

다양한 플랫폼과 프로그래밍 언어를 통해 이 API를 호출하여 갱신할 수 있다.


PHP + Curl (Web, Server-side)

$url = 'https://graph.facebook.com';
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POST, true );

$params = array(
    'id' => 'http://www.picomax.net/',
    'scrape' => true
);
$data = http_build_query($params);

curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_exec( $ch );
$httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );

Javascript (Web, Front-end)

// with jQuery
$.post(
    'https://graph.facebook.com',
    {
        id: 'http://www.picomax.net/',
        scrape: true
    },
    function(response){
        console.log(response);
    }
);


# Vanilla Javascript (Web, Front-end)

//Check if facebook_refresh query string is present
if(window.location.search.indexOf("facebook_refresh") >= 0)
{
    //Feature check browsers for support
    if(document.addEventListener && window.XMLHttpRequest && document.querySelector)
    {
        //DOM is ready
        document.addEventListener("DOMContentLoaded", function() {
            var httpRequest = new XMLHttpRequest();
            httpRequest.open("POST", "https://graph.facebook.com", true);
            
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState == 4) {
                    console.log("httpRequest.responseText", httpRequest.responseText);
                }
            };
            
            //Default URL to send to Facebook
            var url = window.location;
            
            //og:url element
            var og_url = document.querySelector("meta[property='og:url']");
            
            //Check if og:url element is present on page
            if(og_url != null)
            {
                //Get the content attribute value of og:url
                var og_url_value = og_url.getAttribute("content");
                
                //If og:url content attribute isn't empty
                if(og_url_value != "")
                {
                    url = og_url_value;
                } else {
                    console.warn('<meta property="og:url" content=""> is empty.
                    Falling back to window.location');
                }               
            } else {
                console.warn('<meta property="og:url" content=""> is missing.
                Falling back to window.location');
            }
            
            //Send AJAX
            httpRequest.send("scrape=true&id=" + encodeURIComponent(url));
            
        });
    } else {
        console.warn("Your browser doesn't support one of the following:
            document.addEventListener && window.XMLHttpRequest && document.querySelector");
    }
}


# Objective-C (iOS)

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSString *targetId = @"http://www.picomax.net";
    //[self updateFacebookCache:targetId];
}

- (void)updateFacebookCache:(NSString *)targetId {
    NSString *url = @"https://graph.facebook.com";
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:targetId forKey:@"id"];
    [params setObject:@"true" forKey:@"scrape"];
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]
        initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [manager POST:url parameters:params progress:nil
        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        NSLog(@"success!");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error: %@", error);
    }];
}



?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
1113 Develop [js] jQuery 충돌 회피 hooni 2013.12.17 38309
1112 System/OS [linux] 처음 설치부터 APM 설치까지 (업데이트 할 것) hooni 2013.04.23 38269
1111 PPT [android][ios] 알림(Notification) 기능에 대한 원리와 구현 방안 (APNS포함) file hooni 2013.04.23 37847
1110 System/OS CentOS 6.5 USB 설치 6 file hooni 2013.12.18 37668
1109 Develop [ios] iOS 4.0 beta 에서 3.1.3으로 다운그레이드 하는 법 file hooni 2013.04.23 37495
1108 Etc [svn] 콘솔에서 svn 사용시 레티나용 이미지 add 안될 때.. hooni 2013.09.25 37477
1107 System/OS 맥에서 파일공유 (윈도우,맥) file hooni 2013.04.25 37296
1106 System/OS [mac] Mac에서 Mac으로 원격제어하기 (맥에서 맥으로) file hooni 2013.10.08 36978
1105 Develop [js] jQuery 치트 시트 hooni 2013.12.18 36249
1104 Develop [php] 몽이가 준 ajax 채팅 소스 ㅋㅋ file hooni 2013.04.23 36174
1103 Develop [ios] iOS 6.0 이상 회전 하기 (이전 버전과 비교 변경 부분) file hooni 2014.01.27 34180
1102 System/OS [sql] 조회구문(select)에서 중복 데이터를 한 번만 출력 (distinct) 1 hooni 2013.04.23 33897
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 98 Next
/ 98