Swift项目集成有盟推送

1、去自己的appstore开发者平台创建推送证书,包括develop(开发)和dis(生产) 两种环境的推送证书,下载下来,并且导出.p12文件

2、友盟官网创建你的项目, 地址:https://message.umeng.com/list/apps

创建完项目会得到一个 Appkey 和 App Master Secret

3、选中友盟的应用信息模块,把第一步下载的两种证书导出的p12文件上传到应用信息的APNs证书那里

4、打开项目的通知权限

AppDelegate 部分:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
       

        let settings = UIUserNotificationSettings(types: [.badge], categories: nil)
        application.registerUserNotificationSettings(settings)

       
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
        } else {
            // Fallback on earlier versions
        }
        
        UMessage.openDebugMode(true)
        
        if launchOptions != nil {
            VTUmengConfig.configUmeng(launchOptions!)
        }else {
            VTUmengConfig.configUmeng([AnyHashable : Any]())
        }

        return true
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
       
        return false
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        // 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.
        AppEvents.activateApp()
    }


    func applicationWillResignActive(_ application: UIApplication) {
        // 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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // 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.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        application.registerForRemoteNotifications()
    }

    // registerForRemoteNotifications 成功的回调,获取到token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        UMessage.registerDeviceToken(deviceToken)
        

//这个方法iOS13做了更新
        let deviceToken = VTUmengConfig.getDeviceToken(deviceToken)
        


// 把你的token上传到你的服务器
        ErWoPushManager.instance()?.updateTokenToServer()

    }
    
    func handlenotificationMessage(_ dict: [AnyHashable : Any]?) {
        if(dict != nil) {
            let type = validInt(dict?[APS_KEY_TYPE])
            let uid = validInt64(dict?[APS_KEY_UID])
            let name = validString(dict?["name"])
            let headImageUrl = validString(dict?["headImageUrl"])
            switch(type) {
            case 1001: //上麦
                VTPubJump.jump(toLiveRoom: validInt64(dict?["roomId"]))
            case 1000: /** IM信息内容类型: 运营push */
                let jumpType = validInt(dict?["jumpType"])
                if (jumpType == 2) {
                     VTPubJump.jump(toLiveRoom: validInt64(dict?["roomId"]))
                }else if(jumpType == 3) {
                    let dataObj = VTWebViewData()
                    dataObj.url = validString(dict?["url"])
                    dataObj.autoLogin = true
                    dataObj.backView = false
                    dataObj.hideBottomBar = true
                    dataObj.backTitle = ""
                    dataObj.cookieAutoDelete = false
                    dataObj.detectorTypes = .all
                    dataObj.shareAvailabled = false
                    dataObj.webGLAvailabled = true
                    VTPubJump.jumpToWap(with: dataObj, isPush: true, controller: getCurrentVCBS())
                }else {
                    
                }
            case 7:
                TaskUtil.delayExecuting(2, block: {
                    VTPubJump.jumpToPrivateChat(withUid: uid, name: name, headImageURL: headImageUrl, controller: getCurrentVCBS())
                })
            default:
                break
            }
        }
    }
    
    /**
     UNUserNotificationCenterDelegate
     */
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        UMessage.setAutoAlert(false)
        if validInt(UIDevice.current.systemVersion) < 10 {
            UMessage.didReceiveRemoteNotification(userInfo)
            self.handlenotificationMessage(userInfo)
            completionHandler(.newData)
        }
    }
    
    @available(iOS 10.0, *)
    //iOS10新增:处理前台收到通知的代理方法
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            let info = userInfo as NSDictionary
            print(info)
            //应用处于前台时的远程推送接受
            //关闭U-Push自带的弹出框
            UMessage.setAutoAlert(false)
            UMessage.didReceiveRemoteNotification(userInfo)
        }else{
            //应用处于前台时的本地推送接受
        }
        completionHandler([.alert,.sound,.badge])
    }
    
    @available(iOS 10.0, *)
    //iOS10新增:处理后台点击通知的代理方法
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            let info = userInfo as NSDictionary
            print(info)
            //应用处于后台时的远程推送接受
            UMessage.didReceiveRemoteNotification(userInfo)
            handlenotificationMessage(userInfo)
        }else{
            //应用处于后台时的本地推送接受
            handlenotificationMessage(userInfo)
        }
    }
}

友盟的封装部分:

VTUmengConfig.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface VTUmengConfig : NSObject

+ (void)configUmeng:(NSDictionary *)dict;

+ (NSString *)getDeviceToken:(NSData *)data;

@end

NS_ASSUME_NONNULL_END

VTUmengConfig.m

//
//  ErWoUmengConfig.m
//  erwo
//
//  Created by liurui on 2017/9/25.
//  Copyright © 2019 ERWO CO. All rights reserved.
//

#import "VTUmengConfig.h"
#import "UXAppInfoUtils.h"
#import <UMCommon/UMCommon.h>
#import <UMPush/UMessage.h>
//#import <UMCSecurityPlugins/SecurityEnvSDK.H>
#import "ErWoHttpConfigure.h"
#define kUMPush_APPKey              @"这里就是上面第一步友盟创建的项目生成的APP_KEY"  //友盟推送和统计    测试没有单独配置UMeng推送

//aps key定义
#define APS_KEY_APS                         @"aps"                      // aps
#define APS_KEY_ALERT                       @"alert"                    // alert,显示内容
#define APS_KEY_BADGE                       @"badge"                    // badge
#define APS_KEY_TYPE                        @"type"                     // type,通知类型
#define APS_KEY_SOUND                       @"sound"                    // sound,声音文件名称
#define APS_KEY_PHONE                       @"phone"                    // phone,用户电话号码
#define APS_KEY_UID                         @"uid"                      // 对应的uid
#define APS_KEY_ALERT                       @"alert"                    // alert
#define APS_KEY_SEQ                         @"seq"                      // seq,发送sipok需要用到
#define APS_KEY_BODY                        @"body"                     // alert,body显示内容
#define APS_KEY_CALLID                      @"callid"                   // 新版免费电话的callid
#define APS_KEY_MEDIA                       @"m"                        // 新版免费电话的Media
#define APS_KEY_SUBTYPE                     @"st"                       // 子类型
#define APS_KEY_URL                         @"u"                        // URL
#define APS_KEY_TITLE                       @"t"                        // 标题


@class AppDelegate;

@implementation VTUmengConfig
//查看umeng上报关键字: UMLOG: event
+ (void)configUmeng:(NSDictionary *)dict {

    [UMConfigure initWithAppkey:kUMPush_APPKey channel:[UXAppInfoUtils getInviteID]];

    if (HTTP_SERVER_ENVIRONMENTAL) {
        [UMConfigure setLogEnabled:NO];
    } else {
        [UMConfigure setLogEnabled:YES];
    }
    // Push组件基本功能配置
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择,可以选择一个或者多个。默认是三个全部打开,即:声音,弹窗,角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
    [UMessage registerForRemoteNotificationsWithLaunchOptions:dict Entity:entity     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
        }else{
        }
    }];

}

+(NSString *)getDeviceToken:(NSData *)data {
    const unsigned *tokenBytes = (const unsigned *)[data bytes];
    NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    NSLog(@"deviceToken:%@",hexToken);
    return hexToken;
}
@end
发布了79 篇原创文章 · 获赞 42 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/s12117719679/article/details/98616673