개발환경

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 서비스를 구현하였는데요.

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


+ Recent posts