jpush.js
2.34 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { updateJpush } from '@/api/jpush'
import { platform } from '@/config/index'
export function useJPush() {
const jpushModule = uni.requireNativePlugin('JG-JPush')
const isRegistrationPushed = ref(false)
const registerID = ref(null)
const startUploadJpush = () => {
if (registerID.value) {
updateJpush({ registrationId: registerID.value, platform: platform() })
.then(() => {
console.warn('推送注册成功')
// tip.showToast(`推送注册成功${registerID.value}`)
isRegistrationPushed.value = true
})
.catch((err) => {
console.error('推送注册失败', err)
// tip.showToast(`推送注册失败:${err}`)
})
}
}
const registerPush = () => {
if (isRegistrationPushed.value) {
return
}
if (registerID.value) {
// 调用接口后台关联
startUploadJpush()
return
}
try {
jpushModule.getRegistrationID((result) => {
registerID.value = result.registerID
console.warn('推送注册结果:', result)
// tip.showToast(`推送注册结果:${registerID.value}`)
startUploadJpush()
})
}
catch (err) {
console.error('推送注册异常', err)
// tip.showToast(`推送注册异常 :${err}`)
}
// 可能registerPush异常失败,再重试一次
setTimeout(() => {
registerPush()
}, 5000)
}
const checkNotificationAuthorization = () => {
jpushModule.isNotificationEnabled((result) => {
const code = result.code
if (code !== 1) {
uni.showToast({
icon: 'none',
title: '还没有通知权限,请在系统设置中开启',
duration: 3000,
})
jpushModule.openSettingsForNotification((result) => {
console.warn('打开通知设置结果:', result)
if (result.code === 1) {
// 用户已授权
registerPush()
}
else {
// 用户未授权
uni.showToast({
icon: 'none',
title: '您还没有打开通知权限',
duration: 3000,
})
}
})
}
})
jpushModule.requestPermission()
}
return {
jpushModule,
isRegistrationPushed,
registerID,
registerPush,
checkNotificationAuthorization,
}
}