Merge branch 'master' into dev

This commit is contained in:
Hevin 2016-03-04 13:49:13 +08:00
commit dde913b922
23 changed files with 1205 additions and 736 deletions

View File

@ -1,6 +1,17 @@
l## JPush PhoneGap Plugin ## ## JPush PhoneGap Plugin ##
jpush-phonegap-plugin 支持 iOS,Android 的推送插件。
**功能特性:**
>+ 发送推送通知
+ 发送推送自定义消息
+ 设置推送标签和别名
+ 设置角标iOS
*如需要 IM 功能插件,请关注[jmessage-phonegap-plugin](https://github.com/jpush/jmessage-phonegap-plugin)*
## 安装 ##
###准备工作 ###准备工作
1. cordova create 文件夹名字 包名 应用名字 1. cordova create 文件夹名字 包名 应用名字
@ -19,30 +30,32 @@ l## JPush PhoneGap Plugin ##
###Cordova CLI/Phonegap 安装 Android & iOS ###Cordova CLI/Phonegap 安装 Android & iOS
3. 使用git命令将jpush phonegap插件下载的本地,将这个目录标记为`$JPUSH_PLUGIN_DIR` 1). 安装JPush PhoneGap Plugin。 有两种方法。
git clone https://github.com/jpush/jpush-phonegap-plugin.git 方法一: 在线安装
cordova plugin add https://github.com/jpush/jpush-phonegap-plugin.git --variable API_KEY=your_jpush_appkey
方法二:下载到本地再安装
使用git命令将jpush phonegap插件下载的本地,将这个目录标记为`$JPUSH_PLUGIN_DIR`
4. 将`$JPUSH_PLUGIN_DIR/plugin.xml`文件中的AppKey替换为在Portal上注册该应用的的Key,例如9fed5bcb7b9b87413678c407 git clone https://github.com/jpush/jpush-phonegap-plugin.git
cordova plugin add $JPUSH_PLUGIN_DIR --variable API_KEY=your_jpush_appkey
<meta-data android:name="JPUSH_APPKEY" android:value="your appkey"/>
4. 打开`$JPUSH_PLUGIN_DIR/src/ios/PushConfig.plist`文件将文件中的`7d431e42dfa6a6d693ac2d04`替换为在Portal上注册该应用的的Key,例如9fed5bcb7b9b87413678c407
5. 在`$JPUSH_PLUGIN_DIR/src/android/JPushPlugin.java` 文件`import your.package.name.R`替换为在Portal上注册该应用的包名例如(com.thi.pushtest)
2). 安装org.apache.cordova.device
cordova plugin add org.apache.cordova.device
6. cordova cli 添加jpush phonegap插件和依赖的device插件: 3). 在js中调用函数,初始化jpush sdk
cordova plugin add $JPUSH_PLUGIN_DIR window.plugins.jPushPlugin.init();
cordova plugin add org.apache.cordova.device //由于phonegap插件采用了Lazy load的特性 所以这里建议在js文件能执行的最开始就加
7. 在js中调用函数,初始化jpush sdk
window.plugins.jPushPlugin.init();
//由于phonegap插件采用了Lazy load的特性 所以这里建议在js文件能执行的最开始就加
### Android 手工安装 ### Android 手工安装
@ -66,12 +79,6 @@ l## JPush PhoneGap Plugin ##
该项目基于cordova实现目前无法使用'phonegap build'云服务进行打包,建议使用本地环境进行打包 该项目基于cordova实现目前无法使用'phonegap build'云服务进行打包,建议使用本地环境进行打包
###常见错误
1. androd
eclipse中phonegap工程import之后出现:`Type CallbackContext cannot be resolved to a type`
解决方案eclipse中右键单击工程名Build Path->Config Build Path->Projects->选中 工程名称CordovaLib->点击 add
### API说明 ### API说明
插件的API集中在JPushPlugin.js文件中,这个文件的位置如下 插件的API集中在JPushPlugin.js文件中,这个文件的位置如下
@ -186,5 +193,20 @@ l## JPush PhoneGap Plugin ##
[Android API详细说明](document/Android_detail_api.md) [Android API详细说明](document/Android_detail_api.md)
###常见问题
####1. androd
eclipse中phonegap工程import之后出现:`Type CallbackContext cannot be resolved to a type`
解决方案eclipse中右键单击工程名Build Path->Config Build Path->Projects->选中 工程名称CordovaLib->点击 add
####2. iOS 设置/修改 APP_KEY
在PushConfig.plist 中修改。PushConfig.plist 其他值说明:
CHANNEL 渠道标识
IsProduction 是否生产环境(暂未启用)
###更多 ###更多
[JPush官网文档](http://docs.jpush.io/) [JPush官网文档](http://docs.jpush.io/)

View File

@ -271,7 +271,7 @@ ps点击通知后传递的json object 保存在window.plugins.jPushPlugin.ope
#### event - jpush.receiveNotification #### event - jpush.receiveNotification
点击通知进入应用程序时会出发改事件 点击通知进入应用程序时会触发该事件
#####代码示例 #####代码示例

View File

@ -52,7 +52,8 @@ duration 自定义的页面时间
### 设置Badge ### 设置Badge
#### API - setBadge,resetBadge #### API - setBadge,resetBadge
badge是iOS用来标记应用程序状态的一个数字出现在程序图标右上角。 JPush封装badge功能允许应用上传badge值至JPush服务器由JPush后台帮助管理每个用户所对应的推送badge值简化了设置推送badge的操作。 JPush封装badge功能允许应用上传badge值至JPush服务器由JPush后台帮助管理每个用户所对应的推送badge值简化了设置推送badge的操作。
(本接口不会直接改变应用本地的角标值. 要修改本地badege值使用 setApplicationIconBadgeNumber
实际应用中开发者可以直接对badge值做增减操作无需自己维护用户与badge值之间的对应关系。 实际应用中开发者可以直接对badge值做增减操作无需自己维护用户与badge值之间的对应关系。
##### 接口定义 ##### 接口定义
@ -74,6 +75,7 @@ value 取值范围:[0,99999]
#### API - setApplicationIconBadgeNumber #### API - setApplicationIconBadgeNumber
本接口直接改变应用本地的角标值.
设置iOS的角标当设置badge0时为清除角标 设置iOS的角标当设置badge0时为清除角标
##### 接口定义 ##### 接口定义
@ -92,6 +94,27 @@ value 取值范围:[0,99999]
} }
#### API - getApplicationIconBadgeNumber
获取iOS的角标值
##### 接口定义
window.plugins.jPushPlugin.getApplicationIconBadgeNumber(callback)
##### 参数说明
- callback 回调函数
#####代码示例
```
window.plugins.jPushPlugin.getApplicationIconBadgeNumber(function(data){
console.log(data);
});
```
### 本地通知 ### 本地通知
### 日志等级设置 ### 日志等级设置

View File

@ -1,210 +1,224 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Phonegap Sample App</title> <title>Phonegap Sample App</title>
<link href="css/jquery.mobile-1.1.1.css" rel="stylesheet" type="text/css"/> <link href="css/jquery.mobile-1.1.1.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.1.1.js"></script> <script type="text/javascript" src="js/jquery.mobile-1.1.1.js"></script>
<script type="text/javascript" src="cordova.js"></script> <script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript"> <script type="text/javascript">
var onDeviceReady = function(){ var onDeviceReady = function () {
console.log("JPushPlugin:Device ready!") console.log("JPushPlugin:Device ready!");
initiateUI(); initiateUI();
} };
var onGetRegistradionID = function(data) {
try{
console.log("JPushPlugin:registrationID is "+data)
$("#registrationid").html(data); function getRegistrationID() {
window.plugins.jPushPlugin.getRegistrationID(onGetRegistradionID);
}
var onGetRegistradionID = function (data) {
try {
console.log("JPushPlugin:registrationID is " + data);
if (data.length == 0) {
var t1 = window.setTimeout(getRegistrationID, 1000);
} }
catch(exception){ $("#registrationid").html(data);
}
catch (exception) {
console.log(exception);
}
};
var onTagsWithAlias = function (event) {
try {
console.log("onTagsWithAlias");
var result = "result code:" + event.resultCode + " ";
result += "tags:" + event.tags + " ";
result += "alias:" + event.alias + " ";
$("#tagAliasResult").html(result);
}
catch (exception) {
console.log(exception)
}
};
var onOpenNotification = function (event) {
try {
var alertContent;
if (device.platform == "Android") {
alertContent = window.plugins.jPushPlugin.openNotification.alert;
} else {
alertContent = event.aps.alert;
}
alert("open Notificaiton:" + alertContent);
}
catch (exception) {
console.log("JPushPlugin:onOpenNotification" + exception);
}
};
var onReceiveNotification = function (event) {
try {
var alertContent;
if (device.platform == "Android") {
alertContent = window.plugins.jPushPlugin.receiveNotification.alert;
} else {
alertContent = event.aps.alert;
}
$("#notificationResult").html(alertContent);
}
catch (exeption) {
console.log(exception)
}
};
var onReceiveMessage = function (event) {
try {
var message;
if (device.platform == "Android") {
message = window.plugins.jPushPlugin.receiveMessage.message;
} else {
message = event.content;
}
//var extras = window.plugins.jPushPlugin.extras
$("#messageResult").html(message);
}
catch (exception) {
console.log("JPushPlugin:onReceiveMessage-->" + exception);
}
};
var initiateUI = function () {
try {
window.plugins.jPushPlugin.init();
getRegistrationID();
if (device.platform != "Android") {
window.plugins.jPushPlugin.setDebugModeFromIos();
window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
} else {
window.plugins.jPushPlugin.setDebugMode(true);
}
}
catch (exception) {
console.log(exception);
}
$("#setTagWithAliasButton").click(function (ev) {
// window.plugins.jPushPlugin.getApplicationIconBadgeNumber(function(data){
// console.log(data);
// });
try {
var tag1 = $("#tagText1").attr("value");
var tag2 = $("#tagText2").attr("value");
var tag3 = $("#tagText3").attr("value");
var alias = $("#aliasText").attr("value");
var dd = [];
if (tag1 == "" && tag2 == "" && tag3 == "") {
}
else {
if (tag1 != "") {
dd.push(tag1);
}
if (tag2 != "") {
dd.push(tag2);
}
if (tag3 != "") {
dd.push(tag3);
}
}
window.plugins.jPushPlugin.setTagsWithAlias(dd, alias);
}
catch (exception) {
console.log(exception); console.log(exception);
} }
} })
};
var onTagsWithAlias = function(event){ document.addEventListener("jpush.setTagsWithAlias", onTagsWithAlias, false);
try{ document.addEventListener("deviceready", onDeviceReady, false);
console.log("onTagsWithAlias"); document.addEventListener("jpush.openNotification", onOpenNotification, false);
var result="result code:"+event.resultCode+" "; document.addEventListener("jpush.receiveNotification", onReceiveNotification, false);
result+="tags:"+event.tags+" "; document.addEventListener("jpush.receiveMessage", onReceiveMessage, false);
result+="alias:"+event.alias+" ";
$("#tagAliasResult").html(result);
}
catch(exception){
console.log(exception)
}
}
var onOpenNotification = function(event){
try{
var alertContent
if(device.platform == "Android"){
alertContent=window.plugins.jPushPlugin.openNotification.alert;
}else{
alertContent = event.aps.alert;
}
alert("open Notificaiton:"+alertContent);
}
catch(exception){
console.log("JPushPlugin:onOpenNotification"+exception);
}
}
var onReceiveNotification = function(event){
try{
var alert
if(device.platform == "Android"){
alert = window.plugins.jPushPlugin.receiveNotification.alert;
}else{
alert = event.aps.alert;
}
$("#notificationResult").html(alert);
}
catch(exeption){
console.log(exception)
}
}
var onReceiveMessage = function(event){
try{
var message
if(device.platform == "Android"){
message = window.plugins.jPushPlugin.receiveMessage.message;
}else{
message = event.content;
}
//var extras = window.plugins.jPushPlugin.extras
$("#messageResult").html(message);
}
catch(exception){
console.log("JPushPlugin:onReceiveMessage-->"+exception);
}
}
var initiateUI = function(){
try{
window.plugins.jPushPlugin.init();
window.plugins.jPushPlugin.getRegistrationID(onGetRegistradionID);
if(device.platform != "Android"){
window.plugins.jPushPlugin.setDebugModeFromIos();
window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
}else{
window.plugins.jPushPlugin.setDebugMode(true);
}
}
catch(exception){
console.log(exception);
}
$("#setTagWithAliasButton").click(function(ev) {
try{
var tag1 = $("#tagText1").attr("value");
var tag2 = $("#tagText2").attr("value");
var tag3 = $("#tagText3").attr("value");
var alias = $("#aliasText").attr("value");
var dd = [];
if(tag1==""&&tag2==""&&tag3==""){
}
else{
if(tag1 != ""){
dd.push(tag1);
}
if(tag2 != ""){
dd.push(tag2);
}
if(tag3 != ""){
dd.push(tag3);
}
}
window.plugins.jPushPlugin.setTagsWithAlias(dd,alias);
}
catch(exception){
console.log(exception);
}
})
}
document.addEventListener("jpush.setTagsWithAlias", onTagsWithAlias, false);
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("jpush.openNotification", onOpenNotification, false);
document.addEventListener("jpush.receiveNotification", onReceiveNotification, false);
document.addEventListener("jpush.receiveMessage", onReceiveMessage, false);
//jpush.receiveMessage //jpush.receiveMessage
</script> </script>
</head> </head>
<body> <body>
<div data-role="page" id="page"> <div data-role="page" id="page">
<div data-role="content"> <div data-role="content">
<form> <form>
<div class="ui-body ui-body-b"> <div class="ui-body ui-body-b">
<div data-role="fieldcontain"> <div data-role="fieldcontain">
<center><h3>JPushPlugin Example</h3></center> <center><h3>JPushPlugin Example</h3></center>
<span name="alias" id="alias"></span><hr /> <span name="alias" id="alias"></span>
<label>RegistrationID: </label> <hr/>
<label id="registrationid">null</label> <label>RegistrationID: </label>
</div> <label id="registrationid">null</label>
<div data-role="fieldcontain"> </div>
<label>Tags: </label> <div data-role="fieldcontain">
<table> <label>Tags: </label>
<tr> <table>
<td> <tr>
<input type="text" id="tagText1"/> <td>
</td> <input type="text" id="tagText1"/>
</tr> </td>
<tr> </tr>
<td> <tr>
<input type="text" id="tagText2"/> <td>
</td> <input type="text" id="tagText2"/>
</tr> </td>
<tr> </tr>
<td> <tr>
<input type="text" id="tagText3"> <td>
</td> <input type="text" id="tagText3">
</tr> </td>
</table> </tr>
<label>Alias: </label> </table>
<table> <label>Alias: </label>
<tr> <table>
<td> <tr>
<input type="text" id="aliasText"> <td>
</td> <input type="text" id="aliasText">
</tr> </td>
</table> </tr>
</div> </table>
<div data-role="fieldcontain"> </div>
<input type="button" id="setTagWithAliasButton" value="Add tag and alias" /> <div data-role="fieldcontain">
</div> <input type="button" id="setTagWithAliasButton" value="Add tag and alias"/>
<div data-role="fieldcontain"> </div>
<label id="tagAliasPrompt" >设置tag/alias结果 </label> <div data-role="fieldcontain">
<label id="tagAliasResult" >null</label> <label id="tagAliasPrompt">设置tag/alias结果 </label>
</div> <label id="tagAliasResult">null</label>
<div data-role="fieldcontain"> </div>
<label id="notificationPrompt" >接受的通知内容:</label> <div data-role="fieldcontain">
<label id="notificationResult" >null</label> <label id="notificationPrompt">接受的通知内容:</label>
</div> <label id="notificationResult">null</label>
<div data-role="fieldcontain"> </div>
<label id="messagePrompt" >接受的自定义消息:</label> <div data-role="fieldcontain">
<label id="messageResult" >null</label> <label id="messagePrompt">接受的自定义消息:</label>
</div> <label id="messageResult">null</label>
</div>
</div>
</form>
</div> </div>
</form>
</div>
</div> </div>
</body> </body>
</html> </html>

View File

@ -2,7 +2,7 @@
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:android="http://schemas.android.com/apk/res/android"
id="cn.jpush.phonegap.JPushPlugin" id="cn.jpush.phonegap.JPushPlugin"
version="2.0.2"> version="2.1.0">
<name>JPush Plugin</name> <name>JPush Plugin</name>
<description>JPush for cordova plugin</description> <description>JPush for cordova plugin</description>
@ -10,12 +10,14 @@
<keywords>JPush,push</keywords> <keywords>JPush,push</keywords>
<license>Apache 2.0 License</license> <license>Apache 2.0 License</license>
<preference name="API_KEY" />
<engines> <engines>
<engine name="cordova" version=">=3.0"/> <engine name="cordova" version=">=3.0"/>
</engines> </engines>
<js-module src="www/JPushPlugin.js" name="JPushPlugin"> <js-module src="www/JPushPlugin.js" name="JPushPlugin">
<clobbers target="window.plugins.jPushPlugin"/> <clobbers target="jPushPlugin"/>
</js-module> </js-module>
<platform name="ios"> <platform name="ios">
@ -28,8 +30,8 @@
<header-file src="src/ios/Plugins/JPushPlugin.h"/> <header-file src="src/ios/Plugins/JPushPlugin.h"/>
<source-file src="src/ios/Plugins/JPushPlugin.m"/> <source-file src="src/ios/Plugins/JPushPlugin.m"/>
<header-file src="src/ios/lib/APService.h" /> <header-file src="src/ios/lib/JPUSHService.h" />
<source-file src="src/ios/lib/libPushSDK-1.8.3.a" framework="true" /> <source-file src="src/ios/lib/jpush-ios-2.1.0.a" framework="true" />
<header-file src="src/ios/Plugins/AppDelegate+JPush.h"/> <header-file src="src/ios/Plugins/AppDelegate+JPush.h"/>
<source-file src="src/ios/Plugins/AppDelegate+JPush.m"/> <source-file src="src/ios/Plugins/AppDelegate+JPush.m"/>
<resource-file src="src/ios/PushConfig.plist" /> <resource-file src="src/ios/PushConfig.plist" />
@ -43,10 +45,17 @@
<framework src="Security.framework" weak="true" /> <framework src="Security.framework" weak="true" />
<framework src="libz.dylib" weak="true" /> <framework src="libz.dylib" weak="true" />
<config-file target="*PushConfig.plist" parent="APP_KEY">
<string>$API_KEY</string>
</config-file>
</platform> </platform>
<!-- android --> <!-- android -->
<platform name="android"> <platform name="android">
<hook type="after_plugin_add" src="scripts/android-install.js" />
<hook type="after_plugin_install" src="scripts/android-install.js" />
<hook type="before_plugin_rm" src="scripts/android-install.js" />
<hook type="before_plugin_uninstall" src="scripts/android-install.js" />
<config-file target="res/xml/config.xml" parent="/*"> <config-file target="res/xml/config.xml" parent="/*">
<feature name="JPushPlugin"> <feature name="JPushPlugin">
@ -152,14 +161,14 @@
<receiver android:name="cn.jpush.android.service.AlarmReceiver"/> <receiver android:name="cn.jpush.android.service.AlarmReceiver"/>
<!-- Required . Enable it you can get statistics data with channel --> <!-- Required . Enable it you can get statistics data with channel -->
<meta-data android:name="JPUSH_CHANNEL" android:value="developer-default"/> <meta-data android:name="JPUSH_CHANNEL" android:value="developer-default"/>
<meta-data android:name="JPUSH_APPKEY" android:value="your appkey"/> <meta-data android:name="JPUSH_APPKEY" android:value="$API_KEY"/>
</config-file> </config-file>
<source-file src="src/android/jpush-sdk-release1.7.5.jar" target-dir="libs"/> <source-file src="src/android/jpush-android-2.0.6.jar" target-dir="libs"/>
<source-file src="src/android/armeabi/libjpush175.so" target-dir="libs/armeabi"/> <source-file src="src/android/armeabi/libjpush206.so" target-dir="libs/armeabi"/>
<source-file src="src/android/armeabi-v7a/libjpush175.so" target-dir="libs/armeabi-v7a"/> <source-file src="src/android/armeabi-v7a/libjpush206.so" target-dir="libs/armeabi-v7a"/>
<source-file src="src/android/arm64-v8a/libjpush175.so" target-dir="libs/arm64-v8a"/> <source-file src="src/android/arm64-v8a/libjpush206.so" target-dir="libs/arm64-v8a"/>
<source-file src="src/android/JPushPlugin.java" target-dir="src/cn/jpush/phonegap"/> <!--<source-file src="src/android/JPushPlugin.java" target-dir="src/cn/jpush/phonegap"/>-->
<source-file src="src/android/MyReceiver.java" target-dir="src/cn/jpush/phonegap"/> <source-file src="src/android/MyReceiver.java" target-dir="src/cn/jpush/phonegap"/>
<source-file src="src/android/test_notification_layout.xml" target-dir="res/layout"/> <source-file src="src/android/test_notification_layout.xml" target-dir="res/layout"/>
<source-file src="src/android/jpush_notification_icon.png" target-dir="res/drawable"/> <source-file src="src/android/jpush_notification_icon.png" target-dir="res/drawable"/>

View File

@ -0,0 +1,48 @@
#!/usr/bin/env node
module.exports = function (context) {
var path = context.requireCordovaModule('path'),
fs = context.requireCordovaModule('fs'),
shell = context.requireCordovaModule('shelljs'),
projectRoot = context.opts.projectRoot,
ConfigParser = context.requireCordovaModule('cordova-lib/src/configparser/ConfigParser'),
config = new ConfigParser(path.join(context.opts.projectRoot, "config.xml")),
packageName = config.android_packageName() || config.packageName();
console.info("Running android-install.Hook: " + context.hook + ", Package: " + packageName + ", Path: " + projectRoot + ".");
if (!packageName) {
console.error("Package name could not be found!");
return ;
}
// android platform available?
if (context.opts.cordova.platforms.indexOf("android") === -1) {
console.info("Android platform has not been added.");
return ;
}
var targetDir = path.join(projectRoot, "platforms", "android", "src", "cn", "jpush", "phonegap");
targetFile = path.join(targetDir, "JPushPlugin.java");
console.log(targetDir);
if (['after_plugin_add', 'after_plugin_install', 'after_platform_add'].indexOf(context.hook) === -1) {
// remove it?
try {
fs.unlinkSync(targetFile);
} catch (err) {}
} else {
// create directory
shell.mkdir('-p', targetDir);
// sync the content
fs.readFile(path.join(context.opts.plugin.dir, 'src', 'android', 'JPushPlugin.java'), {encoding: 'utf-8'}, function (err, data) {
if (err) {
throw err;
}
data = data.replace(/^import __PACKAGE_NAME__.R;/m, 'import ' + packageName + '.R;');
fs.writeFileSync(targetFile, data);
});
}
};

View File

@ -19,13 +19,15 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.Map.Entry; import java.util.Map.Entry;
import your.package.name.R; import __PACKAGE_NAME__.R;
import cn.jpush.android.api.BasicPushNotificationBuilder; import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.CustomPushNotificationBuilder; import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface; import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.data.JPushLocalNotification; import cn.jpush.android.data.JPushLocalNotification;
import cn.jpush.android.api.TagAliasCallback; import cn.jpush.android.api.TagAliasCallback;
import android.util.Log;
public class JPushPlugin extends CordovaPlugin { public class JPushPlugin extends CordovaPlugin {
private final static List<String> methodList = private final static List<String> methodList =
@ -46,6 +48,7 @@ public class JPushPlugin extends CordovaPlugin {
"setLatestNotificationNum", "setLatestNotificationNum",
"setPushTime", "setPushTime",
"clearAllNotification", "clearAllNotification",
"clearNotificationById",
"addLocalNotification", "addLocalNotification",
"removeLocalNotification", "removeLocalNotification",
"clearLocalNotifications", "clearLocalNotifications",
@ -55,12 +58,16 @@ public class JPushPlugin extends CordovaPlugin {
private ExecutorService threadPool = Executors.newFixedThreadPool(1); private ExecutorService threadPool = Executors.newFixedThreadPool(1);
private static JPushPlugin instance; private static JPushPlugin instance;
private static String TAG = "JPushPlugin";
private static boolean shouldCacheMsg = false;
public static String notificationAlert; public static String notificationAlert;
public static Map<String, Object> notificationExtras=new HashMap<String, Object>(); public static Map<String, Object> notificationExtras=new HashMap<String, Object>();
public static String openNotificationAlert; public static String openNotificationAlert;
public static Map<String, Object> openNotificationExtras=new HashMap<String, Object>(); public static Map<String, Object> openNotificationExtras=new HashMap<String, Object>();
public JPushPlugin() { public JPushPlugin() {
instance = this; instance = this;
} }
@ -68,21 +75,46 @@ public class JPushPlugin extends CordovaPlugin {
@Override @Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) { public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView); super.initialize(cordova, webView);
//JPushInterface.setDebugMode(true);
//JPushPlugin.notificationAlert = alert; Log.i(TAG, "---------------- initialize"+"-"+JPushPlugin.openNotificationAlert + "-" + JPushPlugin.notificationAlert);
//JPushPlugin.notificationExtras = extras;
if(JPushPlugin.openNotificationAlert != null){ shouldCacheMsg = false;
JPushPlugin.transmitOpen(JPushPlugin.openNotificationAlert, JPushPlugin.openNotificationExtras);
} //如果同时缓存了打开事件openNotificationAlert 消息事件notificationAlert只向UI 打开事件
if(JPushPlugin.notificationAlert!=null){ //这样做是为了和iOS 统一
JPushPlugin.transmitReceive(JPushPlugin.notificationAlert, JPushPlugin.notificationExtras); if(JPushPlugin.openNotificationAlert != null){
} JPushPlugin.notificationAlert = null;
JPushPlugin.transmitOpen(JPushPlugin.openNotificationAlert, JPushPlugin.openNotificationExtras);
}
if(JPushPlugin.notificationAlert!=null){
JPushPlugin.transmitReceive(JPushPlugin.notificationAlert, JPushPlugin.notificationExtras);
}
//JPushInterface.init(cordova.getActivity().getApplicationContext()); //JPushInterface.init(cordova.getActivity().getApplicationContext());
} }
public void onPause(boolean multitasking) {
Log.i(TAG, "---------------- onPause");
shouldCacheMsg = true;
}
public void onResume(boolean multitasking) {
shouldCacheMsg = false;
Log.i(TAG, "---------------- onResume"+"-"+JPushPlugin.openNotificationAlert + "-" + JPushPlugin.notificationAlert);
if(JPushPlugin.openNotificationAlert != null){
JPushPlugin.notificationAlert = null;
JPushPlugin.transmitOpen(JPushPlugin.openNotificationAlert, JPushPlugin.openNotificationExtras);
}
if(JPushPlugin.notificationAlert!=null){
JPushPlugin.transmitReceive(JPushPlugin.notificationAlert, JPushPlugin.notificationExtras);
}
}
private static JSONObject notificationObject(String message, private static JSONObject notificationObject(String message,
Map<String, Object> extras) { Map<String, Object> extras) {
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
@ -157,19 +189,18 @@ public class JPushPlugin extends CordovaPlugin {
if (instance == null) { if (instance == null) {
return; return;
} }
if(JPushPlugin.shouldCacheMsg){
return;
}
Log.i(TAG, "---------------- transmitOpen");
JSONObject data = openNotificationObject(alert, extras); JSONObject data = openNotificationObject(alert, extras);
String js = String String js = String
.format("window.plugins.jPushPlugin.openNotificationInAndroidCallback('%s');", .format("window.plugins.jPushPlugin.openNotificationInAndroidCallback('%s');",
data.toString()); data.toString());
// {"alert":"ding",
// "extras":{
// "cn.jpush.android.MSG_ID":"1691785879",
// "app":"com.thi.pushtest",
// "cn.jpush.android.ALERT":"ding",
// "cn.jpush.android.EXTRA":{},
// "cn.jpush.android.PUSH_ID":"1691785879",
// "cn.jpush.android.NOTIFICATION_ID":1691785879,
// "cn.jpush.android.NOTIFICATION_TYPE":"0"}}
try { try {
instance.webView.sendJavascript(js); instance.webView.sendJavascript(js);
@ -182,24 +213,22 @@ public class JPushPlugin extends CordovaPlugin {
} catch (Exception e) { } catch (Exception e) {
} }
JPushPlugin.openNotificationAlert = null;
} }
static void transmitReceive(String alert, Map<String, Object> extras) { static void transmitReceive(String alert, Map<String, Object> extras) {
if (instance == null) { if (instance == null) {
return; return;
} }
if(JPushPlugin.shouldCacheMsg){
return;
}
JSONObject data = openNotificationObject(alert, extras); JSONObject data = openNotificationObject(alert, extras);
String js = String String js = String
.format("window.plugins.jPushPlugin.receiveNotificationInAndroidCallback('%s');", .format("window.plugins.jPushPlugin.receiveNotificationInAndroidCallback('%s');",
data.toString()); data.toString());
// {"alert":"ding",
// "extras":{
// "cn.jpush.android.MSG_ID":"1691785879",
// "app":"com.thi.pushtest",
// "cn.jpush.android.ALERT":"ding",
// "cn.jpush.android.EXTRA":{},
// "cn.jpush.android.PUSH_ID":"1691785879",
// "cn.jpush.android.NOTIFICATION_ID":1691785879,
// "cn.jpush.android.NOTIFICATION_TYPE":"0"}}
try { try {
instance.webView.sendJavascript(js); instance.webView.sendJavascript(js);
@ -209,6 +238,8 @@ public class JPushPlugin extends CordovaPlugin {
} catch (Exception e) { } catch (Exception e) {
} }
JPushPlugin.notificationAlert = null;
} }
@Override @Override
@ -225,7 +256,7 @@ public class JPushPlugin extends CordovaPlugin {
JSONArray.class, CallbackContext.class); JSONArray.class, CallbackContext.class);
method.invoke(JPushPlugin.this, data, callbackContext); method.invoke(JPushPlugin.this, data, callbackContext);
} catch (Exception e) { } catch (Exception e) {
System.out.println(e.toString()); Log.e(TAG,e.toString());
} }
} }
}); });
@ -341,27 +372,15 @@ public class JPushPlugin extends CordovaPlugin {
} }
void setTags(JSONArray data, CallbackContext callbackContext) { void setTags(JSONArray data, CallbackContext callbackContext) {
HashSet<String> tags=null;
try { try {
String tagStr; HashSet<String> tags=new HashSet<String>();
if(data==null){ for(int i=0;i<data.length();i++){
//tags=null; tags.add(data.getString(i));
}else if(data.length()==0) {
tags= new HashSet<String>();
}else{
tagStr = data.getString(0);
String[] tagArray = tagStr.split(",");
for (String tag : tagArray) {
if(tags==null){
tags= new HashSet<String>();
}
tags.add(tag);
}
} }
//Set<String> validTags = JPushInterface.filterValidTags(tags);
JPushInterface.setTags(this.cordova.getActivity() JPushInterface.setTags(this.cordova.getActivity()
.getApplicationContext(), tags,mTagWithAliasCallback); .getApplicationContext(), tags,mTagWithAliasCallback);
callbackContext.success(); callbackContext.success();
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
callbackContext.error("Error reading tags JSON"); callbackContext.error("Error reading tags JSON");

View File

@ -12,13 +12,13 @@ import android.content.Intent;
import android.util.Log; import android.util.Log;
public class MyReceiver extends BroadcastReceiver { public class MyReceiver extends BroadcastReceiver {
private static String TAG = "Client Receiver"; private static String TAG = "JPushPlugin";
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) { if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
}else if (JPushInterface.ACTION_UNREGISTER.equals(intent.getAction())){ // }else if (JPushInterface.ACTION_UNREGISTER.equals(intent.getAction())){
} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) { } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
handlingReceivedMessage(intent); handlingReceivedMessage(intent);
@ -42,13 +42,14 @@ public class MyReceiver extends BroadcastReceiver {
JPushPlugin.transmitPush(msg, extras); JPushPlugin.transmitPush(msg, extras);
} }
private void handlingNotificationOpen(Context context,Intent intent){ private void handlingNotificationOpen(Context context,Intent intent){
Log.i(TAG, "---------------- handlingNotificationOpen");
String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT); String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT);
Map<String,Object> extras = getNotificationExtras(intent); Map<String,Object> extras = getNotificationExtras(intent);
Intent launch = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); Intent launch = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
launch.addCategory(Intent.CATEGORY_LAUNCHER); launch.addCategory(Intent.CATEGORY_LAUNCHER);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP); launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
JPushPlugin.openNotificationAlert = alert; JPushPlugin.openNotificationAlert = alert;
JPushPlugin.openNotificationExtras = extras; JPushPlugin.openNotificationExtras = extras;
@ -57,6 +58,9 @@ public class MyReceiver extends BroadcastReceiver {
context.startActivity(launch); context.startActivity(launch);
} }
private void handlingNotificationReceive(Context context,Intent intent){ private void handlingNotificationReceive(Context context,Intent intent){
Log.i(TAG, "---------------- handlingNotificationReceive");
String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT); String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT);
Map<String,Object> extras = getNotificationExtras(intent); Map<String,Object> extras = getNotificationExtras(intent);

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -9,9 +9,9 @@
#import "AppDelegate+JPush.h" #import "AppDelegate+JPush.h"
#import <objc/runtime.h> #import <objc/runtime.h>
#import "JPushPlugin.h" #import "JPushPlugin.h"
#import "APService.h" #import "JPUSHService.h"
static char launchNotificationKey; //static char launchNotificationKey;
@implementation AppDelegate (JPush) @implementation AppDelegate (JPush)
@ -41,25 +41,44 @@ static char launchNotificationKey;
} }
} }
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[APService registerDeviceToken:deviceToken]; [JPUSHService registerDeviceToken:deviceToken];
} }
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{ -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
[APService handleRemoteNotification:userInfo]; [JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPushPluginReceiveNotification [[NSNotificationCenter defaultCenter] postNotificationName:kJPushPluginReceiveNotification
object:userInfo]; object:userInfo];
} }
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{ -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
[APService handleRemoteNotification:userInfo]; [JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPushPluginReceiveNotification [[NSNotificationCenter defaultCenter] postNotificationName:kJPushPluginReceiveNotification
object:userInfo]; object:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
} }
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
[JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// [application setApplicationIconBadgeNumber:0];
// [application cancelAllLocalNotifications];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
//delegate //delegate
//-(NSDictionary *)luanchOption{ //-(NSDictionary *)luanchOption{
// return objc_getAssociatedObject(self, &launchNotificationKey); // return objc_getAssociatedObject(self, &launchNotificationKey);

View File

@ -22,4 +22,17 @@
-(void)startLogPageView:(CDVInvokedUrlCommand*)command; -(void)startLogPageView:(CDVInvokedUrlCommand*)command;
-(void)stopLogPageView:(CDVInvokedUrlCommand*)command; -(void)stopLogPageView:(CDVInvokedUrlCommand*)command;
// 设置角标到服务器, 服务器下一次发消息时,会设置成这个值
//本接口不会改变应用本地的角标值.
-(void)setBadge:(CDVInvokedUrlCommand*)command;
//相当于 [setBadge:0]
-(void)resetBadge:(CDVInvokedUrlCommand*)command;
//改变应用本地的角标值.
-(void)setApplicationIconBadgeNumber:(CDVInvokedUrlCommand*)command;
//获取应用本地的角标值.
-(void)getApplicationIconBadgeNumber:(CDVInvokedUrlCommand*)command;
@end @end

View File

@ -7,334 +7,453 @@
// //
#import "JPushPlugin.h" #import "JPushPlugin.h"
#import "APService.h" #import "JPUSHService.h"
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
static NSString *const JM_APP_KEY = @"APP_KEY";
static NSString *const JM_APP_CHANNEL = @"CHANNEL";
static NSString *const JM_APP_ISPRODUCTION = @"IsProduction";
static NSString *const JMessageConfigFileName = @"PushConfig";
static NSDictionary *_luanchOptions=nil; static NSDictionary *_luanchOptions=nil;
@implementation JPushPlugin @implementation JPushPlugin
+(void)setLaunchOptions:(NSDictionary *)theLaunchOptions{ +(void)setLaunchOptions:(NSDictionary *)theLaunchOptions{
_luanchOptions=theLaunchOptions; _luanchOptions=theLaunchOptions;
[APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | [JPUSHService setDebugMode];
UIUserNotificationTypeSound | if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
UIUserNotificationTypeAlert) //categories
categories:nil]; [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
[APService setupWithOption:_luanchOptions]; UIUserNotificationTypeSound |
} UIUserNotificationTypeAlert)
categories:nil];
} else {
//categories nil
[JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)
categories:nil];
}
-(void)initial:(CDVInvokedUrlCommand*)command{ //read appkey and channel from JMessageConfig.plist
//do nithng,because Cordova plugin use lazy load mode. NSString *plistPath = [[NSBundle mainBundle] pathForResource:JMessageConfigFileName ofType:@"plist"];
if (plistPath == nil) {
NSLog(@"error: PushConfig.plist not found");
assert(0);
}
NSMutableDictionary *plistData = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSString * appkey = [plistData valueForKey:JM_APP_KEY];
NSString * channel = [plistData valueForKey:JM_APP_CHANNEL];
NSNumber * isProduction = [plistData valueForKey:JM_APP_ISPRODUCTION];
if (!appkey || appkey.length == 0) {
NSLog(@"error: app key not found in JMessageConfig.plist ");
assert(0);
}
[JPUSHService setupWithOption:_luanchOptions appKey:appkey
channel:channel apsForProduction:[isProduction boolValue] ];
} }
- (CDVPlugin*)initWithWebView:(UIWebView*)theWebView{
if (self=[super initWithWebView:theWebView]) {
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self
selector:@selector(networkDidReceiveMessage:)
name:kJPFNetworkDidReceiveMessageNotification
object:nil];
[defaultCenter addObserver:self -(void)stopPush:(CDVInvokedUrlCommand*)command{
selector:@selector(networkDidReceiveNotification:)
name:kJPushPluginReceiveNotification
object:nil];
if (_luanchOptions) { [[UIApplication sharedApplication]unregisterForRemoteNotifications];
NSDictionary *userInfo = [_luanchOptions
valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if ([userInfo count] >0) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error];
NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.openNotification',%@)",jsonString]];
});
}
}
}
}
return self;
} }
-(void)setTagsWithAlias:(CDVInvokedUrlCommand*)command{
NSArray *arguments=command.arguments;
if (!arguments||[arguments count]<2) {
// [self writeJavascript:[NSString stringWithFormat:@"window.plugins.jPushPlugin.pushCallback('%@')",@""]];
return ;
}
NSString *alias=[arguments objectAtIndex:0];
NSArray *arrayTags=[arguments objectAtIndex:1];
NSSet* set=[NSSet setWithArray:arrayTags];
[APService setTags:set
alias:alias
callbackSelector:@selector(tagsWithAliasCallback:tags:alias:)
object:self];
}
-(void)resumePush:(CDVInvokedUrlCommand*)command{ -(void)resumePush:(CDVInvokedUrlCommand*)command{
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1 #if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) { if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//categories //categories
[APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
UIUserNotificationTypeSound | UIUserNotificationTypeSound |
UIUserNotificationTypeAlert) UIUserNotificationTypeAlert)
categories:nil]; categories:nil];
} else { } else {
//categories nil
[APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)
categories:nil];
}
#else
//categories nil //categories nil
[APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound | UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert) UIRemoteNotificationTypeAlert)
categories:nil]; categories:nil];
}
#else
//categories nil
[JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)
categories:nil];
#endif #endif
} }
-(void)isPushStopped:(CDVInvokedUrlCommand*)command{ -(void)isPushStopped:(CDVInvokedUrlCommand*)command{
NSNumber *result; NSNumber *result;
if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications ]) { if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications ]) {
result=@(1); result=@(0);
}else{ }else{
result=@(0); result=@(1);
}
CDVPluginResult * pushResult=[self pluginResultForValue:result];
if (pushResult) {
[self succeedWithPluginResult:pushResult withCallbackID:command.callbackId];
} else {
[self failWithCallbackID:command.callbackId];
}
}
-(void)initial:(CDVInvokedUrlCommand*)command{
//do nithng,because Cordova plugin use lazy load mode.
}
#ifdef __CORDOVA_4_0_0
- (void)pluginInitialize {
NSLog(@"### pluginInitialize ");
[self initNotifications];
}
#else
- (CDVPlugin*)initWithWebView:(UIWebView*)theWebView{
NSLog(@"### initWithWebView ");
if (self=[super initWithWebView:theWebView]) {
[self initNotifications];
}
return self;
}
#endif
-(void)initNotifications {
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self
selector:@selector(networkDidReceiveMessage:)
name:kJPFNetworkDidReceiveMessageNotification
object:nil];
[defaultCenter addObserver:self
selector:@selector(networkDidReceiveNotification:)
name:kJPushPluginReceiveNotification
object:nil];
if (_luanchOptions) {
NSDictionary *userInfo = [_luanchOptions
valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if ([userInfo count] >0) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error];
NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.openNotification',%@)",jsonString]];
});
}
} }
CDVPluginResult * pushResult=[self pluginResultForValue:result];
if (pushResult) { }
[self succeedWithPluginResult:pushResult withCallbackID:command.callbackId]; }
} else {
[self failWithCallbackID:command.callbackId];
}}
-(void)setTagsWithAlias:(CDVInvokedUrlCommand*)command{
NSArray *arguments=command.arguments;
if (!arguments||[arguments count]<2) {
NSLog(@"#### setTagsWithAlias param is less");
return ;
}
NSString *alias=[arguments objectAtIndex:0];
NSArray *arrayTags=[arguments objectAtIndex:1];
NSLog(@"#### setTagsWithAlias alias is %@, tags is %@",alias,arrayTags);
NSSet* set=[NSSet setWithArray:arrayTags];
[JPUSHService setTags:set
alias:alias
callbackSelector:@selector(tagsWithAliasCallback:tags:alias:)
object:self];
}
-(void)setTags:(CDVInvokedUrlCommand *)command{ -(void)setTags:(CDVInvokedUrlCommand *)command{
NSArray *arguments=[command arguments]; NSArray *arguments=[command arguments];
NSString *tags=[arguments objectAtIndex:0]; NSString *tags=[arguments objectAtIndex:0];
NSArray *array=[tags componentsSeparatedByString:@","]; NSLog(@"#### setTags %@",tags);
[APService setTags:[NSSet setWithArray:array]
callbackSelector:@selector(tagsWithAliasCallback:tags:alias:) NSArray *array=[tags componentsSeparatedByString:@","];
object:self]; [JPUSHService setTags:[NSSet setWithArray:array]
callbackSelector:@selector(tagsWithAliasCallback:tags:alias:)
object:self];
} }
-(void)setAlias:(CDVInvokedUrlCommand *)command{ -(void)setAlias:(CDVInvokedUrlCommand *)command{
NSArray *arguments=[command arguments]; NSArray *arguments=[command arguments];
[APService setAlias:[arguments objectAtIndex:0] NSLog(@"#### setAlias %@",arguments);
callbackSelector:@selector(tagsWithAliasCallback:tags:alias:) [JPUSHService setAlias:[arguments objectAtIndex:0]
object:self]; callbackSelector:@selector(tagsWithAliasCallback:tags:alias:)
object:self];
} }
-(void)getRegistrationID:(CDVInvokedUrlCommand*)command{ -(void)getRegistrationID:(CDVInvokedUrlCommand*)command{
NSString* registrationID = [JPUSHService registrationID];
NSLog(@"### getRegistrationID %@",registrationID);
NSString* registrationID = [APService registrationID]; CDVPluginResult *result=[self pluginResultForValue:registrationID];
CDVPluginResult *result=[self pluginResultForValue:registrationID]; if (result) {
if (result) { [self succeedWithPluginResult:result withCallbackID:command.callbackId];
[self succeedWithPluginResult:result withCallbackID:command.callbackId]; } else {
} else { [self failWithCallbackID:command.callbackId];
[self failWithCallbackID:command.callbackId]; }
}
} }
-(void)tagsWithAliasCallback:(int)resultCode tags:(NSSet *)tags alias:(NSString *)alias{ -(void)tagsWithAliasCallback:(int)resultCode tags:(NSSet *)tags alias:(NSString *)alias{
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:resultCode],@"resultCode", [NSNumber numberWithInt:resultCode],@"resultCode",
tags==nil?[NSNull null]:[tags allObjects],@"tags", tags==nil?[NSNull null]:[tags allObjects],@"tags",
alias==nil?[NSNull null]:alias,@"alias",nil]; alias==nil?[NSNull null]:alias,@"alias",nil];
NSMutableDictionary *data = [NSMutableDictionary dictionary]; NSMutableDictionary *data = [NSMutableDictionary dictionary];
[data setObject:[NSNumber numberWithInt:resultCode] forKey:@"resultCode"]; [data setObject:[NSNumber numberWithInt:resultCode] forKey:@"resultCode"];
[data setObject:tags==nil?[NSNull null]:[tags allObjects] forKey:@"tags"]; [data setObject:tags==nil?[NSNull null]:[tags allObjects] forKey:@"tags"];
[data setObject:alias==nil?[NSNull null]:alias forKey:@"alias"]; [data setObject:alias==nil?[NSNull null]:alias forKey:@"alias"];
NSError *error; NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.setTagsWithAlias',%@)",jsonString]]; [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.setTagsWithAlias',%@)",jsonString]];
// [self writeJavascript:[NSString stringWithFormat:@"window.plugins.jPushPlugin.pushCallback('%@')",jsonString]]; // [self writeJavascript:[NSString stringWithFormat:@"window.plugins.jPushPlugin.pushCallback('%@')",jsonString]];
}); });
} }
-(void)startLogPageView:(CDVInvokedUrlCommand*)command{ -(void)startLogPageView:(CDVInvokedUrlCommand*)command{
NSArray *arguments=command.arguments; NSArray *arguments=command.arguments;
if (!arguments||[arguments count]<1) { if (!arguments||[arguments count]<1) {
NSLog(@"startLogPageView argument error"); NSLog(@"startLogPageView argument error");
return ; return ;
} }
NSString * pageName=[arguments objectAtIndex:0]; NSString * pageName=[arguments objectAtIndex:0];
if (pageName) { if (pageName) {
[APService startLogPageView:pageName]; [JPUSHService startLogPageView:pageName];
} }
} }
-(void)stopLogPageView:(CDVInvokedUrlCommand*)command{ -(void)stopLogPageView:(CDVInvokedUrlCommand*)command{
NSArray *arguments=command.arguments; NSArray *arguments=command.arguments;
if (!arguments||[arguments count]<1) { if (!arguments||[arguments count]<1) {
NSLog(@"stopLogPageView argument error"); NSLog(@"stopLogPageView argument error");
return ; return ;
} }
NSString * pageName=[arguments objectAtIndex:0]; NSString * pageName=[arguments objectAtIndex:0];
if (pageName) { if (pageName) {
[APService stopLogPageView:pageName]; [JPUSHService stopLogPageView:pageName];
} }
} }
-(void)beginLogPageView:(CDVInvokedUrlCommand*)command{ -(void)beginLogPageView:(CDVInvokedUrlCommand*)command{
NSArray *arguments=command.arguments; NSArray *arguments=command.arguments;
if (!arguments||[arguments count]<2) { if (!arguments||[arguments count]<2) {
NSLog(@"beginLogPageView argument error"); NSLog(@"beginLogPageView argument error");
return ; return ;
} }
NSString * pageName=[arguments objectAtIndex:0]; NSString * pageName=[arguments objectAtIndex:0];
int duration=[[arguments objectAtIndex:0]intValue]; int duration=[[arguments objectAtIndex:0]intValue];
if (pageName) { if (pageName) {
[APService beginLogPageView:pageName duration:duration]; [JPUSHService beginLogPageView:pageName duration:duration];
} }
} }
-(void)setBadge:(CDVInvokedUrlCommand*)command{ -(void)setBadge:(CDVInvokedUrlCommand*)command{
NSArray *argument=command.arguments; NSArray *argument=command.arguments;
if ([argument count]<1) { if ([argument count]<1) {
NSLog(@"setBadge argument error!"); NSLog(@"setBadge argument error!");
return; return;
} }
NSNumber *badge=[argument objectAtIndex:0]; NSNumber *badge=[argument objectAtIndex:0];
[APService setBadge:[badge intValue]]; [JPUSHService setBadge:[badge intValue]];
} }
-(void)resetBadge:(CDVInvokedUrlCommand*)command{ -(void)resetBadge:(CDVInvokedUrlCommand*)command{
[APService resetBadge]; [JPUSHService resetBadge];
} }
-(void)setApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command{
//
NSArray *argument=command.arguments;
if ([argument count]<1) {
NSLog(@"setBadge argument error!");
return;
}
NSNumber *badge=[argument objectAtIndex:0];
[UIApplication sharedApplication].applicationIconBadgeNumber=[badge intValue];
}
-(void)getApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command {
NSInteger num = [UIApplication sharedApplication].applicationIconBadgeNumber;
CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:num];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
-(void)setDebugModeFromIos:(CDVInvokedUrlCommand*)command{ -(void)setDebugModeFromIos:(CDVInvokedUrlCommand*)command{
[APService setDebugMode]; [JPUSHService setDebugMode];
} }
-(void)setLogOFF:(CDVInvokedUrlCommand*)command{ -(void)setLogOFF:(CDVInvokedUrlCommand*)command{
[APService setLogOFF]; [JPUSHService setLogOFF];
} }
-(void)stopPush:(CDVInvokedUrlCommand*)command{
[[UIApplication sharedApplication]unregisterForRemoteNotifications];
}
- (void)failWithCallbackID:(NSString *)callbackID { - (void)failWithCallbackID:(NSString *)callbackID {
CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
[self.commandDelegate sendPluginResult:result callbackId:callbackID]; [self.commandDelegate sendPluginResult:result callbackId:callbackID];
} }
- (void)succeedWithPluginResult:(CDVPluginResult *)result withCallbackID:(NSString *)callbackID { - (void)succeedWithPluginResult:(CDVPluginResult *)result withCallbackID:(NSString *)callbackID {
[self.commandDelegate sendPluginResult:result callbackId:callbackID]; [self.commandDelegate sendPluginResult:result callbackId:callbackID];
}
-(void)setApplicationIconBadgeNumber:(CDVInvokedUrlCommand*)command{
//
NSArray *argument=command.arguments;
if ([argument count]<1) {
NSLog(@"setBadge argument error!");
return;
}
NSNumber *badge=[argument objectAtIndex:0];
[UIApplication sharedApplication].applicationIconBadgeNumber=[badge intValue];
} }
- (CDVPluginResult *)pluginResultForValue:(id)value { - (CDVPluginResult *)pluginResultForValue:(id)value {
CDVPluginResult *result; CDVPluginResult *result;
if ([value isKindOfClass:[NSString class]]) { if ([value isKindOfClass:[NSString class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsString:[value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; messageAsString:[value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
} else if ([value isKindOfClass:[NSNumber class]]) { } else if ([value isKindOfClass:[NSNumber class]]) {
CFNumberType numberType = CFNumberGetType((CFNumberRef)value); CFNumberType numberType = CFNumberGetType((CFNumberRef)value);
//note: underlyingly, BOOL values are typedefed as char //note: underlyingly, BOOL values are typedefed as char
if (numberType == kCFNumberIntType || numberType == kCFNumberCharType) { if (numberType == kCFNumberIntType || numberType == kCFNumberCharType) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:[value intValue]]; result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:[value intValue]];
} else { } else {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:[value doubleValue]]; result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:[value doubleValue]];
}
} else if ([value isKindOfClass:[NSArray class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:value];
} else if ([value isKindOfClass:[NSDictionary class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:value];
} else if ([value isKindOfClass:[NSNull class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
} else {
NSLog(@"Cordova callback block returned unrecognized type: %@", NSStringFromClass([value class]));
return nil;
} }
return result; } else if ([value isKindOfClass:[NSArray class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:value];
} else if ([value isKindOfClass:[NSDictionary class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:value];
} else if ([value isKindOfClass:[NSNull class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
} else {
NSLog(@"Cordova callback block returned unrecognized type: %@", NSStringFromClass([value class]));
return nil;
}
return result;
} }
- (void)networkDidReceiveMessage:(NSNotification *)notification { - (void)networkDidReceiveMessage:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo]; NSDictionary *userInfo = [notification userInfo];
//NSLog(@"%@",userInfo); //NSLog(@"%@",userInfo);
NSError *error; NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error];
NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
//NSLog(@"%@",jsonString); //NSLog(@"%@",jsonString);
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.receiveMessage',%@)",jsonString]]; [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.receiveMessage',%@)",jsonString]];
[self.commandDelegate evalJs:[NSString stringWithFormat:@"window.plugins.jPushPlugin.receiveMessageIniOSCallback('%@')",jsonString]]; [self.commandDelegate evalJs:[NSString stringWithFormat:@"window.plugins.jPushPlugin.receiveMessageIniOSCallback('%@')",jsonString]];
}); });
} }
-(void)networkDidReceiveNotification:(id)notification{ -(void)networkDidReceiveNotification:(id)notification{
NSError *error; NSError *error;
NSDictionary *userInfo = [notification object]; NSDictionary *userInfo = [notification object];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error];
NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
switch ([UIApplication sharedApplication].applicationState) { switch ([UIApplication sharedApplication].applicationState) {
case UIApplicationStateActive: case UIApplicationStateActive:
{ {
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.receiveNotification',%@)",jsonString]]; [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.receiveNotification',%@)",jsonString]];
}); });
}
break;
case UIApplicationStateInactive:
case UIApplicationStateBackground:
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.openNotification',%@)",jsonString]];
});
}
break;
default:
//do nothing
break;
} }
break;
case UIApplicationStateInactive:
case UIApplicationStateBackground:
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.openNotification',%@)",jsonString]];
});
}
break;
default:
//do nothing
break;
}
} }

View File

@ -3,8 +3,10 @@
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>APP_KEY</key> <key>APP_KEY</key>
<string>7d431e42dfa6a6d693ac2d04</string> <string></string>
<key>CHANNEL</key> <key>CHANNEL</key>
<string>Subscription</string> <string>Subscription</string>
<key>IsProduction</key>
<false/>
</dict> </dict>
</plist> </plist>

View File

@ -1,175 +0,0 @@
//
// APService.h
// APService
//
// Created by JPush on 12-8-15.
// Copyright (c) 2012年 HXHG. All rights reserved.
// Version: 1.8.3
@class CLRegion;
@class UILocalNotification;
extern NSString *const kJPFNetworkDidSetupNotification; // 建立连接
extern NSString *const kJPFNetworkDidCloseNotification; // 关闭连接
extern NSString *const kJPFNetworkDidRegisterNotification; // 注册成功
extern NSString *const kJPFNetworkDidLoginNotification; // 登录成功
extern NSString *const
kJPFNetworkDidReceiveMessageNotification; // 收到消息(非APNS)
extern NSString *const kJPFServiceErrorNotification; // 错误提示
@class CLLocation;
@interface APService : NSObject
#pragma - mark 基本功能
// 以下四个接口是必须调用的
+ (void)setupWithOption:(NSDictionary *)launchingOption; // 初始化
+ (void)registerForRemoteNotificationTypes:(NSUInteger)types
categories:(NSSet *)categories; // 注册APNS类型
+ (void)registerDeviceToken:(NSData *)deviceToken; // 向服务器上报Device Token
+ (void)handleRemoteNotification:(NSDictionary *)
remoteInfo; // 处理收到的APNS消息向服务器上报收到APNS消息
// 下面的接口是可选的
// 设置标签和(或)别名若参数为nil则忽略若是空对象则清空详情请参考文档http://docs.jpush.cn/pages/viewpage.action?pageId=3309913
+ (void)setTags:(NSSet *)tags
alias:(NSString *)alias
callbackSelector:(SEL)cbSelector
target:(id)theTarget;
+ (void)setTags:(NSSet *)tags
alias:(NSString *)alias
callbackSelector:(SEL)cbSelector
object:(id)theTarget;
+ (void)setTags:(NSSet *)tags
callbackSelector:(SEL)cbSelector
object:(id)theTarget;
+ (void)setAlias:(NSString *)alias
callbackSelector:(SEL)cbSelector
object:(id)theTarget;
// 用于过滤出正确可用的tags如果总数量超出最大限制则返回最大数量的靠前的可用tags
+ (NSSet *)filterValidTags:(NSSet *)tags;
#pragma - mark 上报日志
/**
*
* startLogPageView和stopLogPageView为自动计算停留时间
* beginLogPageView为手动自己输入停留时间
*
* @param pageName
* @param seconds
*/
+ (void)startLogPageView:(NSString *)pageName;
+ (void)stopLogPageView:(NSString *)pageName;
+ (void)beginLogPageView:(NSString *)pageName duration:(int)seconds;
/**
* Crash日志收集, .
*/
+ (void)crashLogON;
/**
*
*
* CoreLocation.framework #import <CoreLocation/CoreLocation.h>
* @param latitude .
* @param longitude .
* @param location CLLocation *
*/
+ (void)setLatitude:(double)latitude longitude:(double)longitude;
+ (void)setLocation:(CLLocation *)location;
#pragma - mark 本地通知
/**
* 64
* @param fireDate
* @param alertBody
* @param badge -1
* @param alertAction IOS 8"打开","启动"
* @param notificationKey
* @param userInfo
* @param soundName nil为默认声音
* IOS8新参数
* @param region
* @param regionTriggersOnce
* @param category
*/
+ (UILocalNotification *)setLocalNotification:(NSDate *)fireDate
alertBody:(NSString *)alertBody
badge:(int)badge
alertAction:(NSString *)alertAction
identifierKey:(NSString *)notificationKey
userInfo:(NSDictionary *)userInfo
soundName:(NSString *)soundName;
+ (UILocalNotification *)setLocalNotification:(NSDate *)fireDate
alertBody:(NSString *)alertBody
badge:(int)badge
alertAction:(NSString *)alertAction
identifierKey:(NSString *)notificationKey
userInfo:(NSDictionary *)userInfo
soundName:(NSString *)soundName
region:(CLRegion *)region
regionTriggersOnce:(BOOL)regionTriggersOnce
category:(NSString *)category
NS_AVAILABLE_IOS(8_0);
/**
* App在前台运行时不会进行弹窗
* @param notification
* @param notificationKey
*/
+ (void)showLocalNotificationAtFront:(UILocalNotification *)notification
identifierKey:(NSString *)notificationKey;
/**
*
* @param notificationKey
* @param myUILocalNotification
*/
+ (void)deleteLocalNotificationWithIdentifierKey:(NSString *)notificationKey;
+ (void)deleteLocalNotification:(UILocalNotification *)localNotification;
/**
*
* @param notificationKey
* @return ,[array count]0
*/
+ (NSArray *)findLocalNotificationWithIdentifier:(NSString *)notificationKey;
/**
*
*/
+ (void)clearAllLocalNotifications;
#pragma - mark 设置Badge
/**
* set setBadge
* @param value JPush服务器的badge的值
* UIApplication:setApplicationIconBadgeNumber函数,
*/
+ (BOOL)setBadge:(NSInteger)value;
/**
* set setBadge
* @param value JPush服务器对badge值的设定.
* UIApplication:setApplicationIconBadgeNumber函数,
*/
+ (void)resetBadge;
/**
* get RegistrationID
*/
+ (NSString *)registrationID;
#pragma - mark 打印日志信息配置
/**
* setDebugMode获取更多的Log信息
* DebugMode
*
* setLogOFF关闭除了错误信息外的所有Log
* LogOFF用于节省性能开销
*
* DebugLog,
*/
+ (void)setDebugMode;
+ (void)setLogOFF;
@end

337
src/ios/lib/JPUSHService.h Executable file
View File

@ -0,0 +1,337 @@
/*
* | | | | \ \ / / | | | | / _______|
* | |____| | \ \/ / | |____| | / /
* | |____| | \ / | |____| | | | _____
* | | | | / \ | | | | | | |____ |
* | | | | / /\ \ | | | | \ \______| |
* | | | | /_/ \_\ | | | | \_________|
*
* Copyright (c) 2011 ~ 2015 Shenzhen HXHG. All rights reserved.
*/
#define JPUSH_VERSION_NUMBER 2.1.0
#import <Foundation/Foundation.h>
@class CLRegion;
@class UILocalNotification;
extern NSString *const kJPFNetworkIsConnectingNotification; // 正在连接中
extern NSString *const kJPFNetworkDidSetupNotification; // 建立连接
extern NSString *const kJPFNetworkDidCloseNotification; // 关闭连接
extern NSString *const kJPFNetworkDidRegisterNotification; // 注册成功
extern NSString *const kJPFNetworkDidLoginNotification; // 登录成功
extern NSString *const kJPFNetworkDidReceiveMessageNotification; // 收到消息(非APNS)
extern NSString *const kJPFServiceErrorNotification; // 错误提示
@class CLLocation;
/*!
* JPush
*/
@interface JPUSHService : NSObject
///----------------------------------------------------
/// @name Setup 启动相关
///----------------------------------------------------
/*!
* @abstract SDK
*
* @discussion , PushConfig.plist . 使, .
*/
+ (void)setupWithOption:(NSDictionary *)launchingOption __attribute__((deprecated("JPush 2.1.0 版本已过期")));
/*!
* @abstract SDK
*
* @param launchingOption .
* @param appKey JPush ,. JPush .
* @param channel . .
* @param isProduction . , NO; , YES.
*
* @discussion SDK启动必须的参数, SDK.
* App , JPush SDK .
*/
+ (void)setupWithOption:(NSDictionary *)launchingOption
appKey:(NSString *)appKey
channel:(NSString *)channel
apsForProduction:(BOOL)isProduction;
///----------------------------------------------------
/// @name APNs about 通知相关
///----------------------------------------------------
/*!
* @abstract
*
* @param types
* @param categories
*
* @discussion
*/
+ (void)registerForRemoteNotificationTypes:(NSUInteger)types
categories:(NSSet *)categories;
+ (void)registerDeviceToken:(NSData *)deviceToken;
/*!
* @abstract APNs
*/
+ (void)handleRemoteNotification:(NSDictionary *)remoteInfo;
///----------------------------------------------------
/// @name Tag alias setting 设置别名与标签
///----------------------------------------------------
/*!
*
* ()nilhttp://docs.jpush.io/client/ios_api/#api-ios
* setTags:alias:fetchCompletionHandle:block里面处理设置结果即可.
* WARN: 使block时需要注意循环引用问题
*/
+ (void) setTags:(NSSet *)tags
alias:(NSString *)alias
callbackSelector:(SEL)cbSelector
target:(id)theTarget;
+ (void) setTags:(NSSet *)tags
alias:(NSString *)alias
callbackSelector:(SEL)cbSelector
object:(id)theTarget;
+ (void) setTags:(NSSet *)tags
callbackSelector:(SEL)cbSelector
object:(id)theTarget;
+ (void) setTags:(NSSet *)tags
alias:(NSString *)alias
fetchCompletionHandle:(void (^)(int iResCode, NSSet *iTags, NSString *iAlias))completionHandler;
+ (void) setTags:(NSSet *)tags
aliasInbackground:(NSString *)alias;
+ (void)setAlias:(NSString *)alias
callbackSelector:(SEL)cbSelector
object:(id)theTarget;
/*!
* @abstract tags
*
* @discussion tags , tags.
* tags . SDK .
*/
+ (NSSet *)filterValidTags:(NSSet *)tags;
///----------------------------------------------------
/// @name Stats 统计功能
///----------------------------------------------------
/*!
* @abstract
*
* @param pageName
*/
+ (void)startLogPageView:(NSString *)pageName;
/*!
* @abstract
*
* @param pageName
*/
+ (void)stopLogPageView:(NSString *)pageName;
/*!
* @abstract
*
* @param pageName
* @param seconds
*/
+ (void)beginLogPageView:(NSString *)pageName duration:(int)seconds;
/*!
* @abstract Crash日志收集
*
* @discussion .
*/
+ (void)crashLogON;
/*!
* @abstract
*
* @param latitude .
* @param longitude .
*
*/
+ (void)setLatitude:(double)latitude longitude:(double)longitude;
/*!
* @abstract
*
* @param location CLLocation *
*
* @discussion CoreLocation.framework #import <CoreLocation/CoreLocation.h>
*/
+ (void)setLocation:(CLLocation *)location;
///----------------------------------------------------
/// @name Local Notification 本地通知
///----------------------------------------------------
/*!
* @abstract 64
*
* @param fireDate
* @param alertBody
* @param badge -1
* @param alertAction IOS 8"打开", "启动"
* @param notificationKey
* @param userInfo
* @param soundName nil为默认声音
*
* @discussion 64
*/
+ (UILocalNotification *)setLocalNotification:(NSDate *)fireDate
alertBody:(NSString *)alertBody
badge:(int)badge
alertAction:(NSString *)alertAction
identifierKey:(NSString *)notificationKey
userInfo:(NSDictionary *)userInfo
soundName:(NSString *)soundName;
/*!
* @abstract ( iOS8 )
*
* IOS8新参数
* @param region
* @param regionTriggersOnce
* @param category
*/
+ (UILocalNotification *)setLocalNotification:(NSDate *)fireDate
alertBody:(NSString *)alertBody
badge:(int)badge
alertAction:(NSString *)alertAction
identifierKey:(NSString *)notificationKey
userInfo:(NSDictionary *)userInfo
soundName:(NSString *)soundName
region:(CLRegion *)region
regionTriggersOnce:(BOOL)regionTriggersOnce
category:(NSString *)category NS_AVAILABLE_IOS(8_0);
/*!
* @abstract
*
* @param notification
* @param notificationKey
*
* @discussion App在前台运行时不会进行弹窗
*/
+ (void)showLocalNotificationAtFront:(UILocalNotification *)notification
identifierKey:(NSString *)notificationKey;
/*!
* @abstract
*
* @param notificationKey
* @param myUILocalNotification
*/
+ (void)deleteLocalNotificationWithIdentifierKey:(NSString *)notificationKey;
/*!
* @abstract
*/
+ (void)deleteLocalNotification:(UILocalNotification *)localNotification;
/*!
* @abstract
*
* @param notificationKey
* @return , [array count]0
*/
+ (NSArray *)findLocalNotificationWithIdentifier:(NSString *)notificationKey;
/*!
* @abstract
*/
+ (void)clearAllLocalNotifications;
///----------------------------------------------------
/// @name Server badge 服务器端 badge 功能
///----------------------------------------------------
/*!
* @abstract ()
*
* @param value . ()
*
* @discussion .
* UIApplication:setApplicationIconBadgeNumber .
*
* JPush .
* , APNs , , .
*
* JPush :
*
* - API () badge ;
* - API APNs (),
* 使 "+1" , badge () +1 badge ;
*/
+ (BOOL)setBadge:(NSInteger)value;
/*!
* @abstract (0)
*
* @discussion [setBadge:0] .
* [JPUSHService setBadge:] .
*/
+ (void)resetBadge;
///----------------------------------------------------
/// @name Logs and others 日志与其他
///----------------------------------------------------
/*!
* @abstract JPush标识此设备的 registrationID
*
* @discussion SDK注册成功后, registrationID .
*
* JPush registrationID .
* , registrationID , , .
*
* JPush .
*/
+ (NSString *)registrationID;
/*!
* @abstract Debug
*
* @discussion JMessage iOS Android .
* : Verbose, Debug, Info, Warning, Error.
* , Android .
*
* SDK : Info. , .
*
* : Debug, .
*/
+ (void)setDebugMode;
/*!
* @abstract
*
* @discussion , [JPUSHService setDebugMode]
*
* , Warning, Error . , , .
*
* , , .
*/
+ (void)setLogOFF;
@end

Binary file not shown.

Binary file not shown.

View File

@ -1,4 +1,5 @@
var JPushPlugin = function(){ var JPushPlugin = function(){
}; };
@ -46,6 +47,11 @@ JPushPlugin.prototype.setApplicationIconBadgeNumber = function(badge){
this.call_native( "setApplicationIconBadgeNumber",[badge],null); this.call_native( "setApplicationIconBadgeNumber",[badge],null);
} }
} }
JPushPlugin.prototype.getApplicationIconBadgeNumber = function(callback){
if(this.isPlatformIOS()){
this.call_native( "getApplicationIconBadgeNumber",[],callback);
}
}
JPushPlugin.prototype.setTagsWithAlias = function(tags,alias){ JPushPlugin.prototype.setTagsWithAlias = function(tags,alias){
try{ try{
@ -253,6 +259,13 @@ JPushPlugin.prototype.clearAllNotification = function(){
} }
} }
JPushPlugin.prototype.clearNotificationById = function(notificationId){
if(device.platform == "Android") {
data=[]
this.call_native("clearNotificationById",[notificationId],null);
}
}
JPushPlugin.prototype.setLatestNotificationNum = function(num){ JPushPlugin.prototype.setLatestNotificationNum = function(num){
if(device.platform == "Android") { if(device.platform == "Android") {
this.call_native("setLatestNotificationNum",[num],null); this.call_native("setLatestNotificationNum",[num],null);
@ -321,3 +334,5 @@ if(!window.plugins.jPushPlugin){
module.exports = new JPushPlugin(); module.exports = new JPushPlugin();