你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS自定義推送消息提示框

iOS自定義推送消息提示框

編輯:IOS開發綜合

看到標題你可能會覺得奇怪 推送消息提示框不是系統自己彈出來的嗎? 為什麼還要自己自定義呢? 

因為項目需求是這樣的:最近需要做 遠程推送通知 和一個客服系統 包括店鋪客服和官方客服兩個模塊 如果有新的消息推送的時候 如果用戶當前不在客服界面的時候  要求無論是在app前台 還是app退到後台 頂部都要彈出系統的那種消息提示框

這樣的需求 我們就只能自定義一個在app內 彈出消息提示框  

實現步驟如下: 

1.我們自定義一個view 為 STPushView 推送消息的提示框view 

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

@interface STPushView : UIView

/** *推送數據模型 */
@property(nonatomic,strong) STPushModel *model;

+(instancetype)shareInstance;
+ (void)show;
+ (void)hide;

@end 

#import "STPushView.h"
#import "AppDelegate.h"

@interface STPushView()

@property (nonatomic, weak) UIImageView *imageV;
@property (nonatomic,weak ) UILabel *timLabel;
@property (nonatomic,weak ) UILabel *content;

@end

@implementation STPushView

static STPushView *_instance = nil;

+(instancetype)shareInstance
{
 static dispatch_once_t onceToken;
 dispatch_once(&onceToken, ^{
 _instance = [[STPushView alloc] init];
 });
 return _instance;
}

+(instancetype) allocWithZone:(struct _NSZone *)zone
{
 if (!_instance) {
 _instance = [super allocWithZone:zone];
 }
 return _instance ;
}

- (instancetype)initWithFrame:(CGRect)frame
{
 if (self = [super initWithFrame:frame]) {
 
 self.backgroundColor = CUSTOMCOLOR(15, 14, 12);
 
 CGFloat margin = 12;
 UIImageView *imageV = [[UIImageView alloc] init];
 imageV.userInteractionEnabled = NO;
 imageV.image = [UIImage imageNamed:@"logo"];
 imageV.layer.cornerRadius = 5;
 [self addSubview:imageV];
 self.imageV = imageV;
 [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
  make.left.equalTo(self).offset(margin);
  make.centerY.equalTo(self.mas_centerY);
  make.width.mas_equalTo(30);
  make.height.mas_equalTo(30);
 }];
 
 
 UILabel *titleLabel = [[UILabel alloc] init];
 titleLabel.textColor = [UIColor whiteColor];
 titleLabel.font = [UIFont boldSystemFontOfSize:12];
 titleLabel.text = @"121店官方客服";
 [self addSubview:titleLabel];
 [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  make.left.equalTo(imageV.mas_right).offset(margin);
  make.top.equalTo(self.mas_top).offset(margin);
  make.height.mas_equalTo(16);
 }];
 [titleLabel sizeToFit];
 
 UILabel *timLabel = [[UILabel alloc] init];
 timLabel.font = [UIFont systemFontOfSize:12];
 timLabel.userInteractionEnabled = NO;
 timLabel.textColor = [UIColor whiteColor];
 timLabel.text = @"剛剛";
 timLabel.textColor = [UIColor lightGrayColor];
 [self addSubview:timLabel];
 self.timLabel = timLabel;
 [timLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  make.left.equalTo(titleLabel.mas_right).offset(margin);
  make.top.equalTo(self.mas_top).offset(margin);
  make.width.mas_lessThanOrEqualTo(40);
  make.height.mas_equalTo(16);
 }];
 
 
 UILabel *content = [[UILabel alloc] init];
 content.numberOfLines = 2;
 content.font = [UIFont systemFontOfSize:13];
 content.textColor = [UIColor whiteColor];
 content.userInteractionEnabled = NO;
 [self addSubview:content];
 self.content = content;
 [content mas_makeConstraints:^(MASConstraintMaker *make) {
  make.left.equalTo(imageV.mas_right).offset(margin);
  make.top.equalTo(titleLabel.mas_bottom).offset(-3);
  make.right.equalTo(self.mas_right).offset(-margin);
  make.height.mas_equalTo(35);
 }];
 
 
 UIView *toolbar = [[UIView alloc] init];
 toolbar.backgroundColor = CUSTOMCOLOR(121, 101, 81);
 toolbar.layer.cornerRadius = 3;
 [self addSubview:toolbar];
 [toolbar mas_makeConstraints:^(MASConstraintMaker *make) {
  make.width.mas_equalTo(35);
  make.height.mas_equalTo(6);
  make.centerX.equalTo(self.mas_centerX);
  make.bottom.equalTo(self.mas_bottom).offset(-2);
 }];
 
 }
 return self;
}

- (void)setModel:(STPushModel *)model
{
 _model = model;
 self.timLabel.text = @"剛剛";
 self.content.text = model.content;
}

+ (void)show
{
 
 [UIApplication sharedApplication].statusBarHidden = YES;
 STPushView *pushView = [STPushView shareInstance];
 pushView.hidden = NO;
 
 AppDelegate *app = (AppDelegate*)[UIApplication sharedApplication].delegate;
 [app.window bringSubviewToFront:pushView];

 [UIView animateWithDuration:0.25 animations:^{
 
 pushView.frame = CGRectMake(0, 0, SCREEN_WIDTH, pushViewHeight);
 
 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  
  [UIView animateWithDuration:0.25 animations:^{
  
  pushView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
  
  
  } completion:^(BOOL finished) {
  
  [UIApplication sharedApplication].statusBarHidden = NO;
  pushView.hidden = YES;
  
  }];
  
 });
 
 }];
}

+ (void)hide
{
 STPushView *pushView = [STPushView shareInstance];

 [UIView animateWithDuration:0.25 animations:^{
 
 pushView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
 
 } completion:^(BOOL finished) {
 
 [UIApplication sharedApplication].statusBarHidden = NO;
 pushView.hidden = YES;
 
 }];

}

@end 

上面pushView需要一個模型 實現代碼如下 

// push 推送的model

推送過來的數據如下:
/**
 content = dsfdsnfds;
 id = 5077;
 mid = 1270339;
 title = dsfdsnfds;
 url = "3?_from=push";
 urlType = 3;
 
 **/
#import <Foundation/Foundation.h>

@interface STPushModel : STBaseModel<NSCoding> //STBaseModel 是一個繼承自NSObject的類 我主要是在這個類中實現了字典轉模型的功能 你可以直接修改為NSObject

/***id**/
@property (copy,nonatomic) NSString* recordId;
/***標題**/
@property (copy, nonatomic) NSString *title;
/***url**/
@property (copy, nonatomic) NSString *url;
/***url 類型**/
@property (copy, nonatomic) NSString* urlType;
/***圖標的高度**/
@property (assign,nonatomic) NSString * mid;
/***推送內容**/
@property (copy, nonatomic) NSString* content;

@end 

因為涉及到好幾個頁面需要使用同樣的推送消息數據 進行判斷而處理相應的業務 所有我對此模型做了歸檔處理

#import "STPushModel.h"

@implementation STPushModel


/**
 * 保存對象到文件中
 *
 * @param aCoder <#aCoder description#>
 */
-(void)encodeWithCoder:(NSCoder *)aCoder
{
 [aCoder encodeObject:self.recordId forKey:@"recordId"];
 [aCoder encodeObject:self.title forKey:@"title"];
 [aCoder encodeObject:self.url forKey:@"url"];
 [aCoder encodeObject:self.urlType forKey:@"urlType"];
 [aCoder encodeObject:self.mid forKey:@"mid"];
 [aCoder encodeObject:self.content forKey:@"content"];
}


/**
 * 從文件中讀取對象
 *
 * @param aDecoder <#aDecoder description#>
 *
 * @return <#return value description#>
 */
-(id)initWithCoder:(NSCoder *)aDecoder
{
 //注意:在構造方法中需要先初始化父類的方法
 if (self=[super init]) {
 self.recordId=[aDecoder decodeObjectForKey:@"recordId"];
 self.title=[aDecoder decodeObjectForKey:@"title"];
 self.url=[aDecoder decodeObjectForKey:@"url"];
 self.urlType=[aDecoder decodeObjectForKey:@"urlType"];
 self.mid=[aDecoder decodeObjectForKey:@"mid"];
 self.content= [aDecoder decodeObjectForKey:@"content"];
 }
 return self;
}
@end 

做好了上面的准備工作之後  接下來我們就需要 APPdelegate裡面注冊遠程推送通知  並且監聽推送消息 

這裡以個推為例子:

第一步在下面的方法中 實現個推的注冊方法 

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

 // 注冊個推推送服務
 [[GeTuiApilmpl sharedInstance] geTuiRegister];


} 

GeTuiApilmpl 是一個單例類 專門用於注冊個推的推送方法 實現代碼如下:

#import <Foundation/Foundation.h>
#import "GeTuiSdk.h"
@interface GeTuiApilmpl : NSObject <GeTuiSdkDelegate>

+ (GeTuiApilmpl *) sharedInstance;

- (void) geTuiRegister;

@end 

#import "GeTuiApilmpl.h"

@implementation GeTuiApilmpl

+ (GeTuiApilmpl *) sharedInstance{
 static id instance = nil;
 static dispatch_once_t onceToken;
 dispatch_once(&onceToken, ^{
 instance = [[self alloc] init];
 });
 return instance;
}

- (id)init {
 self = [super init];
 if (self) {
 NSString *path = [[NSBundle mainBundle] pathForResource:@"libGexin" ofType:@"plist"];
 NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
 [GeTuiSdk startSdkWithAppId:[dic objectForKey:@"GT_APPID"]
    appKey:[dic objectForKey:@"GT_APPKEY"]
    appSecret:[dic objectForKey:@"GT_APPSECRET"]
    delegate:self];
 }
 return self;
}

#pragma mark - GeTuiSdkDelegate
/** SDK啟動成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
 // [4-EXT-1]: 個推SDK已注冊,返回clientId
 NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}

/** SDK遇到錯誤回調 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
 // [EXT]:個推錯誤報告,集成步驟發生的任何錯誤都在這裡通知,如果集成後,無法正常收到消息,查看這裡的通知。
 NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}

/** 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:@" payloadId=%@,taskId=%@,messageId:%@,payloadMsg:%@%@", payloadId, taskId, aMsgId, payloadMsg, offLine ? @"<離線消息>" : @""];
 NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
 /**
 *匯報個推自定義事件
 *actionId:用戶自定義的actionid,int類型,取值90001-90999。
 *taskId:下發任務的任務ID。
 *msgId: 下發任務的消息ID。
 *返回值:BOOL,YES表示該命令已經提交,NO表示該命令未提交成功。注:該結果不代表服務器收到該條命令
 **/
 [GeTuiSdk sendFeedbackMessage:90001 taskId:taskId msgId:aMsgId];
}

/** SDK收到sendMessage消息回調 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
 // [4-EXT]:發送上行消息結果反饋
 NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
 NSLog(@"\n>>>[GexinSdk DidSendMessage]:%@\n\n", msg);
}

/** SDK運行狀態通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
 // [EXT]:通知SDK運行狀態
 NSLog(@"\n>>>[GexinSdk SdkState]:%u\n\n", aStatus);
}

/** SDK設置推送模式回調 */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
 if (error) {
 NSLog(@"\n>>>[GexinSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
 return;
 }
 NSLog(@"\n>>>[GexinSdk SetModeOff]:%@\n\n", isModeOff ? @"開啟" : @"關閉");
}

-(void)geTuiRegister{
 
} 

然後再appDelegate 調用注冊遠程推送的方法  

/** 注冊用戶通知 */
- (void)registerUserNotification {
 /*
 注冊通知(推送)
 申請App需要接受來自服務商提供推送消息
 */
 // 判讀系統版本是否是“iOS 8.0”以上
 if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ||
 [UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
 // 定義用戶通知類型(Remote.遠程 - Badge.標記 Alert.提示 Sound.聲音)
 UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
 // 定義用戶通知設置
 UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
 // 注冊用戶通知 - 根據用戶通知設置
 [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
 [[UIApplication sharedApplication] registerForRemoteNotifications];
 } else { // iOS8.0 以前遠程推送設置方式
 // 定義遠程通知類型(Remote.遠程 - Badge.標記 Alert.提示 Sound.聲音)
 UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
 // 注冊遠程通知 -根據遠程通知類型
 [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
 }
} 

然後再設置了窗口的跟控制器 之後 調用:addPushView方法 添加 消息提示框STPushView:  addPushView實現代碼如下 

#pragma mark 推送信息展示
//添加推送view
- (void)addPushView
{
 STPushView *topView = [STPushView shareInstance];
 topView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
 [_window addSubview:topView];
 self.topView = topView;
 topView.hidden = YES;
 
 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hudClick)];
 UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
 [topView addGestureRecognizer:tap];
 [tap requireGestureRecognizerToFail:pan];
 topView.gestureRecognizers = @[tap,pan];
 
}

#pragma mark addPushView相關事件
- (void)hudClick
{
 self.topView.userInteractionEnabled = NO;
 
 [UIView animateWithDuration:0.25 animations:^{
 self.topView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
 }completion:^(BOOL finished) {
 [UIApplication sharedApplication].statusBarHidden = NO;
 [self hudClickOperation];
 
 }];
}

- (void)hudClickOperation
{
 [self push:nil];
 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
 self.topView.userInteractionEnabled = YES;
 });
}


- (void)pan:(UIPanGestureRecognizer*)pan
{
 CGFloat distance = pushViewHeight-(pushViewHeight-[pan translationInView:self.window].y);
 if (distance<-20) {
 [UIView animateWithDuration:0.25 animations:^{
  self.topView.frame = CGRectMake(0, -pushViewHeight, SCREEN_WIDTH, pushViewHeight);
 }completion:^(BOOL finished) {
  [UIApplication sharedApplication].statusBarHidden = NO;
 }];
 }
}

//顯示pushView
- (void)displayPushView
{
 [STPushView show];
} 

上面push方法的實現代碼如下: 處理邏輯 是根據我自己的項目中需求定的 在這裡實現你需要處理的代碼

- (void)push:(NSDictionary *)params{
 
 STPushModel *model = [ NSKeyedUnarchiver unarchiveObjectWithFile:KRAPI_PUSH_DATA];
 
 //如果是h5
 if ([model.urlType isEqualToString:@"h5"]) {
 
 BOOL isStore = [[AnalysisUrl sharedInstance] analysisWebUrl:model.url];
 BOOL isGoods = [[AnalysisUrl sharedInstance] analysisGoodsIdWebUrl:model.url];
 BOOL isRedBag =[[AnalysisUrl sharedInstance] analyredBagWebUrl:model.url];
 BOOL istrace =[[AnalysisUrl sharedInstance] analytraceWebUr:model.url];
 BOOL islog =[[AnalysisUrl sharedInstance] analylogWebUrl:model.url];
 if (isStore || isGoods) {
  [[WYPageManager sharedInstance] pushViewControllerWithUrlString:model.url currentUrlString:TRAKER_URL_INDEX];
  
 }else if (isRedBag)
 {
  RedBageViewController * regBag =[[RedBageViewController alloc]init];
  NSArray *array = [model.url componentsSeparatedByString:@"="];
  NSString * string = [array lastObject];
  regBag.messageID = string;
  regBag.redType = @"coupon";
  UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
  UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
  // 跳轉到對應的控制器
  regBag.hidesBottomBarWhenPushed = YES;
  [pushClassStance pushViewController:regBag animated:YES];
  return;
 }else if (istrace)
 {
  RedBageViewController * regBag =[[RedBageViewController alloc]init];
  NSString * string = [StrUtils getIdFromURLString:model.url interceptString:@"/trace/"];
  regBag.messageID = string;
  regBag.redType = @"trace";
  UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
  UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
  // 跳轉到對應的控制器
  regBag.hidesBottomBarWhenPushed = YES;
  [pushClassStance pushViewController:regBag animated:YES];
  return;
 }else if (islog)
 {
  RedBageViewController * regBag =[[RedBageViewController alloc]init];
  NSString * string = [StrUtils getIdFromURLString:model.url interceptString:@"/log/"];
  regBag.messageID = string;
  regBag.redType = @"log";
  UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
  UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
  // 跳轉到對應的控制器
  regBag.hidesBottomBarWhenPushed = YES;
  [pushClassStance pushViewController:regBag animated:YES];
  return;
 }
 else{
  if (![model.url isEqualToString:@""]) {
  UIStoryboard *setStoryboard = [UIStoryboard storyboardWithName:@"UserCenter" bundle:nil];
  TotalWebViewController *setVC = [setStoryboard instantiateViewControllerWithIdentifier:@"TotalWebViewController"];
  setVC.shopUrl = model.url;
  setVC.shopTitle = [model.title isEqualToString:@""] ? @"121店" : model.title;
  UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
  UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
  setVC.hidesBottomBarWhenPushed = YES;
  [pushClassStance pushViewController:setVC animated:YES];
  }
 }
 }else if ([model.urlType isEqualToString:@"native"]){
  
  if ([model.url isEqualToString:@"1"]) {
  //一元體驗購 已經刪除
  
  }else if ([model.url isEqualToString:@"2"]){
  if (([[STCommonInfo getAuthType] intValue] != 1)) {
   [self createGroundGlass];
  }else{
   STProFitViewController *vc = [[STProFitViewController alloc] init];
   UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
   UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
   vc.hidesBottomBarWhenPushed = YES;
   [pushClassStance pushViewController:vc animated:YES];
  }
  }else if ([model.url isEqualToString:@"3"]){
  if (([[STCommonInfo getAuthType] intValue] != 1)) {
   [self createGroundGlass];
  }else{
   
   MessageMainVC *messageVC = [[MessageMainVC alloc] init];
   messageVC.hidesBottomBarWhenPushed = YES;
   UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
   UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
   [pushClassStance pushViewController:messageVC animated:YES];
  }
  }else if ([model.url hasPrefix:@"http://"]&&([model.url rangeOfString:@"client"].location!=NSNotFound)){ //跳轉到客服接 界面
  
  NSString *orgIdString =[[AnalysisUrl sharedInstance] extractOrgId:model.url];
  NSString *siteIdString = [[AnalysisUrl sharedInstance] extractOrgIdStoreId:model.url];
  [[WYPageManager sharedInstance] pushViewController:@"TLChatViewController" withParam:
   @{
   @"title_nameString":@"官方客服",
   @"orgIdString":orgIdString,
   @"siteIdString":siteIdString,
   @"currentURL":model.url
   } animated:YES];
  
  }
 }
} 

然後再AppDelegate 實現以下方法

/** 自定義:APP被“推送”啟動時處理推送消息處理(APP 未啟動--》啟動)*/- (void)receiveNotificationByLaunchingOptions:(NSDictionary *)launchOptions {
 if (!launchOptions)
 return;
 /*
 通過“遠程推送”啟動APP
 UIApplicationLaunchOptionsRemoteNotificationKey 遠程推送Key
 */
 NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
 if (userInfo) {
 NSLog(@"\n>>>[Launching RemoteNotification]:%@", userInfo);
 }
}

#pragma mark - 用戶通知(推送)回調 _IOS 8.0以上使用

/** 已登記用戶通知 */
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
 // 注冊遠程通知(推送)
 [application registerForRemoteNotifications];
}

#pragma mark - 遠程通知(推送)回調

/** 遠程通知注冊成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
 NSString *myToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
 myToken = [myToken stringByReplacingOccurrencesOfString:@" " withString:@""];
 NSUserDefaults *kr = [NSUserDefaults standardUserDefaults];
 [kr setValue:myToken forKey:@"deviceToken"];
 [kr synchronize];
 [GeTuiSdk registerDeviceToken:myToken];
 [[PostDeviceToken sharedInstance] postUpDeviceToken];
 NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", myToken);
}

/** 遠程通知注冊失敗委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
 [GeTuiSdk registerDeviceToken:@""];
 NSLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}


#pragma mark - APP運行中接收到通知(推送)處理
/** APP已經接收到“遠程”通知(推送) - 透傳推送消息 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
 // 處理APN
 NSLog(@"\n>>>[Receive RemoteNotification - Background Fetch]:%@\n\n", userInfo);
 completionHandler(UIBackgroundFetchResultNewData);
 
 NSString *payLoadString = [[MyPrevent sharedInstance] dictionary:userInfo objectForKey:@"payload"];
 [[SpotPunch sharedInstance] spotPunch:@"999.999.1" pointTwo:@"21" info:payLoadString];
 // NSUserDefaults *kr = [NSUserDefaults standardUserDefaults];
 if (!([[STCommonInfo getAuthType] intValue] != 1)) {
 NSData *jsonData = [payLoadString dataUsingEncoding:NSUTF8StringEncoding];
 NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData
        options:NSJSONReadingMutableContainers
         error:nil];
 
 STPushModel *model = [STPushModel modelObjectWithDict:jsonDic];
 [NSKeyedArchiver archiveRootObject:model toFile:KRAPI_PUSH_DATA];
//如果應用程序在前台 就顯示客服提示框
 if (application.applicationState == UIApplicationStateActive) {
  self.topView.model = model;
  [self displayPushView]; //此方法 的實現 在上一步中 就是展示提示框出來
 }

 
 }
} 

然後這些工作做好了之後 就是你需要在個推的後台 配置推送證書  這個配置的步驟 大家可以到個推官網去參考文檔 配置  

這裡我假設 你已經配置到證書了  經過上面的步驟 我們的遠程推送通知的方法 基本完成 現在我們運行 測試下 你會發現即使在前台 有新消息推送的時候 頂部也會彈出和系統一樣的提示框 點擊 跳轉到對應的頁面的方法邏輯根據你的需要 去做跳轉處理 

測試效果如下:

用戶在後台 收到的消息提示如下:

用戶在前台 收到的消息提示如下:


本文已被整理到了《iOS推送教程》,歡迎大家學習閱讀。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved