APNs 맛 보기.

2012. 11. 15. 16:06제2외국어/iOS

Apple Push Notification service 맛보기.

< 필수 >
: 애플 개발자 (개인 or 기업) 계정 보유.

< 맛보기 환경 및 툴>
: Mac OS X 10.7.5 ( iMac 27 ) , xCode4.5, 터미널

<순서>
1. iOS Provisioning Portal 에서 App IDs 생성



2. App IDs 에서 Configure App ID 를 통해 APNs 인증서 만들기 -> 다운
: 상업용이 아니라 개발용(테스트 목적이기에) 으로 Configure
( 이 때 .csr 파일을 만들어야 되는데... 누구나 알꺼라고 생각하고 생략하겠습니다. )



3. Provisioning 생성 ( 방금 만든 App IDs와 연결 ) -> 다운


4. xCode를 통해 프로젝트 생성 ( App IDs 에서 적었던 Bundle Identifier 와 똑같이 입력 )


5. 생성한 프로젝트의 AppDelegate.m 에 구현
    5-1. APNs 서비스 허용하게 만들기
    : 가끔씩 순서대로 따라해도, 푸쉬를 허락하겠습니까? 라는 메시지가 안 뜰때가 있습니다.
      이 때에는 다시 Provisioning 을 지운후 다시 차근히 해보시는 법이 답입니다.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.
        // Let the device know we want to receive push notifications
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];    

            return YES;
        }

: 허락할 경우 설정 -> 알림 에 보시면 이렇게 방금 만든 Test 앱이 있습니다.


    5-2. Device Token 받기
    : Device Token 은 서버에서 해당 Device 로 메시지를 보낼 때 반드시 필요하다.
    ( 실제 구현시에는 이 Token을 서버로 꼭! 보내주어야 한다. )
    <성공 시>
        - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:                  (NSData*)deviceToken
        {
            NSLog(@"My token is: %@", deviceToken);
          }

    <실패 시>
    
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
    {
        NSLog(@"Failed to get token, error: %@", error);    
    }

    5-3. Push 메시지 받았을 때의 기능 구현
     : 밑에 함수는 간단히 메시지를 받았을 때 알림창으로 받은 메시지를 보여주는 함수입니다.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSString *string = [NSString stringWithFormat:@"%@", userInfo];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:string delegate:nil
                                          cancelButtonTitle:@"OK"   otherButtonTitles:nil];
    [alert show]; 
}


6. TEST 해보기
: 이 부분은 맥이라면 아주 쉽게 스윽지나갈 수 있습니다. ( 아래 참고 사이트에 있는 내용이지만 보기쉽게만 적었습니다. )




[Pem 파일 만들기]
    1. APNs 서비스를 위해 만들었던 CSR 파일
    2. (개발용) APNs 인증서를 클릭하여 키체인에 등록한 후 개인키와 함깨 내보내기를 통해 .p12파일 생성(비밀번호도 같이)
    ( 편하게 key.p12 로 명칭 )
    3. Provisioning 파일 , aps_developer.cer
    ( 편하게 cert.cer 로 명칭 )

[순서]
1. 3번의 aps_developer.cer 파일을 .pem으로 바꾸기

 openssl x590 -in cert.cer -inform der -out cert.pem 

2. 2번의 .p12 파일을 .pem으로 바꾸기

 openssl pkcs -out key.pem -in key.p12
 그리고 비밀번호 생성

3. 순서 1-2번의 .pem 파일들을 하나의 .pem으로 바꾸기

 cat cert.pem key.pem > ck.pem

simplepush.php

- php 파일입니다.

4. 그리고 첨부파일에 있는 .php 파일을 약간 수정, 위에 만들었던 ck.pem 파일과 한곳에 넣은 후!

// Put your device token here (without spaces):
$deviceToken = '0f744707bebcf74f9b7c25d48e3358945f6aa01da5ddb387462c7eaf61bbad78';
 
// Put your private key's passphrase here:
$passphrase = 'password';
 
// Put your alert message here: 
$message = 'My first push notification!'; 

개발서버는 gateway.sandbox.push.apple.com:2195

실제서버는 gateway.push.apple.com:2195


5. 두 파일이 있는 곳으로 cd 로 이동 후에 php 실행

 php push.php
 Connected to APNS
 Message successfully delivered
라고 떳다면 폰을 확인.


Push 메시지가 온걸 확인할 수 있습니다.





<참고 사이트>
: APNs 테스트 부터, 서버를 이용해 메시지 보내는 부분까지 자세히 나와있다. (Best)
Tutorial: iOS Push Notification Services For Beginners
Apple Push Notification Services Tutorial: Part 1/2
Apple Push Notification Services Tutorial: Part 2/2


ps. 그냥 참고 사이트에 있는 내용 그대로입니다.
특별한거 없습니다. 그냥 보기 편하게 정리한 정도입니다. 
더 자세한부분을 원하시면 튜토리얼 part 1/2부분을 정독하시면 됩니다.