76 lines
2.1 KiB
TypeScript
76 lines
2.1 KiB
TypeScript
type AlbumAuthState = 'unknown' | 'granted' | 'denied';
|
|
|
|
const ALBUM_SCOPE = 'scope.writePhotosAlbum';
|
|
|
|
Page({
|
|
data: {
|
|
albumAuthState: 'unknown' as AlbumAuthState,
|
|
},
|
|
|
|
onLoad() {
|
|
this.refreshAlbumAuthState();
|
|
},
|
|
|
|
onShow() {
|
|
this.refreshAlbumAuthState();
|
|
},
|
|
|
|
refreshAlbumAuthState() {
|
|
wx.getSetting({
|
|
success: (res) => {
|
|
const auth = res.authSetting?.[ALBUM_SCOPE];
|
|
let state: AlbumAuthState = 'unknown';
|
|
if (auth === true) {
|
|
state = 'granted';
|
|
} else if (auth === false) {
|
|
state = 'denied';
|
|
}
|
|
this.setData({ albumAuthState: state });
|
|
},
|
|
fail: () => {
|
|
this.setData({ albumAuthState: 'unknown' });
|
|
},
|
|
});
|
|
},
|
|
|
|
onHandleAlbumPerm() {
|
|
const { albumAuthState } = this.data;
|
|
|
|
// 已被拒绝过:只能去系统设置打开
|
|
if (albumAuthState === 'denied') {
|
|
wx.openSetting({
|
|
success: (res) => {
|
|
const granted = !!res.authSetting?.[ALBUM_SCOPE];
|
|
this.setData({
|
|
albumAuthState: granted ? 'granted' : 'denied',
|
|
});
|
|
if (granted) {
|
|
wx.showToast({
|
|
title: '已开启相册权限',
|
|
icon: 'success',
|
|
duration: 1500,
|
|
});
|
|
}
|
|
},
|
|
});
|
|
return;
|
|
}
|
|
|
|
// 未授权过:直接发起授权请求
|
|
wx.authorize({
|
|
scope: ALBUM_SCOPE,
|
|
success: () => {
|
|
this.setData({ albumAuthState: 'granted' });
|
|
wx.showToast({
|
|
title: '已开启相册权限',
|
|
icon: 'success',
|
|
duration: 1500,
|
|
});
|
|
},
|
|
fail: () => {
|
|
this.setData({ albumAuthState: 'denied' });
|
|
},
|
|
});
|
|
},
|
|
});
|