quick 3.3 个推ios集成

 

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

    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

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