#import "AppDelegate.h"
#import "GexinSdk.h"
#import "ViewController.h"
@interface AppDelegate ()<GexinSdkDelegate>
{
GexinSdk *_gexinSdk;
}
@end
@implementation AppDelegate
//开始个推
-(void)startGeTui{
if (_gexinSdk==nil) {//首先系统会给个推分配一个空的地址,判断如果这个东西存在了,那么就给他初始化
NSError *error=nil;
_gexinSdk=[GexinSdk
createSdkWithAppId:@"F84d2DtT68AhFEnBrzio83"
appKey:@"OFymP7ka9J6s0ZkdeiSLS9"
appSecret:@"FM0eZU7lCE7FK7wa1r9JD9"
appVersion:@"1.0"
delegate:self
error:&error];//可能会因为个推服务器的网络延迟,数据错误等初始化失败,一旦初始化失败,就给error赋一个值
while (error !=nil) {//如果error不为空,就是有值了,那就说明前一步初始化的时候出现错误了,重新给初始化
error=nil;
_gexinSdk=[GexinSdk createSdkWithAppId:@"F84d2DtT68AhFEnBrzio83"
appKey:@"OFymP7ka9J6s0ZkdeiSLS9"
appSecret:@"FM0eZU7lCE7FK7wa1r9JD9"
appVersion:@"1.0"
delegate:self
error:&error];
}
}
}
//结束
-(void)stopGeTui{
if (_gexinSdk) {
[_gexinSdk destroy];
_gexinSdk=nil;
}
}
//注册委托方 //clientId手机唯一标志
- (void)GexinSdkDidRegisterClient:(NSString *)clientId{
[[NSUserDefaults standardUserDefaults]setValue:clientId forKey:kPushUserID];
ViewController *v=(ViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
self.window.rootViewController=v;
NSLog(@"注册得到的===clientId====#########=====%@",clientId);
}
//注册发生错误的时候---->类似一个容错机制
- (void)GexinSdkDidOccurError:(NSError *)error{
}
//发送消息
- (void)GexinSdkDidSendMessage:(NSString *)messageId result:(int)result{
}
//收到推送消息的时候
- (void)GexinSdkDidReceivePayload:(NSString *)payloadId fromApplication:(NSString *)appId{
NSLog(@"GexinSdkDidReceivePayload : %@",payloadId);
NSData *payload=[_gexinSdk retrivePayloadById:payloadId];
NSString *payloadMsg=nil;
if (payload) {
payloadMsg=[[NSString alloc]initWithBytes:payload.bytes
length:payload.length
encoding:NSUTF8StringEncoding];
}
//NSLog(@"收到的消息%@",payloadMsg);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:payload options:0 error:nil];
[[NSNotificationCenter defaultCenter]postNotificationName:HJieDan object:dic userInfo:nil];
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{//如果成功的话,就去注册个推
NSString *token=[[deviceToken description]stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
NSString *strDeviceToken=[token stringByReplacingOccurrencesOfString:@" " withString:@""];
//NSLog(@"deviceToken===-----------===%@",strDeviceToken);
[self startGeTui];
if (_gexinSdk!=nil) {
[_gexinSdk registerDeviceToken:strDeviceToken];
}
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{//如果失败了,把这东西置为空
if (_gexinSdk!=nil) {
[_gexinSdk registerDeviceToken:@" "];
}
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
//设置小红点的个数
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
NSString *payloadMsg=[userInfo objectForKey:@"payload"];
NSLog(@"did:%@",payloadMsg);//打印出来 接受到的发送消息
completionHandler(UIBackgroundFetchResultNewData);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UIViewController *_viewController = [[UIViewController alloc] init];
UINavigationController *_navViewController = [[UINavigationController alloc] initWithRootViewController:_viewController];
_navViewController.navigationBar.hidden = YES;
[self startGeTui];//创建个推
#warning 注册推送
//注册 推 送
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
[[UIApplication sharedApplication] registerForRemoteNotifications]; //8.0 远程token 注册
[[UIApplication sharedApplication] registerUserNotificationSettings:uns];
} else {
UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
} //注册完毕
[application.keyWindow.rootViewController.view addSubview:_navViewController.view];
// DNWRootViewController *hvc=[DNWRootViewController new];
// self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
// self.window.backgroundColor=[UIColor whiteColor];
// [self.window makeKeyAndVisible];
// _window.rootViewController=hvc;
/*******************************************************************/
#pragma mark - 本地通知 ###########
/*
UILocalNotification *notification=[[UILocalNotification alloc] init];
if (notification!=nil) {
NSDate *now = [NSDate date];
//从现在开始,10秒以后通知
notification.fireDate=[now dateByAddingTimeInterval:10];
//使用本地时区
notification.timeZone=[NSTimeZone defaultTimeZone];
[email protected]"顶部提示内容,通知时间到啦";
//通知提示音 使用默认的
notification.soundName= UILocalNotificationDefaultSoundName;
notification.alertAction=NSLocalizedString(@"你锁屏啦,通知时间到啦", nil);
//这个通知到时间时,你的应用程序右上角显示的数字。
notification.applicationIconBadgeNumber = 1;
//add key 给这个通知增加key 便于半路取消。nfkey这个key是我自己随便起的。
// 假如你的通知不会在还没到时间的时候手动取消 那下面的两行代码你可以不用写了。
// NSDictionary *dict =[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:notificationtag],@"nfkey",nil];
// [notification setUserInfo:dict];
//启动这个通知
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
//这句真的特别特别重要。如果不加这一句,通知到时间了,发现顶部通知栏提示的地方有了,然后你通过通知栏进去,然后你发现通知栏里边还有这个提示
//除非你手动清除,这当然不是我们希望的。加上这一句就好了。网上很多代码都没有,就比较郁闷了。
// [notification release];
}
*/
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.
}
- (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, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (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.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application‘s managed object context before the application terminates.
[self saveContext];
}
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "-23.about_Car" in the application‘s documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"about_Car" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"about_Car.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application‘s saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application‘s saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
@end