1. 程式人生 > 其它 >uniapp小程式獲取使用者頭像和資訊

uniapp小程式獲取使用者頭像和資訊

1,獲取使用者資訊(頁面彈出授權框,獲取頭像和名稱等等) 使用api:getUserProfile()

示例:

html:

  <image class="image" :src="info.avatarUrl"></image>
  <view>{{info.nickName}}</view>

<button @click="getUserProfile"> 獲取使用者資訊 </button>

 data: info:{}

 methods

getUserProfile() {
	let that = this
	uni.getUserProfile({
		desc: "用於完善使用者資訊",
		success: (res1) => {
			that.info = res1.userInfo;
			console.log(res1)
			uni.showToast({
				icon:"none",
				title:'獲取成功'
			})
		},
		fail: (err) => {
			console.log(err)
			uni.showToast({
				icon:"none",
				title:'使用者拒絕獲取'
			})
		}	
	})
}

2,獲取地理位置 使用api: getLocation() ,獲取前需要檢查是否有授權獲取地理位置,如果沒有,先彈出授權框


示例:

html :
<button @click="isGetLocation">獲取地理位置</button>

<view>經度{{location[1]}}</view>
<view>緯度{{location[0]}}</view>


data location:[0,0] methods: // 獲取地理位置 isGetLocation(a = "scope.userLocation") { // 3. 檢查當前是否已經授權訪問scope屬性 var _this = this; uni.getSetting({ success(res) { if (!res.authSetting[a]) { //3.1 每次進入程式判斷當前是否獲得授權,如果沒有就去獲得授權,如果獲得授權,就直接獲取當前地理位置 _this.getAuthorizeInfo() //獲取授權 } else { _this.getLocationInfo() //獲取地理位置 console.log('取得授權,獲取位置和資訊') } } }); } getAuthorizeInfo() { //1. uniapp彈窗彈出獲取授權(地理,個人微信資訊等授權資訊)彈窗 var _this = this; uni.authorize({ scope: "scope.userLocation", success(e) { //1.1 允許授權 _this.getLocationInfo(); console.log("允許授權") }, fail() { //1.2 拒絕授權 console.log("你拒絕了授權,無法獲得周邊資訊") } }) }, getLocationInfo() { //2. 獲取地理位置 let that = this uni.getLocation({ type: 'wgs84', success(res) { let latitude, longitude; latitude = res.latitude.toString(); longitude = res.longitude.toString(); that.location = [latitude,longitude] } }) },

  ps:獲取位置需要 在manifest.json 的原始碼試圖中設定

"mp-weixin": {
		"appid": "wxb*******04af0b",
		"setting": {
			"urlCheck": false
		},
		"usingComponents": true,
		"permission": {
			"scope.userLocation": {
				"desc": "你的位置資訊將用於小程式位置介面的效果展示"
			}
		}
	}

  此使用者較懶,就寫到這裡了。