diff --git a/.gitignore b/.gitignore index 62f5fc4..677e608 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,5 @@ yarn-error.log .flowconfig .gitattributes .watchmanconfig +android/build/ +android/react-native-aliyun-push.iml diff --git a/Resources/Model.xcdatamodeld/Model.xcdatamodel/contents b/Resources/Model.xcdatamodeld/Model.xcdatamodel/contents new file mode 100644 index 0000000..94cedd9 --- /dev/null +++ b/Resources/Model.xcdatamodeld/Model.xcdatamodel/contents @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/android/build.gradle b/android/build.gradle old mode 100644 new mode 100755 diff --git a/android/libs/alicloud-android-third-push-3.0.5.aar b/android/libs/alicloud-android-third-push-3.0.5.aar old mode 100644 new mode 100755 diff --git a/android/proguard-rules.pro b/android/proguard-rules.pro old mode 100644 new mode 100755 diff --git a/android/project.properties b/android/project.properties old mode 100644 new mode 100755 diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml old mode 100644 new mode 100755 diff --git a/android/src/main/java/org/wonday/aliyun/push/AliyunPushMessageReceiver.java b/android/src/main/java/org/wonday/aliyun/push/AliyunPushMessageReceiver.java index 2aa640c..f17dc2f 100644 --- a/android/src/main/java/org/wonday/aliyun/push/AliyunPushMessageReceiver.java +++ b/android/src/main/java/org/wonday/aliyun/push/AliyunPushMessageReceiver.java @@ -1,7 +1,7 @@ /** * Copyright (c) 2017-present, Wonday (@wonday.org) * All rights reserved. - * + *

* This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ @@ -10,38 +10,23 @@ import android.content.Context; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import javax.annotation.Nullable; - -import com.facebook.react.ReactPackage; -import com.facebook.react.bridge.JavaScriptModule; -import com.facebook.react.bridge.NativeModule; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.LifecycleEventListener; +import com.alibaba.sdk.android.push.MessageReceiver; +import com.alibaba.sdk.android.push.notification.CPushMessage; +import com.facebook.common.logging.FLog; +import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContextBaseJavaModule; -import com.facebook.react.bridge.ReactContext; -import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableMap; -import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.Promise; -import com.facebook.react.modules.core.DeviceEventManagerModule; -import com.facebook.common.logging.FLog; import com.facebook.react.common.ReactConstants; +import com.facebook.react.modules.core.DeviceEventManagerModule; -import com.alibaba.sdk.android.push.CloudPushService; -import com.alibaba.sdk.android.push.MessageReceiver; -import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory; -import com.alibaba.sdk.android.push.notification.CPushMessage; +import java.util.Map; + +import javax.annotation.Nullable; public class AliyunPushMessageReceiver extends MessageReceiver { public static ReactApplicationContext context; public static AliyunPushMessageReceiver instance; +// public static List> array = new ArrayList(); private final String ALIYUN_PUSH_TYPE_MESSAGE = "message"; private final String ALIYUN_PUSH_TYPE_NOTIFICATION = "notification"; @@ -52,16 +37,33 @@ public AliyunPushMessageReceiver() { } @Override - protected void onMessage(Context context, CPushMessage cPushMessage) { + protected void onMessage(final Context context, final CPushMessage cPushMessage) { super.onMessage(context, cPushMessage); + new Thread(new Runnable() { + @Override + public void run() { + try { + SQLiteHelper.getInstance(context.getApplicationContext()).insertMsg(cPushMessage.getContent()); + } catch (Exception e) { + e.printStackTrace(); + } + } + }).start(); + WritableMap params = Arguments.createMap(); params.putString("messageId", cPushMessage.getMessageId()); - params.putString("body", cPushMessage.getContent()); + params.putMap("body", AliyunPushUtils.createBody(cPushMessage.getContent())); params.putString("title", cPushMessage.getTitle()); params.putString("type", ALIYUN_PUSH_TYPE_MESSAGE); +// Map params2 = new HashMap<>(); +// params2.put("messageId", cPushMessage.getMessageId()); +// params2.put("body", AliyunPushUtils.createBody(cPushMessage.getContent())); +// params2.put("title", cPushMessage.getTitle()); +// params2.put("type", ALIYUN_PUSH_TYPE_MESSAGE); +// array.add(params2); sendEvent("aliyunPushReceived", params); } @@ -77,12 +79,24 @@ protected void onNotification(Context context, String title, String content, Map WritableMap extraWritableMap = Arguments.createMap(); for (Map.Entry entry : extraMap.entrySet()) { - extraWritableMap.putString(entry.getKey(),entry.getValue()); + extraWritableMap.putString(entry.getKey(), entry.getValue()); } params.putMap("extras", extraWritableMap); params.putString("type", ALIYUN_PUSH_TYPE_NOTIFICATION); +// Map params2 = new HashMap<>(); +// params2.put("body", content); +// params2.put("title", title); +// +// Map extraWritableMap2 = new HashMap<>(); +// for (Map.Entry entry : extraMap.entrySet()) { +// extraWritableMap2.put(entry.getKey(), entry.getValue()); +// } +// params2.put("extras", extraWritableMap2); +// +// params2.put("type", ALIYUN_PUSH_TYPE_NOTIFICATION); +// array.add(params2); sendEvent("aliyunPushReceived", params); } @@ -121,8 +135,8 @@ protected void onNotificationClickedWithNoAction(Context context, String title, } @Override - protected void onNotificationRemoved(Context context, String messageId){ - FLog.d(ReactConstants.TAG, "onNotificationRemoved: messageId=" + messageId); + protected void onNotificationRemoved(Context context, String messageId) { + FLog.d(ReactConstants.TAG, "onNotificationRemoved: messageId=" + messageId); super.onNotificationRemoved(context, messageId); @@ -150,7 +164,7 @@ public void onNotificationReceivedInApp(Context context, String title, String co WritableMap extraWritableMap = Arguments.createMap(); for (Map.Entry entry : extraMap.entrySet()) { - extraWritableMap.putString(entry.getKey(),entry.getValue()); + extraWritableMap.putString(entry.getKey(), entry.getValue()); } params.putMap("extras", extraWritableMap); @@ -162,9 +176,9 @@ public void onNotificationReceivedInApp(Context context, String title, String co private void sendEvent(String eventName, @Nullable WritableMap params) { if (context == null) { FLog.d(ReactConstants.TAG, "reactContext==null"); - }else{ + } else { context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit(eventName, params); + .emit(eventName, params); } } } \ No newline at end of file diff --git a/android/src/main/java/org/wonday/aliyun/push/AliyunPushModule.java b/android/src/main/java/org/wonday/aliyun/push/AliyunPushModule.java index d0a0426..cde4cdc 100644 --- a/android/src/main/java/org/wonday/aliyun/push/AliyunPushModule.java +++ b/android/src/main/java/org/wonday/aliyun/push/AliyunPushModule.java @@ -1,47 +1,28 @@ /** * Copyright (c) 2017-present, Wonday (@wonday.org) * All rights reserved. - * + *

* This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ package org.wonday.aliyun.push; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -import android.content.BroadcastReceiver; -import android.app.Activity; -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.Context; -import android.os.Handler; - -import com.facebook.react.bridge.NativeModule; +import com.alibaba.sdk.android.push.CommonCallback; +import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory; +import com.facebook.common.logging.FLog; +import com.facebook.react.bridge.Callback; +import com.facebook.react.bridge.LifecycleEventListener; +import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.LifecycleEventListener; -import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.Promise; +import com.facebook.react.bridge.WritableArray; import com.facebook.react.common.ReactConstants; -import com.facebook.common.logging.FLog; -import com.alibaba.sdk.android.push.CloudPushService; -import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory; -import com.alibaba.sdk.android.push.CommonCallback; import me.leolin.shortcutbadger.ShortcutBadger; -import org.wonday.aliyun.push.MIUIUtils; - public class AliyunPushModule extends ReactContextBaseJavaModule implements LifecycleEventListener { private final ReactApplicationContext context; private int badgeNumber; @@ -51,6 +32,7 @@ public AliyunPushModule(ReactApplicationContext reactContext) { super(reactContext); this.context = reactContext; this.badgeNumber = 0; + SQLiteHelper.getInstance(context.getApplicationContext()); AliyunPushMessageReceiver.context = reactContext; ThirdPartMessageActivity.context = reactContext; @@ -67,15 +49,15 @@ public String getName() { @ReactMethod public void getDeviceId(final Promise promise) { String deviceID = PushServiceFactory.getCloudPushService().getDeviceId(); - if (deviceID!=null && deviceID.length()>0) { + if (deviceID != null && deviceID.length() > 0) { promise.resolve(deviceID); } else { // 或许还没有初始化完成,等3秒钟再次尝试 - try{ + try { Thread.sleep(3000); deviceID = PushServiceFactory.getCloudPushService().getDeviceId(); - if (deviceID!=null && deviceID.length()>0) { + if (deviceID != null && deviceID.length() > 0) { promise.resolve(deviceID); return; } @@ -93,7 +75,7 @@ public void setApplicationIconBadgeNumber(int badgeNumber, final Promise promise if (MIUIUtils.isMIUI()) { //小米特殊处理 FLog.d(ReactConstants.TAG, "setApplicationIconBadgeNumber for xiaomi"); - if (badgeNumber==0) { + if (badgeNumber == 0) { promise.resolve(""); return; } @@ -118,7 +100,7 @@ public void setApplicationIconBadgeNumber(int badgeNumber, final Promise promise ShortcutBadger.applyCount(this.context, badgeNumber); this.badgeNumber = badgeNumber; promise.resolve(""); - } catch (Exception e){ + } catch (Exception e) { promise.reject(e.getMessage()); } } @@ -137,6 +119,7 @@ public void bindAccount(String account, final Promise promise) { public void onSuccess(String response) { promise.resolve(response); } + @Override public void onFailed(String code, String message) { promise.reject(code, message); @@ -151,6 +134,7 @@ public void unbindAccount(final Promise promise) { public void onSuccess(String response) { promise.resolve(response); } + @Override public void onFailed(String code, String message) { promise.reject(code, message); @@ -162,13 +146,14 @@ public void onFailed(String code, String message) { public void bindTag(int target, ReadableArray tags, String alias, final Promise promise) { String[] tagStrs = new String[tags.size()]; - for(int i=0; i it = msg.keys(); it.hasNext(); ) { + String key = it.next(); + map.putString(key, msg.optString(key)); + } + map.putDouble("timestramp", Long.valueOf(file.getName())); + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (JSONException e) { + e.printStackTrace(); + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return map; + } + + public static List createListMsg(File dir) { + List data = new ArrayList<>(); + if (dir.exists() && dir.listFiles() != null) { + File[] files = dir.listFiles(); + for (File f : files) { + if (f.isFile()) { + data.add(createMsg(f)); + } else if (f.isDirectory()) { + data.addAll(createListMsg(f)); + } + } + } + return data; + } + + public static File getAliyunPushDir(Context context) { + return new File(context.getFilesDir(), context.getPackageName());/*context.getFilesDir() Environment.getExternalStorageDirectory()*/ + } + + public static void saveAliyunPushMessage(Context context, String eventName, String type, CPushMessage cPushMessage) { + String messageId = cPushMessage.getMessageId(); + String body = cPushMessage.getContent(); + String title = cPushMessage.getTitle(); + String appId = cPushMessage.getAppId(); + String traceInfo = cPushMessage.getTraceInfo(); + JSONObject object = new JSONObject(); + FileOutputStream outputStream = null; + try { + JSONObject bodyJson = new JSONObject(body); + JSONObject data = bodyJson.optJSONObject("data"); + String account = null; + if (data != null) { + account = data.optString("account"); + } + object.put("messageId", messageId); + object.put("body", body); + object.put("title", title); + object.put("appId", appId); + object.put("traceInfo", traceInfo); + File dir = new File(getAliyunPushDir(context), TextUtils.isEmpty(account) ? publicmsg : privatemsg + "/" + account); + if (!dir.exists()) { + dir.mkdirs(); + } + Log.v("saveAliyunPushMessage", dir.getAbsolutePath()); + String fn = "" + System.currentTimeMillis(); + outputStream = new FileOutputStream(new File(dir, fn)); + outputStream.write(object.toString().getBytes()); + outputStream.flush(); + } catch (JSONException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + public static WritableMap createBody(String content){ + try { + JSONObject object = new JSONObject(content); + String msgtype = object.optString(SQLiteHelper.key_msgtype); + String msgId = object.optString(SQLiteHelper.key_msgId); + String timeString = object.optString(SQLiteHelper.key_timeString); + + JSONObject data = object.optJSONObject("data"); + Log.v(AliyunPushUtils.class.getName(), data.toString()); + String account = data.optString(SQLiteHelper.key_data_account); + String title = data.optString(SQLiteHelper.key_data_title); + String date = data.optString(SQLiteHelper.key_data_date); + String time = data.optString(SQLiteHelper.key_data_time); + WritableMap obj = createHeader(msgId, msgtype, timeString); + + + if ("url".equals(msgtype)) { + String describe = data.optString(SQLiteHelper.key_data_describe); + String image = data.optString(SQLiteHelper.key_data_image); + String linkUrl = data.optString(SQLiteHelper.key_data_linkUrl); + obj.putMap("data", createMapUrl(title, date, time, account, + describe, image, linkUrl)); + } else if ("text".equals(msgtype)) { + String body = data.optString(SQLiteHelper.key_data_body); + obj.putMap("data", createMapText(title, date, time, account, + body)); + } else if ("account_notice".equals(msgtype)) { + String amount = data.optString(SQLiteHelper.key_data_amount); + String body = data.optString(SQLiteHelper.key_data_body); + String describe = data.optString(SQLiteHelper.key_data_describe); + String redirectType = data.optString(SQLiteHelper.key_data_redirectType); + String redirectData = data.optString(SQLiteHelper.key_data_redirectData); + obj.putMap("data", createMapAccountNotice(title, date, time, account, + amount, body, describe, redirectType, redirectData)); + } + return obj; + } catch (Exception e) { + e.printStackTrace(); + } + return Arguments.createMap(); + } + public static WritableMap createMapData(String title, String date, String time, String account) { + WritableMap data = Arguments.createMap(); + data.putString(SQLiteHelper.key_data_title, title); + data.putString(SQLiteHelper.key_data_date, date); + data.putString(SQLiteHelper.key_data_time, time); + data.putString(SQLiteHelper.key_data_account, account); + return data; + } + + public static WritableMap createMapUrl(String title, String date, String time, String account, + String describe, String image, String linkUrl) { + WritableMap url = createMapData(title, date, time, account); + + url.putString(SQLiteHelper.key_data_describe, describe); + url.putString(SQLiteHelper.key_data_image, image); + url.putString(SQLiteHelper.key_data_linkUrl, linkUrl); + return url; + } + + public static WritableMap createMapText(String title, String date, String time, String account, + String body) { + WritableMap text = createMapData(title, date, time, account); + + text.putString(SQLiteHelper.key_data_body, body); + return text; + } + + public static WritableMap createMapAccountNotice(String title, String date, String time, String account, + String amount, String body, String describe, String redirectType, String redirectData) { + WritableMap text = createMapData(title, date, time, account); + + text.putString(SQLiteHelper.key_data_amount, amount); + text.putString(SQLiteHelper.key_data_body, body); + text.putString(SQLiteHelper.key_data_describe, describe); + text.putString(SQLiteHelper.key_data_redirectType, redirectType); + text.putString(SQLiteHelper.key_data_redirectData, redirectData); + return text; + } + + public static WritableMap createHeader(String msgId, String msgtype, String timeString) { + + WritableMap map = Arguments.createMap(); + map.putString(SQLiteHelper.key_msgId, msgId); + map.putString(SQLiteHelper.key_msgtype, msgtype); + map.putString(SQLiteHelper.key_timeString, timeString); + return map; + } +} diff --git a/android/src/main/java/org/wonday/aliyun/push/SQLiteHelper.java b/android/src/main/java/org/wonday/aliyun/push/SQLiteHelper.java new file mode 100644 index 0000000..3e5ce00 --- /dev/null +++ b/android/src/main/java/org/wonday/aliyun/push/SQLiteHelper.java @@ -0,0 +1,297 @@ +package org.wonday.aliyun.push; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.support.annotation.Nullable; +import android.util.Log; + +import com.facebook.react.bridge.Arguments; +import com.facebook.react.bridge.WritableArray; +import com.facebook.react.bridge.WritableMap; + +import org.json.JSONObject; + +/** + * Created on 2018/10/17. + */ +public class SQLiteHelper extends SQLiteOpenHelper { + + final static String TABLE_NAME = "PushMsg"; + + final static String key_msgId = "msgId"; + final static String key_msgtype = "msgtype"; + final static String key_timeString = "timeString"; + + final static String key_data_title = "title"; + final static String key_data_date = "date"; + final static String key_data_time = "time"; + final static String key_data_account = "account"; + + + final static String key_data_body = "body"; + + final static String key_data_describe = "describe"; + final static String key_data_image = "image"; + final static String key_data_redirectType = "redirectType"; + final static String key_data_linkUrl = "linkUrl"; + final static String key_data_amount = "amount"; + final static String key_data_redirectData = "redirectData"; + + final static String SQL = new StringBuffer() + .append("create table ") + .append(TABLE_NAME) + .append("(id integer primary key autoincrement,") + .append(key_msgId + " varchar(64),") + .append(key_msgtype + " varchar(64),") + .append(key_timeString + " integer,") + .append(key_data_title + " varchar(64),") + .append(key_data_date + " varchar(64),") + .append(key_data_time + " varchar(64),") + .append(key_data_account + " varchar(64),") + .append(key_data_body + " varchar(500),") + .append(key_data_describe + " varchar(500),") + .append(key_data_image + " varchar(200),") + .append(key_data_redirectType + " varchar(64),") + .append(key_data_linkUrl + " varchar(200),") + .append(key_data_amount + " varchar(64),") + .append(key_data_redirectData + " varchar(200))") + .toString(); + + + private SQLiteDatabase database; + private static SQLiteHelper instance; + + public static SQLiteHelper getInstance(Context context) { + if (instance == null) { + synchronized (SQLiteHelper.class) { + if (instance == null) { + instance = new SQLiteHelper(context); + } + } + } + return instance; + } + + private SQLiteHelper(@Nullable Context context) { + super(context, "aliyun_push", null, 1); + database = getWritableDatabase(); + } + + public void insertMsg(String content) { + try { + JSONObject object = new JSONObject(content); + String msgtype = object.optString(key_msgtype); + String msgId = object.optString(key_msgId); + String timeString = object.optString(key_timeString); + + JSONObject data = object.optJSONObject("data"); + Log.v(getClass().getName(), data.toString()); + String account = data.optString(key_data_account); + String title = data.optString(key_data_title); + String date = data.optString(key_data_date); + String time = data.optString(key_data_time); + if ("url".equals(msgtype)) { + String describe = data.optString(key_data_describe); + String image = data.optString(key_data_image); + String linkUrl = data.optString(key_data_linkUrl); + insertAccountUrl(msgtype, msgId, timeString, title, date, time, account, + describe, image, linkUrl); + } else if ("text".equals(msgtype)) { + String body = data.optString(key_data_body); + insertAccountText(msgtype, msgId, timeString, title, date, time, account, + body); + } else if ("account_notice".equals(msgtype)) { + String amount = data.optString(key_data_amount); + String body = data.optString(key_data_body); + String describe = data.optString(key_data_describe); + String redirectType = data.optString(key_data_redirectType); + String redirectData = data.optString(key_data_redirectData); + insertAccountNotice(msgtype, msgId, timeString, title, date, time, account, + amount, body, describe, redirectType, redirectData); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void insertAccountUrl(String msgtype, String msgId, String timeString, + String title, String date, String time, String account, + String describe, String image, String linkUrl) { + ContentValues values = createValues(msgtype, msgId, timeString, title, date, time, account); + values.put(key_data_describe, describe); + values.put(key_data_image, image); + values.put(key_data_linkUrl, linkUrl); + database.insert(TABLE_NAME, null, values); + } + + private void insertAccountText(String msgtype, String msgId, String timeString, + String title, String date, String time, String account, + String body) { + ContentValues values = createValues(msgtype, msgId, timeString, title, date, time, account); + values.put(key_data_body, body); + database.insert(TABLE_NAME, null, values); + } + + private void insertAccountNotice(String msgtype, String msgId, String timeString, + String title, String date, String time, String account, + String amount, String body, String describe, String redirectType, String redirectData) { + ContentValues values = createValues(msgtype, msgId, timeString, title, date, time, account); + values.put(key_data_amount, amount); + values.put(key_data_body, body == null ? "" : body.replace(" ", ""));//body + values.put(key_data_describe, describe == null ? "" : describe.replace(" ", ""));//describe + values.put(key_data_redirectType, redirectType); + values.put(key_data_redirectData, redirectData); + database.insert(TABLE_NAME, null, values); + } + + private ContentValues createValues(String msgtype, String msgId, String timeString, + String title, String date, String time, String account) { + ContentValues values = new ContentValues(); + values.put(key_msgtype, msgtype); + values.put(key_msgId, msgId); + values.put(key_timeString, timeString); + + values.put(key_data_title, title); + values.put(key_data_date, date); + values.put(key_data_time, time); + values.put(key_data_account, account); + return values; + } + + public WritableArray query(String keyAccount, int page, int size) { + String limit = (page - 1) * size + "," + size; + String selection = key_data_account + " = ? or " + key_data_account + " =?"; + String orderBy = key_timeString + " DESC"; + String[] selectionArgs = new String[]{keyAccount == null ? "" : keyAccount, ""}; + Cursor cursor = database.query(TABLE_NAME, null, "" + selection, selectionArgs, null, null, + "" + orderBy, "" + limit); + WritableArray array = Arguments.createArray(); + if (cursor.getCount() > 0) { + while (cursor.moveToNext()) { + String id = cursor.getString(cursor.getColumnIndex("id")); + String msgId = cursor.getString(cursor.getColumnIndex(key_msgId)); + String msgtype = cursor.getString(cursor.getColumnIndex(key_msgtype)); + long timeString = cursor.getLong(cursor.getColumnIndex(key_timeString)); + String title = cursor.getString(cursor.getColumnIndex(key_data_title)); + String date = cursor.getString(cursor.getColumnIndex(key_data_date)); + String time = cursor.getString(cursor.getColumnIndex(key_data_time)); + + + String account = cursor.getString(cursor.getColumnIndex(key_data_account)); + String body = cursor.getString(cursor.getColumnIndex(key_data_body)); + String describe = cursor.getString(cursor.getColumnIndex(key_data_describe)); + String image = cursor.getString(cursor.getColumnIndex(key_data_image)); + String redirectType = cursor.getString(cursor.getColumnIndex(key_data_redirectType)); + String linkUrl = cursor.getString(cursor.getColumnIndex(key_data_linkUrl)); + String amount = cursor.getString(cursor.getColumnIndex(key_data_amount)); + String redirectData = cursor.getString(cursor.getColumnIndex(key_data_redirectData)); + WritableMap object = createHeader(msgId, msgtype, timeString); + if ("url".equals(msgtype)) { + object.putMap("data", createMapUrl(title, date, time, account, + describe, image, linkUrl)); + } else if ("text".equals(msgtype)) { + object.putMap("data", createMapText(title, date, time, account, + body)); + } else if ("account_notice".equals(msgtype)) { + object.putMap("data", createMapAccountNotice(title, date, time, account, + amount, body, describe, redirectType, redirectData)); + } + array.pushMap(object); +// JSONObject s = new JSONObject(); +// try { +// s.put(key_msgId, msgId); +// s.put(key_msgtype, msgtype); +// s.put(key_timeString, timeString); +// s.put(key_data_title, title); +// s.put(key_data_date, date); +// s.put(key_data_time, time); +// +// s.put(key_data_account, account); +// s.put(key_data_body, body); +// s.put(key_data_describe, describe); +// s.put(key_data_image, image); +// s.put(key_data_redirectType, redirectType); +// s.put(key_data_linkUrl, linkUrl); +// s.put(key_data_amount, amount); +// s.put(key_data_redirectData, redirectData); +// +// Log.v(getClass().getName(), "\n\n" + id); +// Log.v(getClass().getName(), s.toString()); +// } catch (JSONException e) { +// e.printStackTrace(); +// } + + } + } + + return array; + } + + public void delete() { + String selection = key_data_account + " = ?"; + String[] selectionArgs = new String[]{""}; + database.delete(TABLE_NAME, null, null); + } + + WritableMap createMapData(String title, String date, String time, String account) { + WritableMap data = Arguments.createMap(); + data.putString(key_data_title, title); + data.putString(key_data_date, date); + data.putString(key_data_time, time); + data.putString(key_data_account, account); + return data; + } + + WritableMap createMapUrl(String title, String date, String time, String account, + String describe, String image, String linkUrl) { + WritableMap url = createMapData(title, date, time, account); + + url.putString(key_data_describe, describe); + url.putString(key_data_image, image); + url.putString(key_data_linkUrl, linkUrl); + return url; + } + + WritableMap createMapText(String title, String date, String time, String account, + String body) { + WritableMap text = createMapData(title, date, time, account); + + text.putString(key_data_body, body); + return text; + } + + WritableMap createMapAccountNotice(String title, String date, String time, String account, + String amount, String body, String describe, String redirectType, String redirectData) { + WritableMap text = createMapData(title, date, time, account); + + text.putString(key_data_amount, amount); + text.putString(key_data_body, body); + text.putString(key_data_describe, describe); + text.putString(key_data_redirectType, redirectType); + text.putString(key_data_redirectData, redirectData); + return text; + } + + WritableMap createHeader(String msgId, String msgtype, long timeString) { + + WritableMap map = Arguments.createMap(); + map.putString(key_msgId, msgId); + map.putString(key_msgtype, msgtype); + map.putDouble(key_timeString, timeString); + return map; + } + + @Override + public void onCreate(SQLiteDatabase db) { + Log.v(getClass().getName(), SQL); + db.execSQL(SQL); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + + } +} diff --git a/index.js b/index.js index 3e92551..c8f6f54 100644 --- a/index.js +++ b/index.js @@ -102,8 +102,18 @@ export default class AliyunPush { }); } } - - + //根据ID获取全部通知消息,测试环境是T开头,正式环境是P开头 + static getAllNotificationMessages = (userId) => { + return AliyunPushNative.getAllNotificationMessages(); + } + // 删除全部消息 + static clearAllMessage = () => { + return AliyunPushNative.clearAllMessage(); + } + // 查询消息 + static queryMessages = (account,page=1) => { + return AliyunPushNative.queryMessages(account,page); + } static addListener = (callback) => { AliyunPush._addListener(callback,"aliyunPushReceived"); diff --git a/ios/RCTAliyunPush.xcodeproj/project.pbxproj b/ios/RCTAliyunPush.xcodeproj/project.pbxproj index cca1969..e32647a 100644 --- a/ios/RCTAliyunPush.xcodeproj/project.pbxproj +++ b/ios/RCTAliyunPush.xcodeproj/project.pbxproj @@ -7,6 +7,9 @@ objects = { /* Begin PBXBuildFile section */ + 4E1F6979217735F400918F7F /* DWMsgModel+CoreDataClass.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E1F6977217735F400918F7F /* DWMsgModel+CoreDataClass.m */; }; + 4E1F697A217735F400918F7F /* DWMsgModel+CoreDataProperties.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E1F6978217735F400918F7F /* DWMsgModel+CoreDataProperties.m */; }; + 4E1F697D2177364A00918F7F /* DWCoreDataTool.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E1F697C2177364A00918F7F /* DWCoreDataTool.m */; }; 52AE78811EEAA3F4005ECD74 /* AliyunPushManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 52AE78801EEAA3F4005ECD74 /* AliyunPushManager.m */; }; 52FF27CE1EEBF34D00CD75F7 /* AlicloudUtils.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 52FF27CB1EEBF34D00CD75F7 /* AlicloudUtils.framework */; }; 52FF27CF1EEBF34D00CD75F7 /* CloudPushSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 52FF27CC1EEBF34D00CD75F7 /* CloudPushSDK.framework */; }; @@ -27,6 +30,12 @@ /* Begin PBXFileReference section */ 134814201AA4EA6300B7C361 /* libRCTAliyunPush.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRCTAliyunPush.a; sourceTree = BUILT_PRODUCTS_DIR; }; + 4E1F6975217735F400918F7F /* DWMsgModel+CoreDataProperties.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "DWMsgModel+CoreDataProperties.h"; sourceTree = ""; }; + 4E1F6976217735F400918F7F /* DWMsgModel+CoreDataClass.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "DWMsgModel+CoreDataClass.h"; sourceTree = ""; }; + 4E1F6977217735F400918F7F /* DWMsgModel+CoreDataClass.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "DWMsgModel+CoreDataClass.m"; sourceTree = ""; }; + 4E1F6978217735F400918F7F /* DWMsgModel+CoreDataProperties.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "DWMsgModel+CoreDataProperties.m"; sourceTree = ""; }; + 4E1F697B2177364A00918F7F /* DWCoreDataTool.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = DWCoreDataTool.h; sourceTree = ""; }; + 4E1F697C2177364A00918F7F /* DWCoreDataTool.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = DWCoreDataTool.m; sourceTree = ""; }; 52AE787F1EEAA3F4005ECD74 /* AliyunPushManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AliyunPushManager.h; sourceTree = ""; }; 52AE78801EEAA3F4005ECD74 /* AliyunPushManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AliyunPushManager.m; sourceTree = ""; }; 52FF27CB1EEBF34D00CD75F7 /* AlicloudUtils.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AlicloudUtils.framework; path = libs/AlicloudUtils.framework; sourceTree = ""; }; @@ -59,12 +68,26 @@ 27F5D7ED1D0BC820003F92DE /* RCTAliyunPush */ = { isa = PBXGroup; children = ( + 4E1F69712177353100918F7F /* DWMsgModel */, 52AE787F1EEAA3F4005ECD74 /* AliyunPushManager.h */, 52AE78801EEAA3F4005ECD74 /* AliyunPushManager.m */, + 4E1F697B2177364A00918F7F /* DWCoreDataTool.h */, + 4E1F697C2177364A00918F7F /* DWCoreDataTool.m */, ); path = RCTAliyunPush; sourceTree = ""; }; + 4E1F69712177353100918F7F /* DWMsgModel */ = { + isa = PBXGroup; + children = ( + 4E1F6975217735F400918F7F /* DWMsgModel+CoreDataProperties.h */, + 4E1F6976217735F400918F7F /* DWMsgModel+CoreDataClass.h */, + 4E1F6977217735F400918F7F /* DWMsgModel+CoreDataClass.m */, + 4E1F6978217735F400918F7F /* DWMsgModel+CoreDataProperties.m */, + ); + path = DWMsgModel; + sourceTree = ""; + }; 52FF27D11EEBF38500CD75F7 /* Frameworks */ = { isa = PBXGroup; children = ( @@ -140,6 +163,9 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 4E1F697D2177364A00918F7F /* DWCoreDataTool.m in Sources */, + 4E1F697A217735F400918F7F /* DWMsgModel+CoreDataProperties.m in Sources */, + 4E1F6979217735F400918F7F /* DWMsgModel+CoreDataClass.m in Sources */, 52AE78811EEAA3F4005ECD74 /* AliyunPushManager.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/ios/RCTAliyunPush/AliyunPushManager.m b/ios/RCTAliyunPush/AliyunPushManager.m index 06a0b1f..79243aa 100644 --- a/ios/RCTAliyunPush/AliyunPushManager.m +++ b/ios/RCTAliyunPush/AliyunPushManager.m @@ -13,6 +13,8 @@ #import "AliyunPushManager.h" #import +#import "DWCoreDataTool.h" + // iOS 10 notification #import @@ -31,15 +33,18 @@ NSString *const ALIYUN_PUSH_TYPE_MESSAGE = @"message"; NSString *const ALIYUN_PUSH_TYPE_NOTIFICATION = @"notification"; - +NSString *const ALIYUN_PUSH_NOTIFICATIONMSGS = @"notificationmsgs"; +NSString *const ALIYUN_PUSH_PRIVATE = @"privateData"; +NSString *const ALIYUN_PUSH_PUBLIC = @"publicData"; @interface AliyunPushManager () +//@property (strong, nonatomic) NSMutableArray *allMessageArr; @end @implementation AliyunPushManager { - + } @@ -137,14 +142,14 @@ + (AliyunPushManager *)sharedInstance } else { // 或许还没有初始化完成,等3秒钟再次尝试 [NSThread sleepForTimeInterval:3.0f]; - + deviceId = [CloudPushSDK getDeviceId]; if (deviceId!=Nil) { resolve(deviceId); } else { reject([NSString stringWithFormat:@"getDeviceId() failed."], nil, RCTErrorWithMessage(@"getDeviceId() failed.")); } - + } } @@ -152,8 +157,8 @@ + (AliyunPushManager *)sharedInstance * bind account to cloud sdk */ RCT_EXPORT_METHOD(bindAccount:(NSString *)account - resolver:(RCTPromiseResolveBlock)resolve - rejecter:(RCTPromiseRejectBlock)reject) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { [CloudPushSDK bindAccount:account withCallback:^(CloudPushCallbackResult *res) { if (res.success) { @@ -169,7 +174,7 @@ + (AliyunPushManager *)sharedInstance */ RCT_EXPORT_METHOD(unbindAccount:(RCTPromiseResolveBlock)resolve - rejecter:(RCTPromiseRejectBlock)reject) + rejecter:(RCTPromiseRejectBlock)reject) { [CloudPushSDK unbindAccount:^(CloudPushCallbackResult *res) { if (res.success) { @@ -237,7 +242,7 @@ + (AliyunPushManager *)sharedInstance } else { reject([NSString stringWithFormat:@"%ld",(long)res.error.code], res.error.localizedDescription,res.error); } - }]; + }]; } /** @@ -278,7 +283,7 @@ + (AliyunPushManager *)sharedInstance */ RCT_EXPORT_METHOD(listAliases:(RCTPromiseResolveBlock)resolve - rejecter:(RCTPromiseRejectBlock)reject) + rejecter:(RCTPromiseRejectBlock)reject) { [CloudPushSDK listAliases:^(CloudPushCallbackResult *res) { if (res.success) { @@ -309,6 +314,35 @@ + (AliyunPushManager *)sharedInstance } } +/** + * 主动获取本地推送消息数据 + */ +//RCT_EXPORT_METHOD(getAllNotificationMessages:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) +//{ +// if (!self.allMessageArr) { +// self.allMessageArr = [NSMutableArray array]; +// } +// resolve(self.allMessageArr); +//} + +/** + * 根据page和account查询Message + */ +RCT_EXPORT_METHOD(queryMessages:(NSString *)account page:(int)page resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){ + NSMutableArray *arr = [[DWCoreDataTool sharedInstance]queryModelDictWithPage:page account:account]; + resolve(arr); +} + +/** + * 删除数据库message + */ +RCT_EXPORT_METHOD(clearAllMessage:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){ + BOOL isOk = [[DWCoreDataTool sharedInstance]deleteData]; + NSNumber *isOkNumber = [NSNumber numberWithBool:isOk]; + resolve(isOkNumber); +} + + #pragma mark - (NSArray *)supportedEvents { @@ -375,7 +409,7 @@ - (void)application:(UIApplication *)application didRegisterUserNotificationSett #pragma mark APNs Register /** - * 向APNs注册,获取deviceToken用于推送 + * 向APNs注册,获取deviceToken用于推送 * */ - (void)registerAPNs:(void (^)(void))createNotificationCategoryHandler @@ -389,7 +423,7 @@ - (void)registerAPNs:(void (^)(void))createNotificationCategoryHandler if (createNotificationCategoryHandler) { createNotificationCategoryHandler(); } - + _notificationCenter.delegate = sharedInstance; // 请求推送权限 @@ -485,7 +519,7 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNot [self sendEventToJs:notificationDict]; // 通知打开回执上报 - [CloudPushSDK sendNotificationAck:userInfo]; + [CloudPushSDK sendNotificationAck:userInfo]; if ([content.body isEqualToString:@""]){ @@ -493,7 +527,7 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNot completionHandler(UNNotificationPresentationOptionNone); } else { - + // 通知弹出,且带有声音、内容和角标 completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge); @@ -547,7 +581,7 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNoti } else { - + // 用户自定义action notificationDict[@"actionIdentifier"] =response.actionIdentifier; @@ -572,11 +606,11 @@ - (void)application:(UIApplication *)application didReceiveRemoteNotification:(N // 取得APNS通知内容 NSDictionary *aps = [userInfo valueForKey:@"aps"]; - + NSLog(@"------aps:%@",aps); NSMutableDictionary *notificationDict = [NSMutableDictionary dictionary]; // 通知时间 - notificationDict[@"date"] = [NSDate init]; + // notificationDict[@"date"] = [NSDate init]; // 标题 notificationDict[@"title"] = @""; @@ -603,14 +637,14 @@ - (void)application:(UIApplication *)application didReceiveRemoteNotification:(N // 通知打开回执上报 [CloudPushSDK sendNotificationAck:userInfo]; - + completionHandler(UIBackgroundFetchResultNewData); } #pragma mark Channel Opened /** - * 注册推送通道打开监听 + * 注册推送通道打开监听 */ - (void)listenerOnChannelOpened { @@ -622,9 +656,9 @@ - (void)listenerOnChannelOpened } /** - * 推送通道打开回调 + * 推送通道打开回调 * - * @param notification + * @param notification */ - (void)onChannelOpened:(NSNotification *)notification { @@ -633,7 +667,7 @@ - (void)onChannelOpened:(NSNotification *)notification #pragma mark Receive Message /** - * @brief 注册推送消息到来监听 + * @brief 注册推送消息到来监听 */ - (void)registerMessageReceive { @@ -645,9 +679,9 @@ - (void)registerMessageReceive } /** - * 处理到来推送消息 + * 处理到来推送消息 * - * @param notification + * @param notification */ - (void)onMessageReceived:(NSNotification *)notification { @@ -658,18 +692,25 @@ - (void)onMessageReceived:(NSNotification *)notification CCPSysMessage *message = [notification object]; notificationDict[@"title"] = [[NSString alloc] initWithData:message.title encoding:NSUTF8StringEncoding]; - notificationDict[@"body"] = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding]; + NSString *strBody = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding]; + NSData *dataBody = [strBody dataUsingEncoding:NSUTF8StringEncoding]; + NSDictionary *bodyDict = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableLeaves error:nil]; + notificationDict[@"body"] = bodyDict; + //插入数据 + [[DWCoreDataTool sharedInstance] insertClickedWithDict:bodyDict]; + // 取得通知自定义字段内容 if (notification.userInfo) { notificationDict[@"extras"] = notification.userInfo; } else { notificationDict[@"extras"] = @{}; } - - // 类型 “notification” or "message" notificationDict[@"type"] = ALIYUN_PUSH_TYPE_MESSAGE; - + // if (!self.allMessageArr) { + // self.allMessageArr = [NSMutableArray array]; + // } + // [self.allMessageArr addObject:notificationDict]; [self sendEventToJs:notificationDict]; } @@ -681,16 +722,17 @@ - (void)sendEventToJs:(NSMutableDictionary*)notification for (NSString *key in notification) { DLog(@"key: %@ value: %@", key, notification[key]); } - + //修正app退出后,点击通知会闪退bug - AliyunPushManager* __weak weakSelf = self; dispatch_async(dispatch_get_main_queue(), ^{ - //修正app退出后,点击通知会闪退bug if([UIApplication sharedApplication].applicationState == UIApplicationStateActive ||[UIApplication sharedApplication].applicationState == UIApplicationStateInactive) { - [weakSelf sendEventWithName:@"aliyunPushReceived" body:notification]; + [self sendEventWithName:@"aliyunPushReceived" body:notification]; } }); + } + + @end diff --git a/ios/RCTAliyunPush/DWCoreDataTool.h b/ios/RCTAliyunPush/DWCoreDataTool.h new file mode 100644 index 0000000..df8c32f --- /dev/null +++ b/ios/RCTAliyunPush/DWCoreDataTool.h @@ -0,0 +1,27 @@ +// +// DWCoreDataTool.h +// RCTAliyunPush +// +// Created by Dowin on 2018/10/17. +// Copyright © 2018年 Facebook. All rights reserved. +// + +#import + + + +@interface DWCoreDataTool : NSObject + ++ (DWCoreDataTool *)sharedInstance; + +//插入对象 +- (BOOL)insertClickedWithDict:(NSDictionary *)dict; +//删除数据 +- (BOOL)deleteData; +//根据account 和page查询 +- (NSMutableArray *)queryModelDictWithPage:(int)page account:(NSString *)strAccount; + + +@end + + diff --git a/ios/RCTAliyunPush/DWCoreDataTool.m b/ios/RCTAliyunPush/DWCoreDataTool.m new file mode 100644 index 0000000..723e2f1 --- /dev/null +++ b/ios/RCTAliyunPush/DWCoreDataTool.m @@ -0,0 +1,194 @@ +// +// DWCoreDataTool.m +// RCTAliyunPush +// +// Created by Dowin on 2018/10/17. +// Copyright © 2018年 Facebook. All rights reserved. +// + +#import "DWCoreDataTool.h" +#import +#import "DWMsgModel+CoreDataClass.h" + +@interface DWCoreDataTool () + +@end + +@implementation DWCoreDataTool + +static DWCoreDataTool * sharedInstance = nil; +static NSManagedObjectContext * _context = nil; + ++ (BOOL)requiresMainQueueSetup { + return YES; +} + ++ (id)allocWithZone:(NSZone *)zone { + static DWCoreDataTool *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [super allocWithZone:zone]; + }); + return sharedInstance; +} + +//copy返回单例本身 +- (id)copyWithZone:(NSZone *)zone +{ + return self; +} + +- (instancetype)init +{ + + if (!(self = [super init])) { + + } + sharedInstance = self; + return self; + +} + +//获取单例 ++ (DWCoreDataTool *)sharedInstance +{ + @synchronized(self) { + if (sharedInstance == nil){ + sharedInstance = [[self alloc] init]; + [self createSqlite]; + } + } + return sharedInstance; +} + + +#pragma mark -- CoreData +//创建数据库 ++(void)createSqlite{ + //1、创建模型对象 + NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"]; + //根据模型文件创建模型对象 + NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; + //2、创建持久化存储助理:数据库 + //利用模型对象创建助理对象 + NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; + //数据库的名称和路径 + NSString *docStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; + NSString *sqlPath = [docStr stringByAppendingPathComponent:@"coreData.sqlite"]; + NSLog(@"数据库 path = %@", sqlPath); + NSURL *sqlUrl = [NSURL fileURLWithPath:sqlPath]; + NSError *error = nil; + //设置数据库相关信息 添加一个持久化存储库并设置存储类型和路径,NSSQLiteStoreType:SQLite作为存储库 + [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlUrl options:nil error:&error]; + if (error) { + NSLog(@"-------添加数据库失败:%@",error); + } else { + NSLog(@"-------添加数据库成功"); + } + //3、创建上下文 保存信息 操作数据库 + NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; + //关联持久化助理 + context.persistentStoreCoordinator = store; + _context = context; +} + +//插入对象 +- (BOOL)insertClickedWithDict:(NSDictionary *)dict{ + + NSArray *modelArr = [self queryModelWithMsgId:[dict objectForKey:@"msgId"]]; + DWMsgModel *model; + if (modelArr.count) { + model = [modelArr firstObject]; + }else{ + model = [NSEntityDescription insertNewObjectForEntityForName:@"DWMsgModel" inManagedObjectContext:_context]; + } + model.msgId = [NSString stringWithFormat:@"%@",[dict objectForKey:@"msgId"]]; + model.timeString = [NSString stringWithFormat:@"%@",[dict objectForKey:@"timeString"]]; + model.msgtype = [dict objectForKey:@"msgtype"]; + model.account = [NSString stringWithFormat:@"%@",[[dict objectForKey:@"data"] objectForKey:@"account"] ? :@""]; + NSData *tmpData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil]; + model.data = tmpData; + + // 3.保存更新/插入的数据 + NSError *error = nil; + if ([_context save:&error]) { + NSLog(@"-------数据插入到数据库成功"); + return YES; + }else{ + NSLog(@"-------数据插入到数据库失败, %@",error); + return NO; + } +} + +//根据msgID查询model +- (NSArray *)queryModelWithMsgId:(NSString *)strId{ + //创建查询请求 + NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"DWMsgModel"]; + NSPredicate *pre = [NSPredicate predicateWithFormat:@"msgId = %@",strId]; + request.predicate = pre; + //发送请求 + NSArray *resArray = [_context executeFetchRequest:request error:nil]; + + return resArray; +} + +//删除数据 +- (BOOL)deleteData{ + //创建删除请求 + NSFetchRequest *deleRequest = [NSFetchRequest fetchRequestWithEntityName:@"DWMsgModel"]; + //返回需要删除的对象数组 + NSArray *deleArray = [_context executeFetchRequest:deleRequest error:nil]; + + //从数据库中删除 + for (DWMsgModel *model in deleArray) { + [_context deleteObject:model]; + } + + NSError *error = nil; + //保存--记住保存 + if ([_context save:&error]) { + NSLog(@"删除成功"); + return YES; + }else{ + NSLog(@"删除数据失败, %@", error); + return NO; + } +} + +//根据account 和page查询 +- (NSMutableArray *)queryModelDictWithPage:(int)page account:(NSString *)strAccount{ + static int limit=20; + NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"DWMsgModel"]; + request.fetchLimit=limit; + request.fetchOffset=(page-1)*limit; + NSPredicate *predicate=[NSPredicate predicateWithFormat:@"account=%@ or account=%@",strAccount,@""]; + request.predicate=predicate; + + NSSortDescriptor *timeSorter=[NSSortDescriptor sortDescriptorWithKey:@"timeString" ascending:NO]; + + request.sortDescriptors=@[timeSorter]; + + NSArray *array=[_context executeFetchRequest:request error:nil]; + NSMutableArray *dictArr = [NSMutableArray array]; + for (DWMsgModel *tmpModel in array) { + NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:tmpModel.data options:NSJSONReadingMutableContainers error:nil]; + [dictArr addObject:dict]; + } + return dictArr; +} + +//查询所有对象 +- (NSMutableArray *)queryAllModelDict{ + //查询所有数据的请求 + NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"DWMsgModel"]; + NSArray *resArray = [_context executeFetchRequest:request error:nil]; + NSMutableArray *dictArr = [NSMutableArray array]; + for (DWMsgModel *tmpModel in resArray) { + NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:tmpModel.data options:NSJSONReadingMutableContainers error:nil]; + [dictArr addObject:dict]; + } + return dictArr; +} + + +@end diff --git a/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataClass.h b/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataClass.h new file mode 100644 index 0000000..32c080a --- /dev/null +++ b/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataClass.h @@ -0,0 +1,21 @@ +// +// DWMsgModel+CoreDataClass.h +// RCTAliyunPush +// +// Created by Dowin on 2018/10/17. +// Copyright © 2018年 Facebook. All rights reserved. +// +// + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface DWMsgModel : NSManagedObject + +@end + +NS_ASSUME_NONNULL_END + +#import "DWMsgModel+CoreDataProperties.h" diff --git a/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataClass.m b/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataClass.m new file mode 100644 index 0000000..d34a079 --- /dev/null +++ b/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataClass.m @@ -0,0 +1,14 @@ +// +// DWMsgModel+CoreDataClass.m +// RCTAliyunPush +// +// Created by Dowin on 2018/10/17. +// Copyright © 2018年 Facebook. All rights reserved. +// +// + +#import "DWMsgModel+CoreDataClass.h" + +@implementation DWMsgModel + +@end diff --git a/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataProperties.h b/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataProperties.h new file mode 100644 index 0000000..466129f --- /dev/null +++ b/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataProperties.h @@ -0,0 +1,27 @@ +// +// DWMsgModel+CoreDataProperties.h +// RCTAliyunPush +// +// Created by Dowin on 2018/10/17. +// Copyright © 2018年 Facebook. All rights reserved. +// +// + +#import "DWMsgModel+CoreDataClass.h" + + +NS_ASSUME_NONNULL_BEGIN + +@interface DWMsgModel (CoreDataProperties) + ++ (NSFetchRequest *)fetchRequest; + +@property (nullable, nonatomic, copy) NSString *account; +@property (nullable, nonatomic, retain) NSData *data; +@property (nullable, nonatomic, copy) NSString *msgId; +@property (nullable, nonatomic, copy) NSString *msgtype; +@property (nullable, nonatomic, copy) NSString *timeString; + +@end + +NS_ASSUME_NONNULL_END diff --git a/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataProperties.m b/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataProperties.m new file mode 100644 index 0000000..f950db4 --- /dev/null +++ b/ios/RCTAliyunPush/DWMsgModel/DWMsgModel+CoreDataProperties.m @@ -0,0 +1,24 @@ +// +// DWMsgModel+CoreDataProperties.m +// RCTAliyunPush +// +// Created by Dowin on 2018/10/17. +// Copyright © 2018年 Facebook. All rights reserved. +// +// + +#import "DWMsgModel+CoreDataProperties.h" + +@implementation DWMsgModel (CoreDataProperties) + ++ (NSFetchRequest *)fetchRequest { + return [NSFetchRequest fetchRequestWithEntityName:@"DWMsgModel"]; +} + +@dynamic account; +@dynamic data; +@dynamic msgId; +@dynamic msgtype; +@dynamic timeString; + +@end