React Native之獲取通訊錄信息並實現類通訊錄列表(ios android)
一,需求分析
1,獲取通訊錄信息,篩選出通訊錄里有多少好友在使用某個應用。
2,獲取通訊錄信息,實現類通訊錄,可撥打電話 發短信等。
二,技術介紹與配置
2.1 技術介紹
1,react-native-contacts地址:https://www.npmjs.com/package/react-native-contacts
2,下載安裝:npm install react-native-contacts --save
3,自動鏈接:react-native link react-native-contacts
4,react-native-contacts API介紹:
-
- getAll(callback)——以對象數組的形式返回所有聯系人
- getAllWithoutPhotos——和getAll在安卓系統上是一樣的,但是在iOS系統上它不會返回聯系人照片的uri(因為創建這些圖片會帶來很大的開銷)
- getPhotoForId(contactId, callback)——返回聯系人照片的URI(或null)
- openContactForm (contact, callback)——在contactsUI中創建一個新的聯系人並顯示。添加一個聯系人到通訊錄。
- updateContact (contact, callback)——其中contact是一個具有有效recordID的對象
- deleteContact (contact,callback)——其中contact是一個具有有效recordID的對象
- getContactsMatchingString (string, callback)—其中string是匹配名稱(第一個、中間、家族)的任何字符串
- checkPermission(callback)——只檢查訪問聯系人ios的權限(僅限ios)
- requestPermission(callback)——請求僅訪問ios聯系人的權限(僅限ios)
5,react-native SectionLis列表 類似FlatList的使用
1 <SectionList 2 {...this.props} 3 style={this.props.SectionListStyle} 4 ref={s => this.sectionList = s} 5 keyExtractor={this._keyExtractor} 6 sections={delData} 7 renderSectionHeader={this._renderSectionHeader} 8 renderItem={this._renderItem} 9 getItemLayout={(data, index) => ({ length: this.props.sectionHeight, offset: 50 * index, index })} 10 />
2.2 Android配置
第一步
在android/settings.gradle文件中添加如下代碼:
1 include ':react-native-contacts' 2 project(':react-native-contacts').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-contacts/android')
第二步
在android/app/build.gradle文件中的dependencies標簽中添加模塊依賴:
1 ... 2 3 dependencies { 4 5 ... 6 7 implementation project(':react-native-contacts') // Add this line only. 8 9 }
第三步
在MainActivity.java文件中添加如下代碼:
1 import com.rt2zz.reactnativecontacts.ReactNativeContacts; 2 3 ... 4 5 @Override 6 protected List<ReactPackage> getPackages() { 7 return Arrays.<ReactPackage>asList( 8 new MainReactPackage(), 9 new ReactNativeContacts() // Add this line 10 ); 11 }
第四步
在AndroidManifest.xml文件中添加訪問通訊錄權限的配置
1 <!-- 獲取通訊錄權限 --> 2 <uses-permission android:name="android.permission.READ_CONTACTS" /> 3 <uses-permission android:name="android.permission.WRITE_CONTACTS" /> 4 <uses-permission android:name="android.permission.GET_ACCOUNTS" />
然后直接react-native run-android運行即可
2.3 iOS配置
第一步
添加庫到XCode的Libraries
分組里
第二步
將 RCTContacts.xcodeproj下的Products
文件夾中的靜態庫文件(.a文件,拖到Xcode General--Linked FrameworksLibraries下:
第三步
在Xcode Build Settings--Header Searchs Paths添加下:
1 $(SRCROOT)/../node_modules/react-native-contacts/ios/RCTContacts
第四步
配置訪問通訊錄的權限,如果不配置Privacy - Contacts Usage Description到Info.plist下,會出現閃退情況。在Info.plist添加如下:
1 <key>NSContactsUsageDescription</key> 2 <string>訪問通訊錄</string>
下面直接react-native run-ios即可運行,或直接在Xcode里 running
三,實現
3.1 實現的效果
3.2 iOS Android 驗證和請求訪問權限
Android直接可以使用react-native 自帶的API驗證。而iOS需要第三方驗證權限。
1 requestCONTACTS = () => { 2 let self = this; 3 if (Platform.OS === 'android') { 4 PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_CONTACTS).then(res => { 5 if (!res || res !== 'granted') { 6 PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_CONTACTS, { 7 'title': '申請讀取通訊錄權限', 8 'message': '一個很牛逼的應用想借用你的通訊錄,' + 9 '然后你就可以炫出自己的通訊啦。' 10 }) 11 .then(res => { 12 if (res !== 'granted') { 13 Alert.alert('訪問通訊錄權限沒打開', '請在iPhone的“設置-隱私”選項中,允許訪問您的通訊錄') 14 } 15 else { 16 17 self.onButtonPressed() 18 }; 19 }); 20 } 21 else { 22 self.onButtonPressed() 23 }; 24 }); 25 26 } else { 27 if (Contacts) { 28 Contacts.checkPermission((err, permission) => { 29 if (err) throw err; 30 // Contacts.PERMISSION_AUTHORIZED || Contacts.PERMISSION_UNDEFINED || Contacts.PERMISSION_DENIED 31 if (permission === 'undefined') { 32 Contacts.requestPermission((err, permission) => { 33 if (err) throw err; 34 if (permission === 'authorized') { 35 // 同意! 36 self.onButtonPressed() 37 } 38 if (permission === 'denied') { 39 // 拒絕 40 Alert.alert('訪問通訊錄權限沒打開', '請在iPhone的“設置-隱私”選項中,允許訪問您的通訊錄') 41 } 42 }) 43 } 44 if (permission === 'authorized') { 45 // 同意! 46 self.onButtonPressed() 47 } 48 if (permission === 'denied') { 49 // 已經拒絕 50 Alert.alert('訪問通訊錄權限沒打開', '請在iPhone的“設置-隱私”選項中,允許訪問您的通訊錄') 51 } 52 }) 53 } 54 } 55 }
3.3 獲取通訊錄列表
1 onButtonPressed() { 2 let self = this; 3 Contacts.getAll((err, contacts) => { 4 if (err) throw err; 5 alert(JSON.stringify(contacts));//通訊錄列表 6 }) 7 }
3.4 修改通訊錄信息
1 updateContact(contacts){ 2 let someRecord = contacts 3 someRecord.phoneNumbers.push({ 4 label: "mobile", 5 number: "12345678901", 6 }) 7 someRecord.givenName = '李四' 8 Contacts.updateContact(someRecord, (err) => { 9 if (err) throw err; 10 // record updated 11 }) 12 }
3.5 添加通訊錄信息
1 openContactForm(){ 2 var newPerson = { 3 phoneNumbers: [{ 4 label: "mobile", 5 number: "15422234567", 6 }], 7 familyName: "張", 8 givenName: "張三", 9 } 10 11 Contacts.openContactForm(newPerson, (err) => { 12 if (err) throw err; 13 // form is open 14 }) 15 }
3.6 刪除通訊錄
1 deleteContact(contacts){ 2 //delete the second record 3 Contacts.deleteContact(contacts, (err, recordId) => { 4 if (err) throw err; 5 // contact deleted 6 }) 7 }
3.7 實現類通訊錄列表
ContactsList自定義的一個組件,類通訊錄+字母導航,點擊可滾動到對應的位置。(如需完整代碼 請留言評論)
1 import Contacts from 'react-native-contacts'; 2 import ContactsList from './ContactsList/index' 3 4 <View style={{ flex: 1,backgroundColor:'white',paddingTop:20,paddingBottom:20 }}> 5 6 <ContactsList 7 ref={s => this.sectionList = s} 8 sectionListData={this.state.ContactsArray} 9 sectionHeight={50} 10 initialNumToRender={this.state.ContactsArray.length} 11 showsVerticalScrollIndicator={false} 12 SectionListClickCallback={(item, index) => { 13 self.onDialingAction(item.number) 14 }} 15 otherAlphabet="#" 16 /> 17 </View>
3.8 撥打電話
1 onDialingAction = (telephone) => { 2 let url = 'tel: ' + telephone 3 Linking.canOpenURL(url).then(supported => { 4 if (!supported) { 5 Toast.show('您的系統不支持打電話!') 6 } else { 7 return Linking.openURL(url); 8 } 9 }).catch(err => { }); 10 }
3.9 發送短信
1 onSendMessage = (telephone) => { 2 let url = 'smsto: ' + telephone 3 Linking.canOpenURL(url).then(supported => { 4 if (!supported) { 5 Toast.show('您的系統不支持發送短信!') 6 } else { 7 return Linking.openURL(url); 8 } 9 }).catch(err => { }); 10 }
1 let body='測試發送短信!' 2 let url = 'smsto: ' + telephone 3 if(Platform.OS === 'android') body = encodeURIComponent(body); 4 url += Platform.OS === 'ios' ? `&body=${encodeURIComponent(body)}` : `?body=${encodeURIComponent(body)}`; 5 Linking.canOpenURL(url).then(supported => { 6 if (!supported) { 7 Toast.show('您的系統不支持發送短信!') 8 } else { 9 return Linking.openURL(url); 10 } 11 }).catch(err => { });
3.10 篩選出通訊錄里有多少好友正在在使用某個應用
這個功能需要后台配合,在這兒就不做過多贅述啦!