UniApp怎么获取手机通讯录

UniApp中可以使用plus对象中的contacts获取手机通讯录。

话不多说,直接给出代码。

视图层:

<button type="primary" @tap="getContacts" style="padding: 20rpx 0;">获取联系人</button>
<block  v-for="(item,index) in contact_list" :key="index">
    <view>{{item.displayName}}:</view>
    <block v-for="(subitem,idx) in item.phoneNumbers" :key="idx">
        <view>{{subitem.value}} </view>
    </block>
</block>

全局变量中加了一个 allow_contacts表示是否允许获取通讯录,contact_list表示联系人列表。

methods中添加一个方法:

getContacts: function() {
                var that = this
                // 获取通讯录对象
                plus.contacts.getAddressBook( plus.contacts.ADDRESSBOOK_PHONE, function( addressbook ) {
                    uni.showToast({
                        title: '获取通讯录对象成功',
                        duration: 2000
                    })
                    console.log('获取通讯录对象成功')
                    console.log(addressbook)
                    // 查找联系人
                    addressbook.find(["displayName","phoneNumbers"],function(contacts){
                        uni.showToast({
                            title: '获取联系人成功',
                            duration: 2000
                        })
                        console.log('获取联系人成功')
                        console.log(JSON.stringify(contacts))
                        that.allow_contacts = true;
                        that.contact_list = contacts;
                    }, function () {
                        uni.showToast({
                            title: '获取联系人失败',
                            duration: 2000
                        })
                    },{multiple:true});
                }, function ( e ) {
                    uni.showToast({
                        title: '获取通讯录对象失败:' + e.message,
                        duration: 2000
                    })
                });
            }

真机运行,点击获取联系人按钮,会弹出提示框是否允许获取手机通讯录,允许后方可拿到权限。

获取到的通讯录是JSON格式的,示例如下:

[{
    "id": 1,
    "rawId": null,
    "target": 0,
    "displayName": "测试1",
    "name": null,
    "nickname": null,
    "phoneNumbers": [{
        "id": "1",
        "pref": false,
        "value": "15512345678",
        "type": "mobile"
    }],
    "emails": null,
    "addresses": null,
    "ims": null,
    "organizations": null,
    "birthday": null,
    "note": null,
    "photos": null,
    "categories": null,
    "urls": null
}, {
    "id": 2,
    "rawId": null,
    "target": 0,
    "displayName": "测试2",
    "name": null,
    "nickname": null,
    "phoneNumbers": [{
        "id": "3",
        "pref": false,
        "value": "16612345678",
        "type": "mobile"
    }],
    "emails": null,
    "addresses": null,
    "ims": null,
    "organizations": null,
    "birthday": null,
    "note": null,
    "photos": null,
    "categories": null,
    "urls": null
}]

Leave a Comment

豫ICP备19001387号-1