quick 3.3 个推ios集成

对于oc比较不熟练,只能先copy能用然后再理解,参考demo修改的。。。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
AppController.h
#import <UIKit/UIKit.h>
#import "GeTuiSdk.h"

#define kGtAppId @"PJ1tgxuQqw6F62YKmHiKM"
#define kGtAppKey @"WIWEz4faij8udpPiOlMhc5"
#define kGtAppSecret @"QL0vlepuwC8QiFyUP4dwP5"

@class RootViewController;

@interface AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate,UIApplicationDelegate, GeTuiSdkDelegate>
{
UIWindow *window;
RootViewController *viewController;
}

/**
获取个推的AppId、AppKey、AppSecret
Demo演示时代码,正式集成时可以简化该模块
*/
+ (NSString *)getGtAppId;
+ (NSString *)getGtAppKey;
+ (NSString *)getGtAppSecret;

- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret;


AppController.mm
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#import <UIKit/UIKit.h>
#import "cocos2d.h"

#import "AppController.h"
#import "AppDelegate.h"
#import "RootViewController.h"
#import "platform/ios/CCEAGLView-ios.h"

#define NotifyActionKey "NotifyAction"
NSString *const NotificationCategoryIdent = @"ACTIONABLE";
NSString *const NotificationActionOneIdent = @"ACTION_ONE";
NSString *const NotificationActionTwoIdent = @"ACTION_TWO";

@implementation AppController

#pragma mark -
#pragma mark Application lifecycle

// cocos2d application instance
static AppDelegate s_sharedApplication;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

cocos2d::Application *app = cocos2d::Application::getInstance();
app->initGLContextAttrs();
cocos2d::GLViewImpl::convertAttrs();

// Override point for customization after application launch.

// Add the view controller"s view to the window and display.
window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds]
pixelFormat: (NSString*)cocos2d::GLViewImpl::_pixelFormat
depthFormat: cocos2d::GLViewImpl::_depthFormat
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0 ];

[eaglView setMultipleTouchEnabled:YES];

// Use RootViewController manage CCEAGLView
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
viewController.wantsFullScreenLayout = YES;
viewController.view = eaglView;

// Set RootViewController to window
if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
// warning: addSubView doesn"t work on iOS6
[window addSubview: viewController.view];
}
else
{
// use this method on ios6
[window setRootViewController:viewController];
}

[window makeKeyAndVisible];

[[UIApplication sharedApplication] setStatusBarHidden: YES];

// IMPORTANT: Setting the GLView should be done after creating the RootViewController
cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView(eaglView);
cocos2d::Director::getInstance()->setOpenGLView(glview);
// [1]:使用APPID/APPKEY/APPSECRENT创建个推实例
// 注:该代码写法仅适用演示Demo,正式集成可简化,请参考“集成Demo”
// 该方法需要在主线程中调用
[self startSdkWith:[AppController getGtAppId] appKey:[AppController getGtAppKey] appSecret:[AppController getGtAppSecret]];

// [2]:注册APNS
[self registerRemoteNotification];

// [2-EXT]: 获取启动时收到的APN数据
NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];



NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
app->run();
return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
cocos2d::Director::getInstance()->pause();
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
cocos2d::Director::getInstance()->resume();
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
cocos2d::Application::getInstance()->applicationDidEnterBackground();
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
*/
cocos2d::Application::getInstance()->applicationWillEnterForeground();
}

- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
}

static void uncaughtExceptionHandler(NSException *exception) {
NSLog(@"CRASH: %@", exception);
NSLog(@"Stack Trace: %@", [exception callStackSymbols]);

//异常的堆栈信息
NSArray *stackArray = [exception callStackSymbols];
//出现异常的原因
NSString *reason = [exception reason];
//异常名称
NSString *name = [exception name];
NSString *exceptionInfo = [NSString stringWithFormat:@"Exceptionreason:%@\\nExceptionname:%@\\nExceptionstack:%@", name, reason, stackArray];
NSLog(@"%@", exceptionInfo);

//保存到本地--当然你可以在下次启动的时候,上传这个log
[exceptionInfo writeToFile:[NSString stringWithFormat:@"%@/Documents/error.log", NSHomeDirectory()] atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

#pragma mark - background fetch 唤醒
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

//[5] Background Fetch 恢复SDK 运行
[GeTuiSdk resume];

completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - 用户通知(推送) _自定义方法

/** 注册远程通知 */
- (void)registerRemoteNotification {

#ifdef __IPHONE_8_0
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
//IOS8 新的通知机制category注册
UIMutableUserNotificationAction *action1;
action1 = [[UIMutableUserNotificationAction alloc] init];
[action1 setActivationMode:UIUserNotificationActivationModeBackground];
[action1 setTitle:@"取消"];
[action1 setIdentifier:NotificationActionOneIdent];
[action1 setDestructive:NO];
[action1 setAuthenticationRequired:NO];

UIMutableUserNotificationAction *action2;
action2 = [[UIMutableUserNotificationAction alloc] init];
[action2 setActivationMode:UIUserNotificationActivationModeBackground];
[action2 setTitle:@"回复"];
[action2 setIdentifier:NotificationActionTwoIdent];
[action2 setDestructive:NO];
[action2 setAuthenticationRequired:NO];

UIMutableUserNotificationCategory *actionCategory;
actionCategory = [[UIMutableUserNotificationCategory alloc] init];
[actionCategory setIdentifier:NotificationCategoryIdent];
[actionCategory setActions:@[ action1, action2 ]
forContext:UIUserNotificationActionContextDefault];

NSSet *categories = [NSSet setWithObject:actionCategory];
UIUserNotificationType types = (UIUserNotificationTypeAlert |
UIUserNotificationTypeSound |
UIUserNotificationTypeBadge);

UIUserNotificationSettings *settings;
settings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
[[UIApplication sharedApplication] registerForRemoteNotifications];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];

} else {
UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeBadge);
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
}
#else
UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeBadge);
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#endif
}

#pragma mark - 远程通知(推送)回调

/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"deviceToken:%@", token);

// [3]:向个推服务器注册deviceToken
[GeTuiSdk registerDeviceToken:token];
}

/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
// [3-EXT]:如果APNS注册失败,通知个推服务器
[GeTuiSdk registerDeviceToken:@""];
}

#pragma mark - APP运行中接收到通知(推送)处理

/** APP已经接收到“远程”通知(推送) - (App运行在后台/App运行在前台) */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

// [4-EXT]:处理APN
NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], userInfo];
}

/** APP已经接收到“远程”通知(推送) - 透传推送消息 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {

// [4-EXT]:处理APN
NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], userInfo];

completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - 启动GeTuiSdk

/**
获取个推的AppId、AppKey、AppSecret
注:该代码写法仅适用演示Demo,正式集成可简化,请参考“集成Demo”
*/
+ (NSString *)getGtAppId {
NSString *reValue = kGtAppId;

// 添加额外代码,方便测试修改App配置
NSString *configPath = [[NSBundle mainBundle] pathForResource:@"gtsdk" ofType:@"plist"];
NSDictionary *configs = [NSDictionary dictionaryWithContentsOfFile:configPath];
if (configs) {
// SDK测试使用的appid
NSString *appid = configs[@"com.getui.kGTAppId"];
if (appid && [appid isKindOfClass:[NSString class]] && appid.length) {
reValue = appid;
}
}

return reValue;
}
+ (NSString *)getGtAppKey {
NSString *reValue = kGtAppKey;

// 添加额外代码,方便测试修改App配置
NSString *configPath = [[NSBundle mainBundle] pathForResource:@"gtsdk" ofType:@"plist"];
NSDictionary *configs = [NSDictionary dictionaryWithContentsOfFile:configPath];
if (configs) {
// SDK测试使用的appkey
NSString *appkey = configs[@"com.getui.kGTAppKey"];
if (appkey && [appkey isKindOfClass:[NSString class]] && appkey.length) {
reValue = appkey;
}
}

return reValue;
}
+ (NSString *)getGtAppSecret {
NSString *reValue = kGtAppSecret;

// 添加额外代码,方便测试修改App配置
NSString *configPath = [[NSBundle mainBundle] pathForResource:@"gtsdk" ofType:@"plist"];
NSDictionary *configs = [NSDictionary dictionaryWithContentsOfFile:configPath];
if (configs) {
// SDK测试使用的appid
NSString *appsecret = configs[@"com.getui.kGTAppSecret"];
if (appsecret && [appsecret isKindOfClass:[NSString class]] && appsecret.length) {
reValue = appsecret;
}
}

return reValue;
}

- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret {

// 添加额外代码,方便测试修改App配置
NSString *configPath = [[NSBundle mainBundle] pathForResource:@"gtsdk" ofType:@"plist"];
NSDictionary *configs = [NSDictionary dictionaryWithContentsOfFile:configPath];
if (configs) {
// SDK测试使用的appid
NSString *appid = configs[@"com.getui.kGTAppId"];
if (appid && [appid isKindOfClass:[NSString class]] && appid.length) {
appID = appid;
}

NSString *appkey = configs[@"com.getui.kGTAppKey"];
if (appkey && [appkey isKindOfClass:[NSString class]] && appkey.length) {
appKey = appkey;
}

NSString *appsecret = configs[@"com.getui.kGTAppSecret"];
if (appsecret && [appsecret isKindOfClass:[NSString class]] && appsecret.length) {
appSecret = appsecret;
}
}

//[1-1]:通过 AppId、 appKey 、appSecret 启动SDK
//该方法需要在主线程中调用
[GeTuiSdk startSdkWithAppId:appID appKey:appKey appSecret:appSecret delegate:self];

//[1-2]:设置是否后台运行开关
[GeTuiSdk runBackgroundEnable:YES];
//[1-3]:设置电子围栏功能,开启LBS定位服务 和 是否允许SDK 弹出用户定位请求
[GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
}

#pragma mark - GeTuiSdkDelegate

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
// [4-EXT-1]: 个推SDK已注册,返回clientId
NSLog(@">>>[GeTuiSdk RegisterClient]:%@", clientId);
}

/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayload:(NSString *)payloadId andTaskId:(NSString *)taskId andMessageId:(NSString *)aMsgId andOffLine:(BOOL)offLine fromApplication:(NSString *)appId {
// [4]: 收到个推消息
NSData *payload = [GeTuiSdk retrivePayloadById:payloadId];
NSString *payloadMsg = nil;
if (payload) {
payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
length:payload.length
encoding:NSUTF8StringEncoding];
}


NSString *msg = [NSString stringWithFormat:@"%@ : %@%@", [self formateTime:[NSDate date]], payloadMsg, offLine ? @"<离线消息>" : @""];
NSLog(@"GexinSdkReceivePayload : %@, taskId: %@, msgId :%@", msg, taskId, aMsgId);
}



//SDK设置推送模式回调
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
}

- (NSString *)formateTime:(NSDate *)date {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
NSString *dateTime = [formatter stringFromDate:date];
return dateTime;
}



#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
cocos2d::Director::getInstance()->purgeCachedData();
}
- (void)dealloc {
[super dealloc];
}


@end

暂时可以用推送,具体的还需要再修改,日志也没有。。。恩,现在去搞后台直接推送了。。。

查看评论