개발환경

Xcode 8.2.1

Phonegap ios 3.9.2 (2017-01-23 기준 최신버전(4.3.1) 이지만 Phonegap Pushplugin Phonegap 4.0버전이상부터 이슈가있어 3.9.2 버전으로 진행)

Mac OS Sierra


Phonegap 에서는 기본적으로 공식지원되는 플러그인 외에 

third party 플러그인으로 외부플러그인을 사용 할 수 있습니다


이번 포스팅에서 다룰 내용은 

third party 플러그인 중에 알림(Push)에 관한 플러그인인 PushPlugin 을 사용하여

Phonegap 에서의 APNS 를 구현하려고 합니다.


https://github.com/phonegap-build/PushPlugin


구현하기에 앞서 우선 플러그인을 설치해야합니다.


프로젝트의 루트폴더에서 터미널을 실행하고 명령어를 실행합니다.

1
phonegap local plugin add https://github.com/phonegap-build/PushPlugin.git  



설치완료 된 후 

프로젝트빌드를 하지않은 상태라면 project/platform 에서 명령어를 실행합니다.

1
phonegap build ios@3.9.2



여기서 중요한점은 

2017-01-24 기준으로 Phonegap 의 IOS 최신버전은 4.3.1 이지만 

PushPlugin 이 Phonegap IOS 4.0 이상버전에서 빌드가 되지않는 이슈가 있어서 

이슈가해결된 버전이 새로 업데이트 되지않는이상 

PushPlugin 을 사용할 수 있는 최신버전인 3.9.2 로 빌드를 해야합니다.


PushPlugin 을 쓰지않는 프로젝트를 진행하신다면 상관없이 최신버전으로 빌드하시면됩니다.

1
phonegap build ios



정상적으로 빌드가 완료 되었다면 platform/ios 로 빌드된 폴더가 생성됩니다.




빌드완료 후 필요한 파일들을 프로젝트안에 넣어줘야합니다.

프로젝트루트폴더/plugins/com.phonegap.plugins.PushPlugin/www 에 들어가시면

PushNotification.js 라는 파일을 찾을수 있습니다.

이 파일을 

프로젝트루트폴더/www/js 로 복사합니다.


완료 후 최신버전의 jquery 파일을 다운로드받아

https://blog.jquery.com/2016/09/22/jquery-3-1-1-released/

같은 폴더에 똑같이 복사해줍니다.

제가 사용한 버전은 3.1.1 입니다.


복사가 잘 되었다면 이제 코딩을 할 차례입니다.

platform/ios/project.xcodeproj 을 실행합니다.

대략적인 프로젝트 구성입니다.



최상단에있는 config.xml 에 밑에 코드를 추가해줍니다.

1
2
3
<feature name="PushPlugin">
      <param name="ios-package" value="PushPlugin"/>
</feature>





여기서도 중요한점이 있습니다.

Phonegap 에서는 변경점이 생길때마다 

터미널에서 명령어로 반영을 시켜줘야합니다.

지금말고도 앞으로 변경점이 생길때마다 반영시켜줘야하니 꼭 기억하시길바랍니다.

1
phonegap prepare




반영까지 잘 되었다면 이제 html파일에 코딩을 할 차례입니다.

제가 구성한 코드그대로 복사해서 쓰셔도 동작할 것입니다.

잘모르시는분이 계시다면 그대로 복사해서 쓰셔도되고

웹을 어느정도 해보신 분 이라면 금방 응용해서 쓰실 수 있으실 것입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<!DOCTYPE html>
<!--
    Copyright (c) 2012-2016 Adobe Systems Incorporated. All rights reserved.
 
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at
 
    http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>
 
<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
    <!-- Good default declaration:
    * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
    * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
    * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
        * Enable inline JS: add 'unsafe-inline' to default-src
        * Enable eval(): add 'unsafe-eval' to default-src
    * Create your own at http://cspisawesome.com
    -->
    <!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-inline' https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *" /> -->
 
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <title>Hello World</title>
</head>
 
<body>
    <div class="app">
        <h1>PhoneGap</h1>
        <div id="deviceready" class="blink">
            <p class="event listening">Connecting to Device</p>
            <p class="event received">Device is Ready</p>
        </div>
    </div>
    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script src="js/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="js/PushNotification.js"></script>
    <script type="text/javascript">
        
    // 디바이스에서 deviceready event 를 캐치하여 알림서비스권한을 등록한다.
    document.addEventListener("deviceready", function(){
                                  window.plugins.pushNotification.register(tokenHandler, errorHandler, {
                                                                           "badge":"true", // 뱃지기능사용
                                                                           "sound":"true", // 사운드기능사용
                                                                           "alert":"true", // alert기능사용
                                                                           "ecb": "onNotificationAPN"
                                                                           // 알림이 오면 onNotificationAPN 함수를 실행할 수 있도록 ecb에 등록한다.
                                                                           });
                                  });
 
    // Push 서비스가 활성화 되었을때 디바이스 토큰을 수신해 출력해준다.
    // 서버와 Push서비스를 연동할시에 tokenHandler() 안에서 서버로 토큰을 전송해준다.
    function tokenHandler(result){
        console.log('deviceToken:' + result);
    }
    
    // 에러처리 핸들러
    function errorHandler(err){
        console.log('error:' + err);
    }
    
    // 알림처리 완료 후에 실행될 콜백 핸들러
    function successHandler(result){
        console.log('result:'+result);
    }
    
    // IOS 버전 Push 수신 함수
    function onNotificationAPN(push_noti){
       
        // 알림메세지에 title,body가 없을때
        // if (push_noti.alert){
        //   navigator.notification.alert(push_noti.alert);
        // }
        
        // 알림메세지에 title,body가 있을때
        if (push_noti.body){
            navigator.notification.alert(
                                         push_noti.body,            // message
                                         complete,                  // callback
                                         push_noti.title,           // title
                                         '확인'                      // buttonName
                                         );
        }
        
        // alert 확인버튼 클릭후 콜백 함수 (선언은 필수, 필요하지않은경우 빈값으로)
        function complete() {
            // do something
        }
        
        // 알림메세지에 sound 값이 있을 경우
        if (push_noti.sound){
            var snd = new Media(push_noti.sound);
            snd.play();
        }
        
        // 알림메세지에 badge 값이 있을 경우
        if (push_noti.badge){
            window.plugins.pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, push_noti.badge);
        }
    }
        </script>
    </body>
</html>
 
cs


작업 후 꼭 하셔야합니다.

1
phonegap prepare



코딩을 완료 하셨다면 이제 APNS 를 쓸 수 있는 작업은 마무리가 되었습니다.

APNS 는 시뮬레이터에서는 사용 할 수 없는 기능이기때문에

반드시 실기기로 테스트 하셔야 합니다.


이제 Push를 보내볼 차례입니다.

완성되어있는 Push서버가 없다면 테스트 Push를 보내줄 수 있는 Mac App 이 있습니다.

https://itunes.apple.com/kr/app/easy-apns-provider-push-notification/id989622350?l=en&mt=12


1. Add Token에는 실기기에 빌드후 실행시 log에 찍히는 Token값을 넣어주시면됩니다.

2. Certificate file 에는 이전 글들에서 받은인증서중에 애플 개발자페이지 에서 받은 aps_development.cer 파일을 넣어줍니다.

3. connect to 에는 개발용 인증서이기 때문에 gateway.sandbox.push.apple.com 로 선택하고 연결합니다.

4. payload 에는 Push에 담아 보낼 데이터값들을 작성합니다.

5. 버튼을 눌러 Push를 전송합니다.

6. 연결을 해제합니다.


대략적인 설명은 드렸고 직접 이것저것 Push를 보내보시면서 익히시길 권장합니다.




이로써 Phonegap APNS 기능구현을 마무리했습니다.

Push 로 수신하는 JSON 데이터는 응용하셔서 사용하시길 바랍니다.

생각보다 복잡하지 않은 구조로 간단하게 Phonegap 에 Push 서비스를 구현하였는데요.

혹시나 같은 기능을 구현해야 하시는분들에게 조금이나마 도움이 되길 바랍니다.


개발환경

Xcode 8.2.1

Phonegap ios 3.9.2 (2017-01-23 기준 최신버전(4.3.1) 이지만 Phonegap Pushplugin Phonegap 4.0버전이상부터 이슈가있어 3.9.2 버전으로 진행)

Mac OS Sierra


선행조건

1.  개인인증서 발급 ( http://ginjo.tistory.com/9 )

2. 개인인증서를 이용한 애플인증서 발급 ( http://ginjo.tistory.com/10 )


선행조건을 다 완료한 상태라면 키체인에 인증서파일이 있습니다





오른쪽 클릭 -> 보내기





보내기는 2번해야되는데 

최대한 모아두기편하도록 따로폴더를 생성하고

cert.p12 , key.p12 로 저장합니다





저장을 하면 암호설정 부분이 나오는데 원하시는 암호로 설정하시면됩니다.





정상적으로 완료 되었다면 만들어둔 폴더에

cert.p12 , key.p12 파일이 생성되어있습니다

이제 이 두파일의 형식을 변경하여 사용할예정입니다

만들어둔 폴더 안에서 터미널을 실행해서

명령어 몇가지를 입력할텐데요

똑같이 입력만하시면 정상적으로 완료되니 정확히 입력해주세요


1
openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12


ㄴ 명령어를 입력하시면 비밀번호입력이 나오는데 방금 설정하신 비밀번호를 입력하시면됩니다

1
openssl pkcs12 -nocerts -out key.pem -in key.p12



ㄴ 명령어를 입력하시면 똑같이 비밀번호입력이 나오는데 입력하신후에 cert.pem 생성과는다르게 비밀번호 설정이 한번더 나옵니다. 원하시는비밀번호 다시 설정해주시면됩니다.

여기까지 완료 되었다면 
폴더안에는 
cert.p12 , key.p12 , cert.pem , key.pem 
파일이 저장되어있습니다.

이제 key.pem 파일을 변경하기 위해 다시한번 터미널에 입력합니다

1
openssl rsa -in key.pem -out key.unencrypted.pem



ㄴ 위에서 key.pem 파일을 생성할때 설정했던 비밀번호를 입력합니다

마지막으로 cert.pem 파일과 key.unencrypted.pem 을 합쳐 apns.pem 파일을 생성합니다

1
cat cert.pem key.unencrypted.pem > apns.pem



여기까지 완료가 되었다면 


6개의 파일이 생성되어있습니다


인증서 생성은 마무리가 되었고

APNS 에서는 apns.pem 파일을 사용하시면되고

상황에따라 p12 파일이나 다른 pem 파일이 필요할때가 있으니

가급적이면 계속 저장해두시길 권장합니다.



다음포스팅에서는 Phonegap 에서  APNS 를 구현하는 방법에 대해 포스팅하겠습니다.



개발환경

Xcode 8.2.1

Phonegap ios 3.9.2 (2017-01-23 기준 최신버전(4.3.1) 이지만 Phonegap Pushplugin Phonegap 4.0버전이상부터 이슈가있어 3.9.2 버전으로 진행)

Mac OS Sierra


선행조건

개인인증서가 발급된 상태여야 합니다

http://ginjo.tistory.com/9


애플 개발자 사이트 접속

https://developer.apple.com/account/





Certificates, IDs & Profiles 클릭 -> App IDs 클릭 -> Push Notification 기능을 넣고자하는 앱 클릭





현재 저는 Push 기능이 들어가있는 상태로 

Push Notification 이  Enable 상태로 되어있지만 원래라면 Disabled 되어있습니다

확인한 후 Edit 클릭





Push Notification 항목으로 이동해서 중요한부분

Development SSL Certificate 는 개발중일때 테스트용도

Production SSL Certificate 는 앱출시때 사용용도

출시전이라면 이미 충분한 개발완료 되었을 시점으로 사용법도 충분히 숙지했을거라 가정합니다

개발용도로 Development SSL Certificate -> Create Certificate





첫번째 글에서 발급받은 개인인증서를 업로드





발급완료된 애플 인증서를 원하는위치에 다운로드





발급받은 애플 인증서를 실행시키면 키체인에 인증서가 활성화됩니다






다음 포스팅에서는 발급받은 애플인증서를 이용한 키파일 생성에 대해 포스팅하겠습니다.




개발환경

Xcode 8.2.1

Phonegap ios 3.9.2 (2017-01-23 기준 최신버전(4.3.1) 이지만 Phonegap Pushplugin 이 Phonegap 4.0버전이상부터 이슈가있어 3.9.2 버전으로 진행)

Mac OS Sierra



Push Notification 을 위한 개인인증서 발급 

ㄴ 키체인 접근 실행





키체인 접근 실행

ㄴ 인증서 지원 -> 인증 기관에서 인증서 요청





인증 기관에서 인증서 요청

ㄴ 사용자 이메일 주소 : 앱에 Signing 할 개발자 등록된 E-mail

ㄴ 일반 이름 : 개발자 이름

ㄴ CA 이메일 주소 : 해당사항없음

ㄴ 요청항목 : CA로 이메일보냄 (체크해제)

     디스크에 저장됨(체크)

     본인이 키 쌍 정보 지정(체크)





원하는 위치에 이름그대로 저장





키 쌍 정보

ㄴ 그대로 저장





개인 인증서 발급 완료





다음 포스팅에서는 발급받은 개인인증서를 이용한 애플인증서를 받는방법에 대해 포스팅하겠습니다.

기준 버전

XCode 8.2.1

Phonegap 4.3.1

Mac OS Sierra


필수 설치 


1. XCode 설치

ㄴ  AppStore XCode 검색 후 설치 (무조건 최신버전으로 설치)

  https://developer.apple.com/downloads (버전 선택 가능)


2. Homebrew 설치

ㄴ http://brew.sh/index_ko.html


3. Node.js  설치

ㄴ 터미널에서 $ brew install node


4. Phonegap 설치

ㄴ 터미널에서 $ sudo npm install -g phonegap


본격적인 Phonegap 시작


1. 프로젝트를 생성하고싶은 폴더로 이동


2. 프로젝트 생성

ㄴ 터미널에서  $ phonegap create aaa (aaa = 프로젝트폴더이름com.aaa.aaa(com.aaa.aaa = 번들 ID)  aaa (aaa = 프로젝트이름)

 $ phonegap create aaa com.aaa.aaa aaa


3. IOS 용으로 프로젝트 빌드

ㄴ 생성된 프로젝트폴더안에 platform 폴더로이동

ㄴ 터미널에서 $ phonegap build ios


4. Phonegap Plugin 설치 (필수설치아님 , 사용하고싶은 Plugin 설치)

ㄴ 루트폴더에서 터미널 $ phonegap plugin add 플러그인이름

ㄴ 삭제하고싶을땐 $ phonegap plugin remove 플러그인이름


5. 마무리

ㄴ 3번이 성공적으로 완료되었다면 platform 폴더안에 ios 폴더가 생성되어있음.

ㄴ aaa.xcodeproj 실행 후 시작!


etc.

ㄴ 코딩후 시뮬레이터나 실기기 테스트전에

ㄴ $ phonegap prepare 로 프로젝트에 반영시켜준뒤 테스트해야함



+ Recent posts