Swift Notes - 阿里云推送SDK配置

新项目里的消息推送功能,公司技术部开会讨论后决定让 极光,百度,aws都歇菜,取而代之的是尝试 使用阿里云推送SDK。所以今天就简单记录下调试过程。
新任务获得:使用阿里云推送SDK实现消息推送功能~

嗯常规套路先看官方文档 正面上我 。 嗯,很详细,很耐斯,很桥豆麻袋?库文件是OC写的???

坑爹啊,哥的项目都是swift写的啊。呃。。。。。。。。。好吧,也许加一个桥接就可以了。任务变更:桥接阿里云推送SDK(OC版)到Swift工程里,而后实现消息推送功能~

Ready to work

所谓工欲善其事,必先利其器。而且消息推送功能本身就是配置打过逻辑代码的功能,所以我们先要把准备工作做好。


Step.1 - 准备certificate文件

由于消息推送功能的实现,涉及到Apple的官方资源(感兴趣的同志们可以自行去谷歌APNS),所以需要准备特别的证书文件:development certificate x1distribution certificate x1。然后这两个文件具体怎么获得呢,请 正面上我

Step.2 - 获得AppKey, AppSecret

这个appkey 和appsecret 是做啥的呢,嗯简单说就是这两个字串是阿里云用来标记你的app的,万一推错了就不好嘛,稍后我们会用点。那么问题又来了这两个字串那里搞呢?

支线任务获得:寻找NPC -公司的推送服务后台开发人员,交付 development certificate x1distribution certificate x1后,获得 AppKey x1, AppSecret x1.

Step.3 - 配置App

配置App这个就简单了,打开你的项目代码。先把开发团队调到你们的公司

然后打开 Post Notifications 功能

Step.4 - 引入阿里云SDK

下载好压缩包打开,获得四个库文件,然后全部拖到你的项目工程里去。再然后么把 build settings 里的 Enable Bitcode 给关了。最后再转到 Build Phases 里面的 Link Binary With libraries, 加入四个依赖的系统库: libz.tbd,libresolv.tbd,CoreTelephony.framework,SystemConfiguration.framework 。


好啦,到此基本上所有的准备工作都做好了。接下来我们就可以开始写代码了。P.S. 其实上面的都可以在阿里云文档里看到,哥只是拿来凑字的~~

Core Work

Step.1 - 桥接

先建立一个 Header File,命名为 YourProjectName-Bridging-Header.h 。

然后呢去到 Build Setting里,找到 Objective-C Bridging Header 填入刚才的文件名

最后在刚才的桥接文件里,引入阿里云推送的库#import <CloudPushSDK/CloudPushSDK.h>, 这样就可以用SDK里的方法了。

Step.2 - 配置推送

先在APP启动时调用配置方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let aliyunpush_AppKey = "23448723"
let aliyunpush_AppSecret = "8085ed1d1fc7739e9e058d2ad7fbb881"
let aliyunpush_messageNoti = "CCPDidReceiveMessageNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// Override point for customization after application launch.

//init aliyun Push SDK
initCloudPush(application: application)

//feedback to aliyun server
CloudPushSDK.handleLaunching(launchOptions)

return true

}

配置推送注册方法

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
func initCloudPush(application : UIApplication) {

CloudPushSDK.asyncInit(aliyunpush_AppKey, appSecret: aliyunpush_AppSecret) { (res) in
if (res?.success)! {
print("Push SDK init success, deviceID: \(CloudPushSDK.getDeviceId())")
}else{
print("Push SDK init failed, error: \(res?.error?.localizedDescription)")
}

}

//register APNS to fetch deviceToken
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)

if #available(iOS 8.0, *) {

//iOS 8 notifications

application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}else{

//iOS < 8 Notifications
UIApplication.shared.registerUserNotificationSettings(settings)
}

registerMessageReceive()
}

//APNS register success
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
CloudPushSDK.registerDevice(deviceToken as Data!) { (res) in
if (res?.success)!{
print("Register deviceToken success")
}else{
print("Register deviceToken failed, error:\(res?.error?.localizedDescription)")
}

}
}

//APNS register failed
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("did fail to register for remote notification with error : \(error.localizedDescription)")
}

推送处理方法

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
//Observer remote Notifications - Background Mode & Inactive Mode
func registerMessageReceive() {
NotificationCenter.default.addObserver(self, selector: Selector(("onMessageReceived")), name: NSNotification.Name(rawValue: aliyunpush_messageNoti), object: nil)
}

//Handle remote Notifications - Background Mode & Inactive Mode
func onMessageReceived(notification: NSNotification) {
let message : CCPSysMessage = notification.object as! CCPSysMessage
let title : NSString = NSString(data: message.title, encoding: String.Encoding.utf8.rawValue)!
let body : NSString = NSString(data: message.title, encoding: String.Encoding.utf8.rawValue)!
print("Received Message title: \(title), content:\(body)")
}

//Observer & Handle remote Notifications - Foreground Mode
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
print("REceive one notification.")

//retreive APNS content

let aps_dic : NSDictionary = userInfo["aps"] as! NSDictionary

//content
let content = aps_dic.value(forKey: "alert")

//barge num
let badge = (aps_dic.value(forKey: "badge") as AnyObject).integerValue

//sound
let sound = aps_dic.value(forKey: "sound")

//extras
let extras = aps_dic.value(forKey: "Extras")

print("content: \(content)\n, badge:\(badge)\n, sound :\(sound)\n, Extras: \(extras)")

application.applicationIconBadgeNumber = 0

CloudPushSDK.handleReceiveRemoteNotification(userInfo)
}

最后运行程序,看到如下结果就可以去交任务啦。

完结,鼓掌,撒花~~


This artical is avaliable under WTFPL-V2. Generally, everyone is permitted to copy and do what the fuck you want to.
P.S. Even so said, your kindly declaration that inspired from this site - Chen’s Alchemy would be appreciated

本文链接:http://yoursite.com/2016/09/01/swift-APNS-aliyun/

Donate comment here