<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Kaan Şan</title>
    <description>The latest articles on DEV Community by Kaan Şan (@kaansan).</description>
    <link>https://dev.to/kaansan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F78937%2F32b87f7a-765b-40f6-aab5-0d796f9f6589.jpeg</url>
      <title>DEV Community: Kaan Şan</title>
      <link>https://dev.to/kaansan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/kaansan"/>
    <language>en</language>
    <item>
      <title>Tutorial: Transfering contacts with React Native</title>
      <dc:creator>Kaan Şan</dc:creator>
      <pubDate>Mon, 21 Dec 2020 21:56:35 +0000</pubDate>
      <link>https://dev.to/kaansan/tutorial-transfering-contacts-with-react-native-4o6i</link>
      <guid>https://dev.to/kaansan/tutorial-transfering-contacts-with-react-native-4o6i</guid>
      <description>&lt;h1&gt;
  
  
  Painful problem
&lt;/h1&gt;

&lt;p&gt;I always forgot to store my contacts on google or anywhere.&lt;br&gt;
Sometimes I don't want to either.&lt;br&gt;
When I changed my smartphone, I have to transfer my contacts essentially. Manually adding contacts is a huge pain.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fencrypted-tbn0.gstatic.com%2Fimages%3Fq%3Dtbn%3AANd9GcSdnTNMNAErCgTRu07hCMTk521lXak4MdocEQ%26usqp%3DCAU" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fencrypted-tbn0.gstatic.com%2Fimages%3Fq%3Dtbn%3AANd9GcSdnTNMNAErCgTRu07hCMTk521lXak4MdocEQ%26usqp%3DCAU" alt="pain"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  Research I did
&lt;/h1&gt;

&lt;p&gt;I've researched some applications but unfortunately didn't like their behaviour. They were not open source or they were using bluetooth. I didn't trust some of them either.&lt;/p&gt;
&lt;h1&gt;
  
  
  Solution
&lt;/h1&gt;

&lt;p&gt;After some researchs, I've decided to code an android app. I've used expo with react native to build a quick solution for transfering contacts.&lt;br&gt;
Basically, Your old phone can send your contacts in a json format.&lt;br&gt;
On your new phone, you can use that json file to compare values and import them.&lt;br&gt;
This is an open source app called &lt;strong&gt;contacto&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;a href="https://github.com/kaansan/contacto" rel="noopener noreferrer"&gt;https://github.com/kaansan/contacto&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It might be helpful for react native beginners to read and understand, what &lt;strong&gt;contacto&lt;/strong&gt; does in under the hood.&lt;/p&gt;
&lt;h1&gt;
  
  
  Quick Tips
&lt;/h1&gt;

&lt;p&gt;&lt;strong&gt;contacto&lt;/strong&gt; uses Contacts, Sharing, FileSystem, DocumentPicker, IntentLauncher as well for achieving for transfering contacts.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Every contact number on a phone can be imported with a file format called &lt;strong&gt;vcf&lt;/strong&gt;. It stands for Variant Call Format.&lt;br&gt;
Which I create vcf aka vCard with this function.&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getVcardTemplate = (name, number) =&amp;gt;`
BEGIN:VCARD
VERSION:2.1
N:;${name};;;
TEL;CELL:${number}
END:VCARD
`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Show me the code ...
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;We get phone contacts data with Contacts API with expo&lt;br&gt;
We have to get permission first, to get contacts then we can iterate that data to get numbers and names.&lt;br&gt;
I also get the id from contacts for rendering unique objects on the FlatList&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getPhoneContacts = async () =&amp;gt; {
        const { status } = await Contacts.requestPermissionsAsync()

        if (status === 'granted') {
            // Getting contacts with permissions on android
            const { data } = await Contacts.getContactsAsync({
                fields: [
                    Contacts.PHONE_NUMBERS,
                ],
            })

            // Getting data we need.
            const contacts = []
            data.map((number) =&amp;gt; {
                const { name, phoneNumbers, id } = number
                if (name &amp;amp;&amp;amp; phoneNumbers &amp;amp;&amp;amp; id) {
                    let phoneNumber = phoneNumbers[0]?.number
                    phoneNumber = phoneNumber.replace(/\s+/g, '')
                    contacts.push({ name, number: phoneNumber, id })
                }
            })

            // Let's write phone contacts to a json file.
            const jsonContacts = JSON.stringify(contacts)
            const uri = createFileName(FileSystem, 'contacts.json')
            await this.writeContactsToFile(uri, jsonContacts)
            await this.sendOldPhoneContacts(uri)
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Another key function for comparing values&lt;br&gt;
We pick the contacts.json with DocumenPicker.&lt;br&gt;
Get the permission and get new phone contacts too for comparing numbers.&lt;br&gt;
Then, we have to iterate parsed contact.json and create vCard templates.&lt;br&gt;
After aggregating data, we can simply write a new vcf file.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;compareNumbers = async () =&amp;gt; {
        const result = await DocumentPicker.getDocumentAsync({})

        if (result.type === 'success') {
            if (!result.name.includes('contacts.json')) {
                alert('You have to select contacts.json')
                return        
            } else {
                alert(`You've picked the file: ${result.name}`)
            }

            const { uri } = result
            if (uri) {
                try {
                    const jsonContacts = await FileSystem.readAsStringAsync(uri)
                    const parsedContacts = JSON.parse(jsonContacts)
                    const { status } = await Contacts.requestPermissionsAsync()

                    if (status === 'granted') {
                        // Getting contacts with permissions on android
                        const { data } = await Contacts.getContactsAsync({
                            fields: [
                                Contacts.PHONE_NUMBERS,
                            ],
                        })

                        const numbers = []
                        data.map((number) =&amp;gt; {
                            const { phoneNumbers } = number
                            if (phoneNumbers) {
                                let phoneNumber = phoneNumbers[0]?.number
                                phoneNumber = phoneNumber.replace(/\s+/g, '')
                                numbers.push(phoneNumber)
                            }
                        })

                        const newContacts = []
                        let vCardTotal = ''
                        parsedContacts.map((contact) =&amp;gt; {
                            const { name, number, id } = contact

                            // Finding unrecorded phone numbers
                            const exist = numbers.find((currentNumber) =&amp;gt; currentNumber === number)

                            if (!exist) {
                                newContacts.push({ id, name, number })
                                const vCard = getVcardTemplate(name, number)
                                vCardTotal += vCard
                            } else {
                                console.log(`${number} is exist !`)
                            }
                        })

                        const newRecordsUri = createFileName(FileSystem, 'new_contacts.vcf')
                        this.setState({ newContacts, newRecordsUri })
                        if (vCardTotal) {
                            await this.writeContactsToFile(newRecordsUri, vCardTotal)
                        } else {
                            alert('Your contacts are up to date !')
                        }
                    }
                } catch (err) {
                    throw new Error(err)
                }
            }
        } else {
            alert('You have to give permission for comparing contacts !')
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Importing VCF file for adding contacts with expo is not documented.&lt;br&gt;
I had to use IntentLauncher for viewing vcf file. You cant import via Linking&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; importNewContacts = async () =&amp;gt; {
        const { newRecordsUri } = this.state

        await FileSystem.getContentUriAsync(newRecordsUri).then((cUri) =&amp;gt; {
            IntentLauncher.startActivityAsync('android.intent.action.VIEW', {
                data: cUri,
                type: 'text/x-vcard',
                flags: 1,
            })
        })
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Anyways, I hope this would be helpful or resolves somenone's issue.&lt;/p&gt;

</description>
      <category>reactnative</category>
      <category>javascript</category>
      <category>android</category>
      <category>contacts</category>
    </item>
  </channel>
</rss>
