8.7 发布—WinterCG 兼容性第一部分
了解更多

在 GitHub 上查看

@nativescript/contacts

一个允许您访问 iOS 和 Android 上的联系人目录的插件。您可以选择联系人、更新联系人、删除联系人或添加新联系人。

内容

安装

运行以下命令安装插件

cli
npm install @nativescript/contacts

权限要求

为了使应用程序能够访问用户的联系人应用程序,用户必须授予它访问权限。在请求权限之前,请确保满足以下要求。

iOS 权限要求

  • 为了说明您的应用程序为什么需要访问用户的联系人,请将NSContactsUsageDescription键添加到App_Resources/iOS/Info.plist文件,并将您的说明作为其值。
xml
<key>NSContactsUsageDescription</key>
<string>Kindly provide permission to access contacts on your device.</string>
xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>com.apple.developer.contacts.notes</key>
    <true/>
  </dict>
</plist>

Android 权限要求

对于 API 级别23+,请通过在AndroidManifest.xml中列出以下权限来告知 Android 您的应用程序需要从用户那里获取哪些权限才能访问联系人。

xml
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.GLOBAL_SEARCH" />

使用 @nativescript/contacts

在您指示了应用程序需要从用户那里获取哪些权限后,您可以通过调用nativescript-permissions插件的requestPermissions()方法来向用户请求权限。

ts
import { Contact } from '@nativescript/contacts'
import { requestPermissions } from 'nativescript-permissions'

const contact = new Contact()
// build a new contact...

requestPermissions(
  [
    android.Manifest.permission.GET_ACCOUNTS,
    android.Manifest.permission.READ_CONTACTS,
    android.Manifest.permission.WRITE_CONTACTS,
    android.Manifest.permission.GLOBAL_SEARCH,
  ],
  "I need these permissions because I'm cool"
).then(() => {
  contact.save()
})

获取联系人

要获取选定的联系人,请调用Contacts类的getContact()方法。

ts
import { Contact } from '@nativescript/contacts'

Contacts.getContact().then(function (args) {
  /// Returns args:
  /// args.data: Generic cross platform JSON object
  /// args.reponse: "selected" or "cancelled" depending on wheter the user selected a contact.

  if (args.response === 'selected') {
    const contact = args.data //See data structure below

    console.log(contact.name.given + ' ' + contact.name.family)

    contact.phoneNumbers.forEach(function (phone) {
      console.log(phone.value)
    })

    //lets say you want to get the addresses
    contact.postalAddresses.forEach(function (address) {
      console.log(address.location.street)
    })
  }
})

创建新联系人

要创建新联系人,首先实例化Contact类,设置联系人的各种数据,然后要保存联系人,请调用实例上的save()方法。

ts
import { Contact, KnownLabel } from '@nativescript/contacts'
import { ImageSource } from '@nativescript/core'

const newContact = new Contact()
newContact.name.given = 'John'
newContact.name.family = 'Doe'
newContact.phoneNumbers.push({
  label: KnownLabel.HOME,
  value: '123457890',
}) // See below for known labels
newContact.phoneNumbers.push({ label: 'My Custom Label', value: '11235813' })
newContact.photo = ImageSource.fromFileOrResource('~/photo.png')
newContact.save()

更新联系人

要更新现有联系人,请使用getContact()方法获取它,对其进行编辑,然后调用save()方法来更新它。

ts
import { Application, ImageSource } from '@nativescript/core'
import { Contacts } from '@nativescript/contacts'

Contacts.getContact().then(function (args) {
  if (args.response === 'selected') {
    const contact = args.data
    contact.name.given = 'Jane'
    contact.name.family = 'Doe'

    ImageSource.fromUrl(
      'http://www.google.com/images/errors/logo_sm_2.png'
    ).then(function (src) {
      contact.photo = src
      contact.save()
    })
  }
})

删除联系人

要删除联系人,请使用getContact()方法获取它,然后调用它上的delete()方法。

ts
import { Contacts } from '@nativescript/contacts'

Contacts.getContact().then(function (args) {
  /// args.data: Generic cross platform JSON object
  /// args.reponse: "selected" or "cancelled" depending on wheter the user selected a contact.

  if (args.response === 'selected') {
    const contact = args.data //See data structure below
    contact.delete()
  }
})

检查联系人是否已统一/链接(iOS 特定)

要检查联系人是否已统一,请调用联系人的isUnified()

ts
import { Contacts } from '@nativescript/contacts'

Contacts.getContact().then(function (args) {
  /// args.data: Generic cross platform JSON object
  /// args.reponse: "selected" or "cancelled" depending on whether the user selected a contact.

  if (args.response === 'selected') {
    const contact = args.data //See data structure below
    console.log(
      contact.isUnified() ? 'Contact IS unified' : 'Contact is NOT unified'
    )
  }
})

按姓名获取联系人

要查找与特定姓名匹配的所有联系人,请使用getContactsByName()方法。返回一个联系人数据的数组。

ts
import { Contacts } from '@nativescript/contacts'

/*
  contactFields contains the fields to retrieve from native backend to reduce processing time
  const contactFields = ['name','organization','nickname','notes','photo','urls','phoneNumbers','emailAddresses','postalAddresses']
*/
const contactFields = ['name', 'phoneNumbers']

Contacts.getContactsByName('Hicks', contactFields).then(
  function (args) {
    console.log('getContactsByName Complete')
    /// Returns args:
    /// args.data: Generic cross platform JSON object, null if no contacts were found.
    /// args.reponse: "fetch"
  },
  function (err) {
    console.log('Error: ' + err)
  }
)

获取所有联系人

要读取所有联系人,请使用getAllContacts()方法。它返回一个包含Contact实例数组的 Promise。

ts
import { Contacts } from '@nativescript/contacts'

/*
  Optional: contactFields contains the fields to retrieve from native backend to reduce processing time
  const contactFields = ['name','organization','nickname','notes','photo','urls','phoneNumbers','emailAddresses','postalAddresses']

  If not supplied, all available contactFields will be returned.
*/
const contactFields = ['name', 'phoneNumbers']

Contacts.getAllContacts(contactFields).then(
  function (args) {
    console.log('getAllContacts Complete')
    /// Returns args:
    /// args.data: Generic cross platform JSON object, null if no contacts were found.
    /// args.reponse: "fetch"
  },
  function (err) {
    console.log('Error: ' + err)
  }
)

按 ID 获取联系人

要查找具有特定标识符的联系人,请使用getContactById()方法。该方法返回一个iOS 特定GetFetchResult对象。

ts
import { Contacts } from '@nativescript/contacts'

const contactId = '[Contact Identifier]' // Assumes this is a valid contact identifier (Contact.id)

Contacts.getContactById(contactId).then(
  function (args) {
    console.log('getContactById Complete')
    /// Returns args:
    /// args.data: Generic cross platform JSON object, null if no contacts were found.
    /// args.reponse: "fetch"
  },
  function (err) {
    console.log('Error: ' + err)
  }
)

获取联系人组

要获取联系人组,请使用getGroups()方法。要获取具有特定名称的联系人组,请调用该方法并将其传递给组的名称。

ts
import { Contacts } from '@nativescript/contacts'

Contacts.getGroups('Test Group') //[name] optional. If defined will look for group with the specified name, otherwise will return all groups.
  .then(
    function (args) {
      console.log('getGroups Complete')
      /// Returns args:
      /// args.data: Generic cross platform JSON object, null if no groups were found.
      /// args.reponse: "fetch"

      if (args.data === null) {
        console.log('No Groups Found!')
      } else {
        console.log('Group(s) Found!')
      }
    },
    function (err) {
      console.log('Error: ' + err)
    }
  )

创建新联系人组

要创建新联系人组,请创建Group类的实例,设置组的名称并调用实例上的save()方法来保存它。

ts
import { Group } from '@nativescript/contacts/models'

const groupModel = new Group()
groupModel.name = 'Test Group'
//Save Argument (boolean)
//iOS: [false=> Use Local Container, true=> Use Default Container]
//Android: will always be true, setting this value will not affect android.
groupModel.save(false)

删除联系人组

要删除联系人组,请调用getGroups()方法以首先获取目标组。然后调用该组的delete()方法将其删除。

ts
import { Contacts } from '@nativescript/contacts'

Contacts.getGroups('Test Group').then(
  function (args) {
    console.log('getGroups Complete')
    console.log(JSON.stringify(args))
    /// Returns args:
    /// args.data: Generic cross platform JSON object, null if no groups were found.
    /// args.reponse: "fetch"

    if (args.data !== null) {
      console.log('Group(s) Found!')
      args.data[0].delete() //Delete the first found group
    }
  },
  function (err) {
    console.log('Error: ' + err)
  }
)

将联系人添加到组

要将联系人添加到组,请获取对目标联系人 and 组的引用。接下来,在该组上调用addMember()方法,并将要添加的联系人的引用传递给它。

ts
import { Contacts } from '@nativescript/contacts'

Contacts.getContact().then(function (args) {
  /// args.reponse: "selected" or "cancelled" depending on whether the user selected a contact.

  if (args.response === 'selected') {
    const contact = args.data //See data structure below
    Contacts.getGroups('Test Group').then(
      function (a) {
        if (a.data !== null) {
          const group = a.data[0]
          group.addMember(contact)
        }
      },
      function (err) {
        console.log('Error: ' + err)
      }
    )
  }
})

从组中删除联系人

Group类实例上调用removeMember(),并将要删除的联系人传递给它。

ts
import { Contacts } from '@nativescript/contacts'

Contacts.getGroups('Test Group').then(
  function (args) {
    if (args.data !== null) {
      const group = args.data[0]

      Contacts.getContactsInGroup(group).then(
        function (a) {
          /// args.reponse: "fetch"
          console.log('getContactsInGroup complete')

          if (a.data !== null) {
            a.data.forEach(function (c, idx) {
              group.removeMember(c)
            })
          }
        },
        function (err) {
          console.log('Error: ' + err)
        }
      )
    }
  },
  function (err) {
    console.log('Error: ' + err)
  }
)

获取组中的所有联系人

要获取组中的所有联系人,请使用Contacts.getContactsInGroup()方法,并将组实例传递给它。

ts
import { Contacts } from '@nativescript/contacts'

Contacts.getGroups('Test Group') //[name] optional. If defined will look for group with the specified name, otherwise will return all groups.
  .then(
    function (args) {
      if (args.data !== null) {
        const group = args.data[0]

        Contacts.getContactsInGroup(group).then(
          function (a) {
            console.log('getContactsInGroup complete')
            /// Returns args:
            /// args.data: Generic cross platform JSON object, null if no groups were found.
            /// args.reponse: "fetch"
          },
          function (err) {
            console.log('Error: ' + err)
          }
        )
      }
    },
    function (err) {
      console.log('Error: ' + err)
    }
  )

联系人类

Contact 类具有以下结构

ts
{
    id : "",
    name : {
        given: "",
        middle: "",
        family: "",
        prefix: "",
        suffix: "",
        displayname: "",
        phonetic : {
            given: "",
            middle: "",
            family: ""
        }
    },
    nickname : "",
    organization : {
        name: "",
        jobTitle: "",
        department: "",

        // Android Specific properties
        symbol: "",
        phonetic: "",
        location: "",
        type: ""
    },
    notes : "",
    photo: null, // {N} ImageSource instance

    phoneNumbers : [],
    emailAddresses : [],
    postalAddresses : [],
    urls : []
}

电话号码/电子邮件地址结构

ts
{
    id: "",
    label: "",
    value: ""
}

URL 结构

ts
{
    label: "",
    value: ""
}

邮政地址结构

ts
{
    id: "",
    label: "",
    location: {
        street: "",
        city: "",
        state: "",
        postalCode: "",
        country: "",
        countryCode: ""
    }
}

已知标签(用于 URL、地址和电话)

该插件通过KnownLabel对象公开以下标签,用于联系人数据。

  • HOME iOS - 电话、电子邮件、邮政、URL Android - 电话、电子邮件、邮政、URL
  • WORK iOS - 电话、电子邮件、邮政、URL Android - 电话、电子邮件、邮政、URL
  • OTHER iOS - 电话、电子邮件、邮政、URL Android - 电话、电子邮件、邮政、URL
  • FAX_HOME iOS - 电话 Android - 电话
  • FAX_WORK iOS - 电话 Android - 电话
  • PAGER iOS - 电话 Android - 电话
  • MAIN iOS - 电话 Android - 电话
  • HOMEPAGE iOS - URL Android - URL
  • CALLBACK Android - 电话
  • CAR Android - 电话
  • COMPANY_MAIN Android - 电话
  • ISDN Android - 电话
  • OTHER_FAX Android - 电话
  • RADIO Android - 电话
  • TELEX Android - 电话
  • TTY_TDD Android - 电话
  • WORK_MOBILE Android - 电话
  • WORK_PAGER Android - 电话
  • ASSISTANT Android - 电话
  • MMS Android - 电话
  • FTP Android - URL
  • PROFILE Android - URL
  • BLOG Android - URL

这些是系统标签,但您也可以使用任何所需的自定义标签。

组对象结构

ts
{
	id: string,
	name: string,
	addMember: (constact: Contact) => void
	removeMember: (constact: Contact) => void

}

GetFetchResult 对象结构

Contacts类的getContactById()方法返回的对象。

ts
{
  data: Contact[];
  response: string;
}

iOS 联系人对象

查看有关可用属性的 Apple 文档:https://developer.apple.com/library/mac/documentation/Contacts/Reference/CNContact_Class/index.html#//apple_ref/occ/cl/CNContact

注意

该插件使用 Contact 框架,仅在 iOS 9.0 及更高版本上受支持!

致谢

感谢原始作者 Ryan Lebel 创建了 nativescript-contacts

许可证

Apache 许可证 2.0 版

上一个
相机