<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marwa Diab on Medium]]></title>
        <description><![CDATA[Stories by Marwa Diab on Medium]]></description>
        <link>https://medium.com/@marwa.diab?source=rss-ef56d0d0bdcf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hayCj1CGse6ZNCmNnPgkqw.jpeg</url>
            <title>Stories by Marwa Diab on Medium</title>
            <link>https://medium.com/@marwa.diab?source=rss-ef56d0d0bdcf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:02:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marwa.diab/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rich Link Representation in Jetpack Compose]]></title>
            <link>https://blog.stackademic.com/rick-link-representation-in-jetpack-compose-d33956e8719e?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d33956e8719e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[link-presentation]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 09:18:37 GMT</pubDate>
            <atom:updated>2024-09-09T12:13:17.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Dmf-mAY-uEsmZseYA-i9Q.png" /></figure><h4>Learn how to present URL links in rich visual representation</h4><p><strong>Rick Link Representation</strong> is displaying URLs in a more engaging and informative way, rather than as plain text, to enhance the user experience. This approach makes the content more appealing and gives users a better idea of what to expect before they click on the link.</p><p>In this tutorial, you will learn how to fetch metadata for a given URL and present it in a visually rich component.</p><blockquote>If you want to read the <strong>SwiftUI</strong> version, check out this article 👇🏻:</blockquote><p><a href="https://medium.com/@marwa.diab/rich-link-representation-in-swiftui-2f155689fe62">Rich Link Representation in SwiftUI</a></p><p>In this tutorial, we will use the following libraries:</p><ul><li>Jsoup: an open-source Java library designed to parse, extract, and manipulate data stored in HTML documents.</li><li>Coil: an image loading library for Android. It is fast, lightweight, and leverages Kotlin’s language features.</li></ul><blockquote>To understand more about these libraries, I’ve linked them in the <strong>Resources</strong> section at the end of this article.</blockquote><h4>KMP Support</h4><p>I’ve linked the kmp branch on the Github repository which includes KMP support, contributed by <a href="https://x.com/prashant_gahlot">Prashant Gahlot</a>. Be sure to check it out!</p><h4>Dependencies</h4><p>If you’er using the version catalog (which is the recommended approach), add the following Jsoup and coil libraries in libs.versions.toml file:</p><pre>[versions]<br># other versions ....<br>coil-compose = &quot;2.7.0&quot;<br>jsoup = &quot;1.15.3&quot;<br><br>[libraries]<br># other libraries ....<br>coil-compose = { module = &quot;io.coil-kt:coil-compose&quot;, version.ref = &quot;coil-compose&quot; }<br>jsoup = { module = &quot;org.jsoup:jsoup&quot;, version.ref = &quot;jsoup&quot; }</pre><p>And in the app-level <strong>build.gradle</strong> file, add the following:</p><pre>dependencies {<br>    /// other libraries ...<br>    <br>    implementation(libs.coil.compose) // --&gt; &quot;org.jsoup:jsoup:1.15.3&quot;<br>    implementation(libs.jsoup) // --&gt; &quot;io.coil-kt:coil-compose:2.7.0&quot;<br>}</pre><p>Sync the project with the Gradle files.</p><p>Next, in <strong>AndroidManifest.xml</strong>, add the following line before the application tag, to request permission to access the internet:</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</pre><h4>Fetch Metadata</h4><p>Next, create new kotlin file named <strong>LinkMetadata.kt</strong> in <strong>model</strong> package, and add the following code:</p><pre>// 1.<br>sealed class LinkViewState {<br>    data object Loading: LinkViewState()<br>    data class Success(val metadata: LinkMetadata): LinkViewState()<br>    data class Failure(val exception: Exception): LinkViewState()<br>}<br><br>// 2.<br>data class LinkMetadata(<br>    val url: String,<br>    val host: String,<br>    val title: String? = null,<br>    val description: String? = null,<br>    val imageUrl: String? = null<br>)<br><br>// 3.<br>fun fetchMetadata(url: String): LinkViewState {<br>    return try {<br>        val host = URL(url).host<br>        // 4.<br>        val doc = Jsoup.connect(url).get()<br>        // 5.<br>        val title = doc.title()<br>        val description = doc.select(&quot;meta[property=og:description]&quot;).attr(&quot;content&quot;)<br>        val imageUrl = doc.select(&quot;meta[property=og:image]&quot;).attr(&quot;content&quot;)<br>        LinkViewState.Success(LinkMetadata(url, host, title, description, imageUrl))<br>    } catch (e: Exception) {<br>        // 6.<br>        Log.e(&quot;MetadataFetch&quot;, &quot;Error fetching metadata&quot;, e)<br>        LinkViewState.Failure(e)<br>    }<br>}</pre><p>Here’s what happens in this code snippet:</p><ol><li>LinkViewState is a sealed class representing different states of fetching the metadata process.</li><li>LinkMetadata is a data class that holds the metadata about a link. title, and image are the most essential elements for presenting a preview. Additionally, the description is included as an optional field for extra use cases if needed in your app.</li><li>fetchMetadata(url:) function fetches and parses an HTML document for a given URL using Jsoup.</li><li>Jsoup.connect(url) function creates a connection to the specified URL. .get() executes the request, fetching the HTML content from the URL and parse it into a Document object.</li><li>Extracts the required elements from the HTML document, and returns a Success state with the metadata.</li><li>If an error occurred, returns a Failure state with the exception.</li></ol><h4>Main Screen</h4><p>Go to MainActivity.kt file and add the following code:</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContent {<br>            RichLinksTheme {<br>                MainScreen()<br>            }<br>        }<br>    }<br>}<br><br>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun MainScreen() {<br>    val linksList = listOf(<br>        &quot;https://not-valid-url&quot;, // --&gt; Invalid URL<br>        &quot;https://m3.material.io/develop/android/jetpack-compose&quot;, // --&gt; Valid URL<br>        &quot;https://expatexplore.com/blog/when-to-travel-weather-seasons/&quot;, // --&gt; URL that does not contain image<br>    )<br><br>    Scaffold(<br>        topBar = {<br>            CenterAlignedTopAppBar(<br>                title = { Text(&quot;Rich Links&quot;) },<br>            )<br>        },<br>        containerColor = MaterialTheme.colorScheme.background<br>    ) { paddingValues -&gt;<br>        LazyColumn(<br>            modifier = Modifier<br>                .padding(paddingValues)<br>                .fillMaxSize()<br>                .wrapContentSize(Alignment.TopCenter),<br>            contentPadding = PaddingValues(16.dp),<br>            verticalArrangement = Arrangement.spacedBy(16.dp),<br>            horizontalAlignment = Alignment.CenterHorizontally<br>        ) {<br>            items(linksList) { link -&gt;<br>                LinkItemView(link = link) // --&gt; will be created next<br>            }<br>        }<br>    }<br>}<br><br>@Preview(showBackground = true)<br>@Composable<br>fun RickLinksPreview() {<br>    RichLinksTheme {<br>        MainScreen()<br>    }<br>}</pre><p>In this code snippet, we created a simple MainScreen composable that contains a LazyColumn with padding and alignments to present a list of LinkItemView. The linksList variable in the MainScreen composable contains different URLs to test various scenarios in our views; feel free to add more links to test your views.</p><h4>Custom Rick Link View</h4><p>Now let’s create a composable that will fetch and display metadata content. Add new kotlin file named <strong>LinkItemView.kt</strong> and add the following LinkItemView composable:</p><pre>@Composable<br>fun LinkItemView(<br>    link: String,<br>    modifier: Modifier = Modifier<br>) {<br>    // 1.<br>    val scope = rememberCoroutineScope()<br>    // 2.<br>    val context = LocalContext.current<br>    // 3.<br>    var loadingState by remember {<br>        mutableStateOf&lt;LinkViewState&gt;(LinkViewState.Loading)<br>    }<br>    // 4.<br>    LaunchedEffect(link) {<br>        scope.launch(Dispatchers.IO) {<br>            loadingState = fetchMetadata(link)<br>        }<br>    }<br><br>    // TODO: content…<br>}</pre><p>Here’s what happens in this code snippet:</p><ol><li>Creates a coroutine scope that is tied to the lifecycle of the composable.</li><li>Provides the current context, which will be used later to start an activity when the link is clicked.</li><li>Initializes loadingState state variable to keep track of the metadata fetching status.</li><li>LaunchedEffect(link) side-effect runs whenever the given link parameter changes. scope.launch(Dispatchers.IO) launches a coroutine in the IO dispatcher. fetchMetadata(link) within the coroutine, it fetches metadata for the given link and assigns it to loadingState.</li></ol><p>Next, replace <strong>//TODO:</strong> content… with the following:</p><pre>Row(modifier = modifier<br>        .clip(RoundedCornerShape(15.dp))<br>        .fillMaxWidth()<br>        .height(90.dp)<br>        .background(MaterialTheme.colorScheme.surface)<br>) {<br>    when (val state = loadingState) {<br>        is LinkViewState.Loading -&gt; {<br>            // TODO: Loading View<br>        }<br>        is LinkViewState.Success -&gt; {<br>            // TODO: Link View            <br>        }<br>        is LinkViewState.Failure -&gt; {<br>            // TODO: Failure View   <br>        }<br>    }<br>}</pre><p>This code snippet uses a when expression to handle different states of loadingState. Depending on the loadingState value, it will execute the corresponding block of code to display the appropriate view.</p><p>Next, let’s create the three views that correspond to the three different states of loadingState.</p><p>First, for the LinkViewState.Failure state, add the following Row layout that contains an Icon and a Text to let the user know that the provided link is invalid:</p><ul><li>Feel free to download link_off drawable icon <a href="https://github.com/marwaniaaj/RichLinksJetpackCompose/blob/main/app/src/main/res/drawable/link_off.xml">here</a></li></ul><pre>Row(<br>    modifier = Modifier.fillMaxSize(),<br>    horizontalArrangement = Arrangement.spacedBy(<br>        8.dp,<br>        Alignment.CenterHorizontally<br>    ),<br>    verticalAlignment = Alignment.CenterVertically,<br>) {<br>    Icon(<br>        painter = painterResource(R.drawable.link_off),<br>        contentDescription = null,<br>        modifier = Modifier.size(25.dp),<br>        tint = Color.Red<br>    )<br>    Text(<br>        text = &quot;Provided link is invalid&quot;,<br>        style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),<br>    )<br>}</pre><p>Refresh the preview or run the app, it should look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*ERn3X02A-eQ79lY5J5ttFQ.png" /><figcaption>Invalid link view</figcaption></figure><p>Secondly, for the LinkViewState.Loading state, add the following Box layout that contains a CircularProgressIndicator and two Texts with a shimmer effect to indicate a loading state:</p><ul><li>Feel free to download the <a href="https://github.com/marwaniaaj/RichLinksJetpackCompose/blob/main/app/src/main/java/com/devtutorial/richlinks/ui/ShimmerModifier.kt">file</a> for the shimmer effect modifier.</li><li>The reference for the shimmer effect is linked at the end of the article.</li></ul><pre>Box(<br>    modifier = Modifier.size(90.dp),<br>    contentAlignment = Alignment.Center<br>) {<br>    CircularProgressIndicator(<br>        color = MaterialTheme.colorScheme.primary,<br>        strokeWidth = 5.dp<br>    )<br>}<br>Column(<br>    modifier = Modifier.padding(4.dp),<br>    verticalArrangement = Arrangement.spacedBy(4.dp),<br>) {<br>    Text(<br>        text = &quot;&quot;, minLines = 2,<br>        modifier = Modifier.fillMaxWidth().shimmer(),<br>    )<br>    Text(<br>        text = &quot;&quot;,<br>        modifier = Modifier.fillMaxWidth().shimmer()<br>    )<br>}</pre><p>Refresh the preview or run the app, it should look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVLSfZVBYLfz2T_HRTTYlw.gif" /><figcaption>Loading link view</figcaption></figure><p>Lastly, for the LinkViewState.Success state, add the following:</p><pre>val metadata = state.metadata<br>Row(<br>    modifier = modifier<br>        // 1.<br>        .clickable {<br>            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link))<br>            context.startActivity(intent)<br>        },<br>    horizontalArrangement = Arrangement.spacedBy(6.dp),<br>    verticalAlignment = Alignment.CenterVertically<br>) {<br>    // TODO: Coil&#39;s SubcomposeAsyncImage<br><br>    // 2.<br>    Column(<br>        modifier = Modifier.padding(4.dp),<br>        verticalArrangement = Arrangement.spacedBy(4.dp),<br>    ) {<br>        Text(<br>            text = metadata.title ?: &quot;Untitled&quot;,<br>            modifier = Modifier.fillMaxWidth(),<br>            color = MaterialTheme.colorScheme.primary,<br>            style = MaterialTheme.typography.bodyLarge,<br>            maxLines = 2<br>        )<br>        Text(<br>            text = metadata.host,<br>            modifier = Modifier.fillMaxWidth(),<br>            color = Color.Gray,<br>            style = MaterialTheme.typography.bodySmall<br>        )<br>    }<br>}</pre><p>Here’s what happens in this code snippet:</p><ol><li>In the case of LinkViewState.Success, add clickable modifier to the view, to enable the user to click on the link to open it in a browser.</li><li>Add a column layout that contains a Text for the metadata title, and a Text for the metadata url host.</li></ol><p>Next, replace <strong>//TODO:</strong> Coil’s SubcomposeAsyncImage with the following implementation for SubcomposeAsyncImage to load and display an image from the fetched metadata imageUrl:</p><ul><li>Feel free to download imagesmode icon <a href="https://github.com/marwaniaaj/RichLinksJetpackCompose/blob/main/app/src/main/res/drawable/imagesmode.xml">here</a></li></ul><pre>SubcomposeAsyncImage(<br>    // 1. <br>    model = ImageRequest.Builder(LocalContext.current)<br>        .data(metadata.imageUrl)<br>        .size(90.dp.value.toInt())<br>        .crossfade(true)<br>        .build(),<br>    contentDescription = null,<br>    modifier = Modifier<br>        .size(90.dp)<br>        .clip(RoundedCornerShape(15.dp)),<br>    contentScale = ContentScale.Crop,<br>    // 2. <br>    loading = {<br>        Box(<br>            modifier = Modifier.size(90.dp),<br>            contentAlignment = Alignment.Center<br>        ) {<br>            CircularProgressIndicator(<br>                color = MaterialTheme.colorScheme.primary,<br>                strokeWidth = 5.dp<br>            )<br>        }<br>    },<br>    // 3.<br>    error = {<br>        Icon(<br>            painter = painterResource(R.drawable.imagesmode),<br>            contentDescription = null,<br>            modifier = Modifier.size(35.dp),<br>            tint = Color.Gray<br>        )<br>    }<br>)</pre><p>Here’s what happens in this code snippet:</p><ol><li>Builds an ImageRequest using ImageRequest.Builder, sets the data with metadata.imageUrl, specifies the size as 90.dp, and enables crossfade animation for a smooth transition.</li><li>Displays a CircularProgressIndicator when the image is loading.</li><li>Shows a placeholder Icon if an error occurred while loading the image.</li></ol><blockquote>To learn more about using coil in <strong>Jetpack Compose</strong>, I’ve linked references in the <strong>Resources</strong> section at the end of this article.</blockquote><p>Run the app on the Emulator, the result should look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*mq-QV7BMmSJHAqkPJq00Zw.gif" /><figcaption>Final Result for Rick Links</figcaption></figure><h4>Saveable</h4><p>If you attempt to rotate the phone, all the links will reload again, to prevent this, you need to change the remember of loadingState to rememeberSaveable. To achieve this, you need to define a custom Saver object for LinkViewState to handle the saving and restoring process. Additionally, the LinkMetadata data class needs to implement the Parcelable<em> </em>interface so that it can be serialized and deserialized by the Saver.</p><p>First, enable the Kotlin Parcelize plugin by adding the following in the plugins section of the app-level <strong>build.gradle</strong>, and sync the project with the Gradle files:</p><pre>plugins {<br>    /// ...<br>    id(&quot;kotlin-parcelize&quot;)<br>}</pre><p>Next, modify LinkMetadata data class to implement Parcelable interface:</p><pre>@Parcelize<br>data class LinkMetadata(<br>    val url: String,<br>    val host: String,<br>    val title: String? = null,<br>    val description: String? = null,<br>    val imageUrl: String? = null<br>): Parcelable</pre><p>The @Parcelize annotation generates the necessary code required for implementing the Parcelable interface, reducing boilerplate code.</p><p>In <strong>LinkItemView.kt</strong> file, before the LinkItemView composable, add a custom Saver object for the LinkViewState as follows:</p><pre>val LinkViewStateSaver = Saver&lt;LinkViewState, Any&gt;(<br>    save = { linkViewState -&gt;<br>        when (linkViewState) {<br>            LinkViewState.Loading -&gt; &quot;Loading&quot;<br>            is LinkViewState.Success -&gt; linkViewState.metadata<br>            is LinkViewState.Failure -&gt; linkViewState.exception.message ?: &quot;Error&quot;<br>        }<br>    },<br>    restore = { savedValue -&gt;<br>        when (savedValue) {<br>            is LinkMetadata -&gt; LinkViewState.Success(savedValue)<br>            is String -&gt; LinkViewState.Failure(Exception(savedValue))<br>            else -&gt; LinkViewState.Loading<br>        }<br>    }<br>)</pre><p>In this code snippet, the Saver is responsible for saving and restoring instances of LinkViewState to and from a format that can be handled by rememeberSaveable.</p><p>Finally, modify loadingState to replace remember with rememeberSaveable(stateSaver = LinkViewStateSaver), as follows:</p><pre>var loadingState by rememberSaveable(stateSaver = LinkViewStateSaver) {<br>    mutableStateOf(LinkViewState.Loading)<br>}</pre><p>Run the app on the Emulator, and test the rotation 🔄</p><h4>And Voilà! 🎉</h4><p>With that, you have a custom composable to represent rich links in your app. Feel free to make any changes to suit your needs.</p><blockquote>Enjoy coding 👩🏻‍💻📲✨</blockquote><h4>Resources 🔗</h4><ul><li><a href="https://callmeryan.medium.com/gradle-version-catalog-728111fa210f">Gradle Version Catalog</a></li><li><a href="https://coil-kt.github.io/coil/compose/">Jetpack Compose - Coil</a></li><li><a href="https://www.sinasamaki.com/loading-images-using-coil-in-jetpack-compose/">Loading images using coil in Jetpack Compose</a></li><li><a href="https://github.com/jhy/jsoup">GitHub - jhy/jsoup: jsoup: the Java HTML parser, built for HTML editing, cleaning, scraping, and XSS safety.</a></li><li><a href="https://www.droidcon.com/2021/10/27/how-to-create-a-preview-for-a-link-in-android/">How to create a preview for a link in Android</a></li><li><a href="https://fonts.google.com/icons?icon.size=24&amp;icon.color=%235f6368&amp;icon.style=Rounded&amp;icon.set=Material+Symbols&amp;icon.platform=web">Material Symbols and Icons - Google Fonts</a></li><li><a href="https://proandroiddev.com/shimmer-shadow-loading-effect-animation-with-jetpack-compose-f4b3de28dc2b">Shimmer &amp; Shadow Loading Effect Animation with Jetpack Compose</a></li></ul><blockquote>You can find the project’s full source code on <a href="https://github.com/marwaniaaj/RichLinksJetpackCompose.git">GitHub</a> 🚀 <br>For <strong>KMP</strong> support, check out this <a href="https://github.com/marwaniaaj/RichLinksJetpackCompose/tree/kmp">branch</a>.<br>If you liked this, don’t forget to 👏 and follow 😍.<br>Feedbacks are most welcome, drop them below in the comments section.</blockquote><blockquote>“ Everyone has something to learn. Everyone has something to teach.” ~ Paul Hudson</blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d33956e8719e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/rick-link-representation-in-jetpack-compose-d33956e8719e">Rich Link Representation in Jetpack Compose</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rich Link Representation in SwiftUI]]></title>
            <link>https://blog.stackademic.com/rich-link-representation-in-swiftui-2f155689fe62?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f155689fe62</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[link-presentation]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 13:17:59 GMT</pubDate>
            <atom:updated>2024-09-09T00:38:13.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBaZFjb43AIEyK4Dbhz85w.png" /></figure><h4>Learn how to present URL links in rich visual representation</h4><p><strong>Rick Link Representation</strong> is displaying URLs in a more engaging and informative way, rather than as plain text, to enhance the user experience. This approach makes the content more appealing and gives users a better idea of what to expect before they click on the link.<br>This is achieved through the <strong><em>LinkPresentation</em></strong> framework, which seamlessly handles fetching and displaying this metadata.</p><blockquote>The Link Presentation framework enables you to present content-rich URLs in a consistent way. Retrieve metadata from a URL, present the rich link content inside your app, and provide link metadata to the share sheet experience in iOS. ~ <a href="https://developer.apple.com/documentation/linkpresentation">Link Presentation</a></blockquote><p>In this tutorial, you will learn how to use Apple’s <a href="https://developer.apple.com/documentation/linkpresentation/lplinkview">LPLinkView</a> to present rich links, as well as create your own custom LinkView, that matches your app’s look and feel.</p><h4>LPLinkView</h4><p>Using Apple’s <a href="https://developer.apple.com/documentation/linkpresentation/lplinkview">LPLinkView</a> to present a rich link in your app is easy and straight forward, but it is not customizable if you require different look and feel.</p><p>Since LPLinkView is a <strong>UIKit</strong> component, it requires some bridging between SwiftUI and UIKit to integrate into <strong>SwiftUI</strong> project.</p><p>Create new swift file named <strong>LinkPreview.swift</strong>, and add the following:</p><ol><li>Create a LinkPreview struct that conforms to UIViewRepresentable and wraps the LPLinkView.</li><li>Implement the required methods to manage the lifecycle of the LPLinkView. The makeUIView method initializes the LPLinkView and starts fetching metadata for the provided previewURL. The updateUIView method is currently empty as no updates are needed after the initial setup.</li></ol><pre>import SwiftUI<br>import LinkPresentation<br><br>struct LinkPreview : UIViewRepresentable {<br>    var previewURL: URL<br><br>    func makeUIView(context: Context) -&gt; LPLinkView {<br>        let linkView = LPLinkView(url: previewURL)<br>        let provider = LPMetadataProvider()<br><br>        provider.startFetchingMetadata(for: previewURL) { (metadata, error) in<br>            guard let metadata = metadata, error == nil else { return }<br><br>            DispatchQueue.main.async {<br>                linkView.metadata = metadata<br>                linkView.sizeToFit()<br>            }<br>        }<br><br>        return linkView<br>    }<br><br>    func updateUIView(_ uiView: LPLinkView, context: Context) {}<br>}</pre><p>Next, go to ContentView and add the following:</p><pre>struct ContentView: View {<br>    @State private var links = [<br>        // Invalid URL<br>        &quot;https://not-valid-url&quot;, <br>        // Valid URL<br>        &quot;https://developer.apple.com/tutorials/swiftui/&quot;,<br>        // URL that does not contain image<br>        &quot;https://expatexplore.com/blog/when-to-travel-weather-seasons/&quot;, <br><br>    var body: some View {<br>        NavigationStack {<br>            ScrollView {<br>                ForEach(links, id:\.self) { link in<br>                    if let url = URL(string: link) {<br>                        LinkPreview(previewURL: url)<br>                            .aspectRatio(contentMode: .fit)<br>                            .padding(4)<br>                    }<br>                }<br>                .padding()<br>            }<br>            .navigationTitle(&quot;Rick Links&quot;)<br>            .navigationBarTitleDisplayMode(.inline)<br>        }<br>    }<br>}</pre><p>As you can see in the previous code snippet, the links variable contains different URLs to test various scenarios in our views, feel free to add more links to test your views.</p><p>Refresh the preview or run the app, it should look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*l-q-RwhaTtvgq4OVyEASmg.gif" /><figcaption>Rick Links using LPLinkView</figcaption></figure><h4>Custom Rick Link</h4><p>Now, let’s create customized rich link using <a href="https://developer.apple.com/documentation/linkpresentation/lpmetadataprovider">LPMetadataProvider</a> to fetch metadata, and then use the retrieved metadata to view the URL’s content.</p><p>First, create the following enum that holds image status while loading the requested image from the metadata:</p><pre>import SwiftUI<br><br>enum ImageStatus {<br>    case loading<br>    case finished(Image)<br>    case failed(Error)<br>}<br><br>enum LoadingError: Error {<br>    case contentUnavailable<br>    case contentTypeNotSupported<br>}</pre><p>Then, create new <strong>SwiftUI</strong> view named LinkItemView, and add the following:</p><ol><li>url holds the URL that the view will display. It’s initialized with the URL string passed to the view’s initializer.</li><li>isValidUrl is a boolean that tracks whether the URL is valid. It will be used to handle invalid URLs gracefully.</li><li>metadata stores the fetched metadata of the URL and used to populate the link preview.</li><li>imageStatus tracks the status of the requested image loading process. It will be used to show a loading indicator or placeholder image if the image failed to load.</li><li>The .task modifier fetches URL metadata asynchronously when the url changes.</li></ol><pre>struct LinkItemView: View {<br>    @State private var url: URL?<br>    @State private var isValidUrl = true<br>    @State private var metadata: LPLinkMetadata? = nil<br>    @State private var imageStatus: ImageStatus = .loading<br><br>    // 1.<br>    init(link: String) {<br>        _url = State(wrappedValue: URL(string: link))<br>    }<br><br>    var body: some View {<br>        VStack {<br>            // TODO: Link preview content ....<br>        }<br>        // 2.<br>        .task(id: url) {<br>            // TODO: fetch url metadata asynchronously<br>        }<br>    }<br>}</pre><p>After the body create the following fetchMetadata() asynchronous function:</p><ol><li>Unwrap provided url, if it failed to unwrap, set isValidUrl to false.</li><li>To request metadata for the provided URL, call startFetchingMetadata(for:) on a LPMetadataProvider instance.</li><li>If any error occurs, set isValidUrl to false.</li></ol><pre>private func fetchMetadata() async {<br>    // 1. <br>    guard let url else {<br>        isValidUrl = false<br>        return<br>    }<br><br>    do {<br>        // 2. <br>        metadata = try await LPMetadataProvider().startFetchingMetadata(for: url)<br>        // TODO: load image<br>    }<br>    catch {<br>        // 3.<br>        print(&quot;Error fetching URL metadata: \(error.localizedDescription)&quot;)<br>        isValidUrl = false<br>    }<br>}</pre><p>The fetched metadata contains the following properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*LOTE6wn_XpvyCHX5OnyNEA.png" /><figcaption>metadata for the URL</figcaption></figure><p>To load the image for the URL, we will use the provided imageProvider.</p><p>Create the following loadImage(from:) asynchronous function:</p><pre>private func loadImage(from imageProvider: NSItemProvider?) async {<br>    let imageType = UTType.image.identifier<br>    do {<br>        // 1.<br>        guard let imageProvider, imageProvider.hasItemConformingToTypeIdentifier(imageType) else {<br>            imageStatus = .failed(LoadingError.contentUnavailable)<br>            return<br>        }<br><br>        // 2.<br>        let item = try await imageProvider.loadItem(forTypeIdentifier: imageType)<br><br>        // 3.<br>        if item is UIImage, let image = item as? UIImage {<br>            imageStatus = .finished(Image(uiImage: image))<br>        }<br>        else if item is URL {<br>            guard let url = item as? URL,<br>                  let data = try? Data(contentsOf: url),<br>                  let image = UIImage(data: data)<br>            else {<br>                imageStatus = .failed(LoadingError.contentTypeNotSupported)<br>                return<br>            }<br>            imageStatus = .finished(Image(uiImage: image))<br>        }<br>        else if item is Data {<br>            guard let data = item as? Data, let image = UIImage(data: data) else {<br>                imageStatus = .failed(LoadingError.contentTypeNotSupported)<br>                return<br>            }<br>            imageStatus = .finished(Image(uiImage: image))<br>        }<br>    }<br>    catch {<br>        // 4.<br>        print(&quot;Error loading Image: \(error.localizedDescription)&quot;)<br>        imageStatus = .failed(error)<br>    }<br>}</pre><p>Here’s what happens in this code snippet:</p><ol><li>Ensure the imageProvider is not nil and conforms to the image type identifier. If not, set the imageStatus to failed.</li><li>Load the item asynchronously from the imageProvider.</li><li>Handle various types of items and converts them into a UIImage accordingly. If an image was successfully loaded, set the imageStatus to finished with the loaded image.</li><li>If any error occurs, set the imageStatus to failed.</li></ol><p>Next, replace <strong>// TODO: </strong>load image in fetchMetadata() function with the following line:</p><pre>await loadImage(from: metadata?.imageProvider)</pre><h4>Let’s construct the view</h4><p>Modify the body of LinkItemView to look like the following:</p><pre>var body: some View {<br>    VStack {<br>        if isValidUrl, let url {<br>            Link(destination: url) {<br>                HStack(alignment: .center) {<br>                    VStack {<br>                        switch imageStatus {<br>                        case .loading:<br>                            ProgressView()<br><br>                        case .finished(let image):<br>                            image<br>                                .resizable()<br>                                .scaledToFill()<br><br>                        case .failed:<br>                            Image(systemName: &quot;photo&quot;)<br>                                .resizable()<br>                                .scaledToFit()<br>                                .padding()<br>                                .foregroundStyle(.gray)<br>                        }<br>                    }<br>                    .clipped()<br>                    .frame(width: 90, height: 90)<br>                    .cornerRadius(15)<br><br>                    VStack(alignment: .leading) {<br>                        Text(metadata?.title ?? &quot;url title placeholder&quot;)<br>                            .font(.body)<br>                            .redacted(reason: metadata == nil ? .placeholder : [])<br><br>                        Text(metadata?.url?.host ?? &quot;url host placeholder&quot;)<br>                            .font(.footnote)<br>                            .foregroundStyle(.gray)<br>                            .redacted(reason: metadata == nil ? .placeholder : [])<br>                    }<br>                    .multilineTextAlignment(.leading)<br>                    .padding(.horizontal, 8)<br>                }<br>            }<br>        }<br><br>        else {<br>            HStack {<br>                Image(systemName: &quot;circle.slash&quot;)<br>                    .foregroundStyle(.red)<br>                Text(&quot;Provided link is invalid&quot;)<br>                    .font(.title3).bold()<br>            }<br>            .frame(maxWidth: .infinity, alignment: .center)<br>        }<br>    }<br>    .frame(height: 90)<br>    .frame(maxWidth: .infinity, alignment: .leading)<br>    .background {<br>        RoundedRectangle(cornerRadius: 15, style: .continuous)<br>            .fill(.gray.opacity(0.2))<br>    }<br>    .task(id: url) {<br>        await fetchMetadata()<br>    }<br>}</pre><p>The code for LinkItemView is simple and understandable, I just want to highlight that Link(destination: url) wraps the content in case of a valid URL, allowing the user to navigate to the tapped URL.</p><p>Lastly, in ContentView, replace LinkPreview with LinkItemView like follows:</p><pre>ForEach(links, id:\.self) { link in<br>    LinkItemView(link: link)<br>}</pre><p>Refresh the preview or run the app, it should look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*hoxR0HlTUghB0YzKbXAKrw.gif" /><figcaption>Rick Links using Custom LinkView</figcaption></figure><h4>And Voilà! 🎉</h4><p>With that, you now have two ways to represent rich links in your app.<br>Feel free to make any changes to suit your needs.</p><blockquote>Enjoy coding 👩🏻‍💻📲✨</blockquote><h4>Resources 🔗</h4><ul><li><a href="https://developer.apple.com/documentation/linkpresentation">Link Presentation | Apple Developer Documentation</a></li><li><a href="https://wwdcnotes.com/documentation/wwdcnotes/wwdc19-262-embedding-and-sharing-visually-rich-links/">Documentation</a></li><li><a href="https://medium.com/@alaputska/creating-custom-link-preview-instead-of-lplinkview-with-swiftui-909512a4cb27">Creating custom Link preview instead of LPLinkView with SwiftUI.</a></li></ul><blockquote>You can find the project’s full source code on <a href="https://github.com/marwaniaaj/RichLinksSwiftUI.git">GitHub</a> 🚀<br>If you liked this, don’t forget to 👏 and follow 😍.<br>Feedbacks are most welcome, drop them below in the comments section.</blockquote><blockquote><em>“ Everyone has something to learn. Everyone has something to teach.” ~ </em><a href="https://twitter.com/twostraws/status/1613922671523418117"><em>Paul Hudson</em></a></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f155689fe62" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/rich-link-representation-in-swiftui-2f155689fe62">Rich Link Representation in SwiftUI</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase Cloud Functions Event Triggers]]></title>
            <link>https://medium.com/firebase-developers/firebase-cloud-functions-event-triggers-57d9a039bc7f?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/57d9a039bc7f</guid>
            <category><![CDATA[cloud-firestore]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <category><![CDATA[firebase-event-triggers]]></category>
            <category><![CDATA[cloud-storage]]></category>
            <category><![CDATA[firebaseauth]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 12:00:09 GMT</pubDate>
            <atom:updated>2024-07-13T12:00:09.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BX6w13QbDA_EY4s5RTVeRA.png" /></figure><h4>Firebase Cloud Functions</h4><h4>Learn how to use Cloud Functions to handle events triggered by Firebase services, such as Authentication, Firestore, &amp; Storage triggers.</h4><blockquote>Cloud Functions for Firebase is a serverless framework that lets you automatically run backend code in response to events triggered by background events, HTTPS requests, the Admin SDK, or Cloud Scheduler jobs. Your JavaScript, TypeScript or Python code is stored on Google Cloud infrastructure and runs in a managed environment. There’s no need to manage and scale your own servers. ~ <a href="https://firebase.google.com/docs/functions?hl=en&amp;authuser=0">Firebase Documentation</a></blockquote><p>When building mobile apps (iOS/Android) it’s important to consider backend development, this involves handling server events, optimizing operations, minimizing client-side server calls, and promptly responding to event triggers.</p><p>In this article, I will showcase some of the use cases I typically encounter while building apps that utilize <strong>Firebase</strong> services. In this example, you’ll learn how to handle <strong>Authentication</strong>, <strong>Firestore</strong>, and <strong>Storage</strong> events.</p><h4>Use Cases</h4><ol><li>When a new user is authenticated, create new document in users collection with auth data such as email, name, photoUrl, and providerData. (collection name can vary based on your app’s business logic)</li><li>When a new document is created in <strong>Firestore</strong>, update the document with creationDate, and any other data required by the app upon document creation (e.g. isActive, isApproved, isAdmin, etc). Additionally, when a document is modified, update it with lastModifiedDate. These two cases are useful to ensure that you never need to worry about creation and modification dates when saving data from the client.</li><li>When a user uploads an image (or any other file type) for a specific document, it will be uploaded in <strong>Firebase</strong> <strong>Storage</strong> in the path &lt;collectionType&gt;/&lt;documentId/, The image’s URL will then be saved in the mediaUrl field within the document, allowing it to be downloaded and viewed in the app.</li></ol><p>I’ve written a comprehensive series of articles on implementing <strong>Firebase Authentication</strong>. Feel free to check them out if you haven’t already!</p><p>In <strong>SwiftUI</strong> apps:</p><p><a href="https://blog.stackademic.com/firebase-authentication-in-swiftui-apps-a828e804a80e">Firebase Authentication in SwiftUI apps</a></p><p>And in <strong>Jetpack Compose</strong> apps:</p><p><a href="https://blog.stackademic.com/firebase-authentication-in-jetpack-compose-c0584d5d6a03">Firebase Authentication in Jetpack Compose apps</a></p><h4>Prerequisites</h4><ul><li>Prior knowledge in <strong>Firebase</strong> services, such as Authentication, Firestore, and Storage.</li><li><a href="https://nodejs.org/en"><strong>Node.js</strong></a> (using <a href="https://github.com/nvm-sh/nvm/blob/master/README.md">nvm</a>), and <strong>NPM</strong> installed (explanation provided in the attached video below).</li><li>Firebase Blaze Plan (note that <em>Cloud Functions is not applicable in Spark Plan</em>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*GJRCiSOkDtsM_rTdTaVpJA.png" /></figure><h4>Project structure</h4><p>Whenever I start a new mobile app/project, I create the following project structure:</p><p>MyAwesomeApp/<br>├─ AndroidApp/<br>├─ iOSApp/<br>├─ CloudFunctions/</p><p>The <strong>CloudFunctions</strong> folder is where the <strong>Firebase CLI</strong> will be installed.</p><p>Open <strong><em>Terminal</em></strong>, and navigate to CloudFunctions folder, you can easily obtain the full path by typing cd followed by a space, and then dragging the folder into the terminal. The folder path will be pasted.</p><p>Feel free to check out the following video tutorial by <a href="https://medium.com/u/c37eed0fd693">David East</a> on the <a href="https://medium.com/u/33757dff064a">Firebase</a> YouTube channel, I highly recommend watching it to:</p><ol><li>Understand the importance and the benefits of using <strong>Cloud Functions</strong>.</li><li>Learn how to setup <strong>Firebase CLI</strong>, run <strong>Local Emulator Suite</strong>, and deploying <strong>Cloud Functions</strong>.</li><li>Running functions asynchronously, and understand Promises.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2u6Zb36OQjM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2u6Zb36OQjM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2u6Zb36OQjM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c835d2729d72bf846dbf1d23c7a9d70/href">https://medium.com/media/1c835d2729d72bf846dbf1d23c7a9d70/href</a></iframe><h4>Cloud Functions version</h4><p>In this article, Cloud Function (2nd gen) will be used for <strong>Firestore</strong> and <strong>Storage</strong> triggers, while Cloud Function (1st gen) will be used for <strong>Auth</strong> triggers. The reason for this distinction is that Cloud Functions (2nd gen) doesn’t currently support Authentication triggers.</p><blockquote>We recommend that you choose Cloud Functions (2nd gen) for new functions wherever possible. However, we plan to continue supporting Cloud Functions (1st gen). ~ <a href="https://firebase.google.com/docs/functions/version-comparison?authuser=0">Cloud Functions version comparison</a></blockquote><h3>Setup the CLI</h3><h4>As mentioned in the video</h4><blockquote>The CLI works as a project starter, setting up the boilerplate that you need to develop. It also works as a local emulator that spins up a local server that emulates a production environment and allows you to trigger different types of functions. It also serves as the Deployment Manager, allowing you to deploy all or even individual sets of functions.</blockquote><p>Feel free to follow the steps in <a href="https://firebase.google.com/docs/functions/get-started?authuser=0&amp;gen=2nd#set-up-your-environment-and-the-firebase-cli">Set up your environment and the Firebase CLI</a> and <a href="https://firebase.google.com/docs/functions/get-started?authuser=0&amp;gen=2nd#initialize-your-project">Initialize your project</a> sections in the Cloud Functions Documentations, if you haven’t already followed the steps from the previous video.</p><h4>Firebase Emulator</h4><p>It’a a good practice to test Cloud Functions in Firebase Emulator before deploying changes to Firebase. To start the emulators, run firebase emulators:start in the command line.</p><p>Additionally, to import and export test data when running emulators (so that the data isn’t lost between sessions), add the following inside your package.json scripts.</p><pre>&quot;scripts&quot;: {<br>  // other scripts...<br>  &quot;firebase:start:import&quot;: &quot;npm run build &amp;&amp; firebase emulators:start --import ../test-data --export-on-exit ../test-data&quot;,<br>}</pre><p>This CLI command ensures that each time emulators are shut down, the data is persisted (exported) to the provided directory (in this case, test-data), and it imports data from the same directory each time the emulators start.</p><p>To test your functions, run the following command in the command line to build and start emulators with import and export options:</p><pre>npm run firebase:start:import</pre><p>Remember that you can use ^c (control+c) in the command line to exit the emulators.</p><h4>Watch changes</h4><p>To automatically recompile code with new changes, you can use the npm run build:watch command. It monitors the source files for modifications and triggers a rebuild of the project whenever any changes are detected. This feature is particularly useful during development, as it eliminates the need to manually rebuild the project each time you make edits, allowing you to see the results almost immediately.</p><h3>Authentication Triggers</h3><blockquote>You can trigger functions in response to the creation and deletion of Firebase user accounts. For example, you could send a welcome email to a user who has just created an account in your app. ~ <a href="https://firebase.google.com/docs/functions/auth-events?authuser=0">Firebase Authentication triggers</a>.</blockquote><p>Import the required modules and initialize Admin SDK:</p><pre>import * as functions from &quot;firebase-functions&quot;;<br>import * as admin from &quot;firebase-admin&quot;;<br><br>admin.initializeApp();</pre><h4>onCreate</h4><p>Add the following code for onAuthUserCreate trigger function that handles the creation of a Firebase Auth user:</p><ol><li>Create userData containing data to be updated in the user’s document. Add an isAuthenticated flag to indicate that the user is authenticated. feel free to update the document with any additional data your app requires upon authentication.</li><li>Create a user DocumentReference using user.uid as the documentId, use set(data:options:) to write data to the document, this method creates the document if it doesn’t exist yet or merges data into an existing document.</li></ol><pre>export const onAuthUserCreate = functions.auth.user().onCreate(async user =&gt; {<br>    // 1.<br>    const userData: any = {<br>        &quot;email&quot;: user.email,<br>        &quot;isAuthenticated&quot;: true,<br>    };<br>      <br>    if (user.displayName !== null) {<br>        userData[&quot;name&quot;] = user.displayName<br>    }<br>    if (user.photoURL !== null) {<br>        userData[&quot;photoUrl&quot;] = user.photoURL<br>    }<br><br>    // 2.<br>    const userDocRef = admin.firestore().doc(`users/${user.uid}`);<br>    return await userDocRef.set(userData, {merge: true});<br>    // TODO: Send a welcome email<br>});</pre><h4>onDelete</h4><blockquote>The Delete User Data extension (delete-user-data) lets you delete a user&#39;s data when the user is deleted from your Firebase project. You can configure this extension to delete user data from any or all of the following: Cloud Firestore, Realtime Database, or Cloud Storage. Each trigger of the extension to delete data is keyed to the user&#39;s UserId. ~ <a href="https://firebase.google.com/docs/extensions/official/delete-user-data">Using the Delete User Data extension</a></blockquote><p>Before Firebase introduced the <strong><em>Delete User Data</em></strong> extension, I manually deleted all user data in <strong>Firestore</strong> within the onDelete trigger function. Now that the extension handles data deletion, the remaining task is to send the user a farewell email.</p><pre>export const onAuthUserDelete = functions.auth.user().onDelete(async user =&gt; {<br>    // TODO: Send a farewell email<br>});</pre><h3>Firestore Triggers</h3><blockquote>With Cloud Functions, you can handle events in Cloud Firestore with no need to update client code. You can make Cloud Firestore changes via the document snapshot interface. ~ <a href="https://firebase.google.com/docs/functions/firestore-events?authuser=0&amp;gen=2nd">Cloud Firestore triggers</a>.</blockquote><blockquote><strong>Warning:</strong> Any time you write to the same document that triggered a function, you are at risk of creating an infinite loop. Use caution and ensure that you safely exit the function when no change is needed.</blockquote><p>This is a crucial warning to take into account, with further explanation provided in the <strong>onDocumentUpdated</strong> section below.</p><p>Import the following event handlers (onDocumentCreated, &amp; onDocumentUpdated), Change class, and QueryDocumentSnapShot type:</p><pre>import { <br>    onDocumentCreated, <br>    onDocumentUpdated, <br>    Change, <br>    QueryDocumentSnapshot <br>} from &quot;firebase-functions/v2/firestore&quot;;</pre><h4>onDocumentCreated</h4><p>Add the following onUserDocumentCreate trigger function that handles a document creation in users collection in <strong>Firestore</strong>, within this function, update the newly created document with the following data:</p><ul><li>updateTime The timestamp when the document was last updated (at the time the snapshot was generated).</li><li>isActive is a Boolean indicating whether this document is active. Feel free to use any default values that your app requires upon document creation. For example, you can check for a mediaUrl field, and if it’s null, set it with a placeholder image saved in <strong>Cloud Storage</strong>.</li></ul><pre>export const onUserDocumentCreate = onDocumentCreated(&quot;users/{userId}&quot;, (event) =&gt; {<br>    return event.data?.ref.update({<br>        creationDate: event.data.updateTime,<br>        &quot;isActive&quot;: true,<br>    });<br>})</pre><h4>onDocumentUpdated</h4><p>Add the following onUserDocumentUpdate trigger function that handles a document update in the users collection in <strong>Firestore</strong>, call the updateLastModifiedOnDocumentUpdate function and pass change.data, which holds the before-and-after changes made to the document.</p><pre>export const onUserDocumentUpdate = onDocumentUpdated(&quot;users/{userId}&quot;, (change) =&gt; {<br>    return updateLastModifiedOnDocumentUpdate(change.data)<br>})</pre><p>Add the following updateLastModifiedOnDocumentUpdate(change:) function that handles updating the document’s modification date:</p><pre>function updateLastModifiedOnDocumentUpdate(change: Change&lt;QueryDocumentSnapshot&gt; | undefined): any {<br>    if (!change) { return null; }<br>    // 1.<br>    if (change.before.data().lastModifedDate) {<br>        // 2.<br>        if (change.before.data().lastModifedDate.isEqual(change.after.data().lastModifedDate)) {<br>            return change.after.ref.update({<br>                lastModifedDate: change.after.updateTime,<br>            });<br>        }<br>    } else {<br>        // 3.<br>        return change.after.ref.update({<br>            lastModifedDate: change.after.updateTime,<br>        });<br>    }<br>};</pre><p>Here’s what happens in this code snippet:</p><ol><li>Check if lastModifiedDate field exists.</li><li>If the lastModifiedDate exists, check if an update occurred and it was not triggered by lastModifiedDate field (before and after changes have the same value), then update lastModifiedDate with the snapshot timestamp.</li><li>If the lastModifiedDate field does not exist, then insert new value.</li></ol><p>The following condition is crucial to prevent infinite loop, it updates the document only if the update was triggered by any other field.</p><pre>if (change.before.data().lastModifedDate.isEqual(change.after.data().lastModifedDate)) {}</pre><h4>Test it out</h4><p>Run the emulators to test authentication and firestore triggers, navigate to the <strong>Authentication</strong> emulator, and click on <strong><em>Add User</em></strong> to create a new authenticated user, enter the necessary data and click <strong><em>Save</em></strong>. Next navigate to the <strong>Firestore</strong> emulator, where you’ll find a new user document created with the UID as the Document ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*YIhxrmzKY5jS5JVLL6zkig.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fN5ctgOQei-P3mmXUvpqTw.png" /><figcaption>Create new authenticated user, and resulted user document in Firestore.</figcaption></figure><h3>Storage Triggers</h3><blockquote>You can trigger a function in response to the uploading, updating, or deleting of files and folders in Cloud Storage. ~ <a href="https://firebase.google.com/docs/functions/gcp-storage-events?authuser=0&amp;gen=2nd">Cloud Storage Triggers</a>.</blockquote><p>Based on previously mentioned use case for <strong>Firebase Storage</strong>, there are three types of URLs:</p><ol><li><strong><em>Token</em></strong> URLs, These are persistent and have security features.</li><li><strong><em>Signed</em></strong> URLs, These are temporary and also have security features.</li><li><strong><em>Public</em></strong> URLs, These are persistent but lack security.</li></ol><p>Import the following event handlers, and functions:</p><pre>import { <br>     onObjectFinalized, onObjectDeleted<br>} from &quot;firebase-functions/v2/storage&quot;;<br><br>import { getStorage, getDownloadURL } from &quot;firebase-admin/storage&quot;</pre><h4>onObjectFinalized</h4><p>Add the following onFileFinalized trigger function that handles object creation in <strong>Cloud Storage</strong>:</p><pre>export const onFileFinalized = onObjectFinalized(async (event) =&gt; {<br>    // 1.<br>    if (!event.data) { return null; }<br>    // 2.<br>    if (event.data.contentType == &quot;application/octet-stream&quot;) { return null; }<br><br>    const filePath = event.data.name;<br>    const bucketName = event.data.bucket;<br>    // 3.<br>    if (event.data.name.includes(&quot;&lt;collectionName&gt;/&quot;)) {<br>        const docCollection = event.data.name.split(&quot;/&quot;)[0];<br>        const docId = event.data.name.split(&quot;/&quot;)[1];<br>        const fileRef = getStorage().bucket(bucketName).file(filePath);<br><br>        // TODO: check if running on emulator<br>        <br>        //4.<br>        const mediaUrl = await getDownloadURL(fileRef);<br>        return await admin.firestore().doc(`${docCollection}/${docId}`).set({ &quot;mediaUrl&quot;: mediaUrl }, { merge: true });<br>    }<br>    return null;<br>})</pre><p>Here’s what happens in this code snippet:</p><ol><li>If event.data is null, then return null.</li><li>If contentType is of application/octet-stream (indicating that the file is a stream of binary data for which the actual type is unknown or unspecified), then return null.</li><li>Check if the file is uploaded to &lt;collectionName&gt;/ directory, If it is, retrieve the document collection and the documentId, and then generate a file storage reference.</li><li>Retrieve the download URL for the generated file reference using the getDownloadURL(file:) function, and then set this URL in the document.</li></ol><p>If you attempt to run the code on the Emulator, the following error will be thrown:</p><pre>Error: Permission denied. No READ permission.</pre><h4>Emulator Limitations</h4><p>The reason for this error is that the <strong>Firebase</strong> emulators are designed for local testing of <strong>Firebase</strong> applications, focusing on security rules and basic interactions. Some features, such as getDownloadURL(), may not be supported.</p><p>A workaround solution: unlike getDownloadURL(), publicUrl() is supported in <strong>Firebase Emulator</strong>, however, it does not contain a token, making it a good option for the local testing environment, but not recommended for production.</p><p>Replace // <strong>TODO</strong>: check if running on emulator comment with the following code, which checks if the user environment running in the <strong>Emulator</strong>, and then generate publicURL() instead:</p><pre>if (process.env.FUNCTIONS_EMULATOR) {<br>    console.log(&quot;Emulator detected. Switching to publicUrl.&quot;)<br>    const publicUrl = fileRef.publicUrl()<br>    return await admin.firestore().doc(`${docCollection}/${docId}`).set({ &quot;mediaUrl&quot;: publicUrl }, { merge: true });<br>}</pre><h4>onObjectDeleted</h4><p>Add the following onFileDeleted trigger function that handles object deletion in <strong>Cloud Storage</strong>:</p><pre>export const onFileDeleted = onObjectDeleted(async (event) =&gt; {<br>    if (event.data.name.includes(&quot;&lt;collectionName&gt;/&quot;)) {<br>        const docCollection = event.data.name.split(&quot;/&quot;)[0];<br>        const docId = event.data.name.split(&quot;/&quot;)[1];<br>        return await admin.firestore().doc(`${docCollection}/${docId}`).set({&quot;mediaUrl&quot;: null}, {merge: true})    <br>    }<br>    return null;<br>})</pre><p>Here’s what happens in this code snippet:</p><ol><li>Check if the file is deleted from &lt;collectionName&gt;/ directory, then retrieve the document collection and the documentId.</li><li>Update mediaUrl with null in the document.</li></ol><h4>Using Signed URL</h4><p>Using signedUrl() requires that Firebase Admin SDK to be initialized with a service account key that includes the client_email and the private_key fields, if Firebase Admin SDK is not properly initialized with the necessary credentials, the following error will be thrown:</p><pre>Error: Cannot sign data without client_email.</pre><p>Service account key can be downloaded form <strong>Firebase</strong> and saved securely in your project.</p><h4><strong>Obtain a Firebase service account key</strong></h4><p>In <a href="https://console.firebase.google.com/">Firebase Console</a>, select your project, navigate to Project settings, and select Service accounts tab, with Firebase Admin SDK selected, it will look like follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgxwkB8imYw0IdQc_quZuw.png" /><figcaption><strong>Firebase Admin SDK</strong></figcaption></figure><p>Click on <strong>Generate new private key</strong>, you will be presented with the following warning, click on <strong>Generate key</strong> to download the JSON file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fr281ZuSnHo2VW38GqtcLQ.png" /><figcaption>Generate new private key</figcaption></figure><p>Create a new directory named secure under the functions directory, place the downloaded JSON file into the newly created secure directory, rename the JSON file to <em>serviceAccountKey.json. </em>Your project structure should look like this:</p><p>MyAwesomeApp/<br>├─ AndroidApp/<br>├─ iOSApp/<br>├─ CloudFunctions/<br>│ ├─ functions/<br>│ │ ├─ secure/<br>│ │ │ ├─ serviceAccountKey.json/</p><blockquote>Remember to add secure/ to your gitignore before committing your code.</blockquote><h4><strong>Initialize Firebase Admin SDK with the service account key</strong></h4><p>Update the code to initialize the Firebase Admin SDK with serviceAccountKey.json file. Replace admin.initializeApp() with the following:</p><pre>// 1.<br>let serviceAccountPath = &#39;../secure/serviceAccountKey.json&#39;;<br><br>// 2.<br>if (admin.apps.length === 0) {<br>    admin.initializeApp({<br>        // 3. <br>        credential: admin.credential.cert(require(serviceAccountPath)),<br>        storageBucket: &#39;your-storage-bucket-url&#39;<br>    });<br>}</pre><p>Here’s what happens in this code snippet:</p><ol><li>Create path to Firebase service account key file.</li><li>Check if the Firebase Admin SDK has not been initialized.</li><li>Initialize the Firebase Admin with the service account key, and storageBucket.</li></ol><blockquote>Make sure to replace your-storage-bucket-url with your actual Firebase Storage bucket URL.</blockquote><p>Add the following variable to toggle between using getDownloadURL, and getSignedUrl, (created for this article purposes only):</p><pre>const useSignedUrl = true;</pre><p>Go back to onFileFinalized trigger function and replace the code starting form if (process.env.FUNCTIONS_EMULATOR), with the following:</p><pre>if (!useSignedUrl) {<br>    if (process.env.FUNCTIONS_EMULATOR) {<br>        console.log(&quot;Emulator detected. Switching to publicUrl.&quot;)<br>        const publicUrl = fileRef.publicUrl()<br>        console.log(&quot;Public URL: &quot;, publicUrl)<br>        return await admin.firestore().doc(`${docCollection}/${docId}`).set({ &quot;mediaUrl&quot;: publicUrl }, { merge: true });<br>    }<br><br>    const mediaUrl = await getDownloadURL(fileRef)<br>    console.log(&quot;Download URL: &quot;, mediaUrl)<br>    return await admin.firestore().doc(`${docCollection}/${docId}`).set({ &quot;mediaUrl&quot;: mediaUrl }, { merge: true });<br>}<br><br>try {<br>    const options: any = {<br>        version: &#39;v4&#39;, // Use version 4 signing process<br>        action: &#39;read&#39;, // Specify the action (read, write, delete, etc.)<br>        expires: Date.now() + 15 * 60 * 1000, // 15 minutes from now<br>    };<br>    const [mediaUrl] = await fileRef.getSignedUrl(options)<br>    console.log(&quot;Signed URL: &quot;, mediaUrl)<br>    return await admin.firestore().doc(`${docCollection}/${docId}`).set({ &quot;mediaUrl&quot;: mediaUrl }, { merge: true });<br>} catch (error) {<br>    console.error(&quot;Error generating signed URL: &quot;, error);<br>}</pre><blockquote>Keep in mind that the maximum allowed expiration date is seven days ahead (604800 seconds).</blockquote><p>Unlike getDownloadURL(file:), getSignedUrl(options:) is supported in Firebase Emulator, so you can test it in the Emulator.</p><h4>Test it out</h4><p>Change useSignedUrl to false to test getDownloadURL(), then run the emulators to test storage triggers. Considering the example of books/&lt;DocumentID&gt; as the path for both Firestore document path and file storage folder path. Navigate to the <strong>Storage</strong> emulator, and click on <strong><em>Upload File</em></strong> to add a new file, next navigate back to <strong>Firestore</strong> emulator, where you’ll a mediaUrl field created with the generated URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*Hj25CsMJ-gV4geiIA-utAA.gif" /><figcaption><strong>Adding file in Storage emulator</strong></figcaption></figure><p>Since we’re running on a local environment, the Public URL will be printed out in the console like follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMl3EimDfVzPAwcBSqVJqw.png" /><figcaption>Public URL printed in console.</figcaption></figure><p>Change useSignedUrl back to true to test getSignedUrl(), and test again. The Signed URL will be printed out in the console like follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MYC4vaw-pjPTgflIx621OA.png" /><figcaption>Signed URL printed in console.</figcaption></figure><p>In order to test getDownloadURL(), cloud functions must be deployed to Firebase. To do this, run the following command in the command line to deploy (you can find deploy script in package.json):</p><pre>npm run deploy</pre><p>After functions are successfully deployed to <strong>Firebase</strong>, go to the <strong>Firebase Console</strong> and navigate to the <strong>Functions</strong> section, where you’ll find all deployed functions like follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcMbpw6NqZPfwWQD_Kjrjg.png" /><figcaption><strong>Deployed Function in Firestore</strong></figcaption></figure><p>Go ahead and perform the same test you did previously in the emulators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*MNEOtn9EDtcxu1P6-ZzQ1Q.gif" /><figcaption><strong>Adding file in Firebase Storage</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kymmnyuxlCSPJNKm3pPSaQ.png" /><figcaption>Download URL printed out in Logs Explorer</figcaption></figure><p>Note: Remember to handle any errors or edge cases that may arise during the update process.</p><blockquote>As <strong>Linus Torvalds</strong> once said: “Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.”</blockquote><p>Enjoy Coding 👩🏻‍💻♡</p><h3>Resources</h3><ul><li><a href="https://github.com/marwaniaaj/FirebaseCloudFunctionsTriggers.git">GitHub - marwaniaaj/FirebaseCloudFunctionsTriggers: This project is demo on how to create cloud functions to handle events triggered by Firebase services, such as Authentication, Firestore, &amp; Storage triggers.</a></li><li><a href="https://firebase.google.com/docs/functions?authuser=0">Cloud Functions for Firebase</a></li><li><a href="https://stackoverflow.com/questions/42956250/get-download-url-from-file-uploaded-with-cloud-functions-for-firebase/56010225#56010225">Get Download URL from file uploaded with Cloud Functions for Firebase</a></li><li><a href="https://github.com/firebase/firebase-admin-node/issues/2344#issuecomment-2081689051">Firebase Admin SDK: getDownloadUrl - Permission denied. No READ permission · Issue #2344 · firebase/firebase-admin-node</a></li><li><a href="https://firebase.google.com/docs/extensions/official/delete-user-data">Using the Delete User Data extension | Firebase Extensions</a></li><li><a href="https://firebase.google.com/docs/admin/setup">Add the Firebase Admin SDK to your server</a></li></ul><blockquote>“ Everyone has something to learn. Everyone has something to teach.” ~ <a href="https://twitter.com/twostraws/status/1613922671523418117">Paul Hudson</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57d9a039bc7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebase-developers/firebase-cloud-functions-event-triggers-57d9a039bc7f">Firebase Cloud Functions Event Triggers</a> was originally published in <a href="https://medium.com/firebase-developers">Firebase Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Share Extension with Apple/Google Maps in SwiftUI]]></title>
            <link>https://blog.stackademic.com/share-extension-with-apple-google-maps-in-swiftui-d311e5871c08?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d311e5871c08</guid>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[share-extension]]></category>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[place-details-api]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 15:23:37 GMT</pubDate>
            <atom:updated>2024-06-11T09:06:54.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWUO5ZtIIVcXuhwdn4bNvQ.png" /></figure><h4><strong><em>The function of good software is to make the complex appear to be simple</em></strong></h4><h4>Learn how to share a location to SwiftUI app from Apple/Google Maps and retrieve location details.</h4><p>In this tutorial you will learn how to share a location from <strong>Apple</strong> and <strong>Google</strong> <strong>Maps</strong> to your app extension, fetch the location coordinates and details, &amp; limit app availability to only map locations and links.</p><h3>Add Share Extension</h3><p>In your project (or create project named <strong>LocationShare</strong> to follow along), add new target like follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GW844UQDoBboylBwQb7ITg.png" /><figcaption><strong>File → New → Target</strong></figcaption></figure><p>Select the <strong>Share Extension</strong>, and make sure the new extension is in the same project.</p><p>Click <strong>Finish</strong>, and when the <strong>Xcodes</strong> asks you to activate the scheme select activate. You will find the following group of files created for you in <strong>Extension</strong> folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*NiNPbzE53LyvP5vWr5IBNg.png" /></figure><p>In Info.plist, you will find that NSExtensionActivationRule has the default value of TRUEPREDICATE for easier debugging at the beginning, which means that the app extension availability is not limited to any type and that it will always be shown in the share sheet. We will modify that later to limit visibility with maps related types.</p><blockquote>Keep in mind that it is required by <strong>Apple</strong> to replace this value with a valid activation rules before submitting your app for review.</blockquote><figure><img alt="Info.plist with showing NSExtensionActivationRules with TRUEPREDICATE value" src="https://cdn-images-1.medium.com/max/1024/1*5JJQLJqB_uzRi4jeCyi16Q.png" /><figcaption>Info.plist</figcaption></figure><p>You can now run your app, or run extension directly on Safari like the following screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*aBC9Xrb63TqRcy9vX4IfMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*XWdHk94gEFVssUcOst5rvQ.png" /><figcaption>Select <strong>Extension</strong> scheme &amp; run it on <strong>Safari</strong>.</figcaption></figure><p>If you share from website, or select a text to share, or even share an image from <strong>Photos</strong>, the compose view will be presented as the following screenshots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z22NSpgpugGgzbRXWTiciA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Exv6C4AOYONS2ppHn407Zw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRMWtb4Wi1_ejbVflUN-0g.jpeg" /><figcaption>The default visibility for <strong>LocationShare</strong></figcaption></figure><h3>Configure View Controller</h3><p>Delete the created MainInterface.storyboard file, then in Info.plist remove NSExtensionMainStoryboard key and value, then add a new key NSExtensionPrincipalClass and set the value to<em> </em>&lt;ShareExtensionTarget&gt;.ShareViewController, like follows:</p><figure><img alt="Info.plist showing NSExtensionPrincipalClass with Extension.ShareViewController value" src="https://cdn-images-1.medium.com/max/1024/1*636_HZwiueg_9aCjqTMCyg.png" /><figcaption>Info.plist</figcaption></figure><ul><li>NSExtensionPrincipalClass is the custom class that implements an app extension’s primary view or functionality.</li><li>If the app extension’s Info.plist file contains both NSExtensionMainStoryboard and NSExtensionPrincipalClass keys, the system won’t load the extension.</li></ul><p>Next, go to the created ShareViewController.swift file, remove the default code and conform the ShareViewController class to UIViewController instead of SLComposeServiceViewController, then override the viewDidLoad() function.</p><pre>class ShareViewController: UIViewController {<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>    }<br>}</pre><p>Before modifying the activation rules, we need to check what types <strong>Apple &amp; Google Maps</strong> share to the app extension.</p><p>Inside the viewDidLoad() function, ensure that we have access to the shared extension items, otherwise dismiss the app extension’s view controller by calling completeRequest(returningItems:) on extensionContext instance.</p><pre>class ShareViewController: UIViewController {<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        guard<br>            let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem else {<br>            self.dismiss()<br>            return<br>        }<br>        print(extensionItem.attachments)<br>    }<br><br>    func dismiss() {<br>        self.extensionContext?.completeRequest(returningItems: [])<br>    }<br>}</pre><p>Set a breakpoint at the print statement, then run app extension directly on <strong>Maps</strong>, select any location, then share, and select <strong>your app</strong>, the following will be printed in the debug area:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*S5gkNo_frec8JbECs6VYIA.png" /><figcaption>Apple Maps attachments</figcaption></figure><p>Repeat the same step with <strong>Google Maps</strong>, the following will be printed in the debug area:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*gUSQ0TFBmdmhPy0NNo9seA.png" /><figcaption>Google Maps attachments</figcaption></figure><h4>What this means?</h4><p><strong>Apple Maps</strong> shares an array of NSItemProvider of different UTIs, a plain text of the location name, a URL of the location, and a com.apple.mapkit.map-item type, which can be decoded and used to fetch the location details.</p><p>While in devices running <em>iOS 17</em>, <strong>Google Maps</strong> share only a URL UTI, in devices running <em>iOS 16</em>, <strong>Google Maps</strong> shares an array of NSItemProvider of two UTIs, a url and a plain text.</p><p>Most <strong>Share Extension</strong> tutorials use the following statement to get the required itemProvider —and in most cases it works — , but in the case of using the <strong>Maps</strong>, this statement cannot be used because it only fetches the first itemProvider (which will be the plain text in this case), and we don’t want that.</p><pre>let itemProvider = extensionItem.attachments?.first</pre><h3>Activation Rules</h3><p>Now that you understand which UTIs are needed in this project, activation rules needs to be modified to allow only the required types for both <strong>Maps</strong>.</p><p>Open Info.plist as a source code, and inside string tag of NSExtensionActivationRule add the following predicate statement which checks that any attachment conforms to URL UTI that is not file URL, <strong>OR</strong> conform to com.apple.mapkit.map-item UTI:</p><pre>&lt;key&gt;NSExtensionActivationRule&lt;/key&gt;<br>&lt;string&gt;<br>    SUBQUERY(<br>        extensionItems,<br>        $extensionItem,<br>        SUBQUERY(<br>            $extensionItem.attachments,<br>            $attachment,<br>            SUBQUERY(<br>                $attachment.registeredTypeIdentifiers, $uti, $uti UTI-CONFORMS-TO &quot;public.url&quot;<br>                AND NOT $uti UTI-CONFORMS-TO &quot;public.file-url&quot;<br>            ).@count == $extensionItem.attachments.@count<br>        ).@count &gt;= 1<br>    ).@count &gt;= 1<br>    OR<br>    SUBQUERY(<br>        extensionItems,<br>        $extensionItem,<br>        SUBQUERY(<br>            $extensionItem.attachments,<br>            $attachment,<br>            ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO &quot;com.apple.mapkit.map-item&quot;<br>        ).@count &gt;= 1<br>    ).@count &gt;= 1<br>&lt;/string&gt;</pre><blockquote>This statement iterates over an array of <a href="https://developer.apple.com/documentation/foundation/nsextensionitem">NSExtensionItem</a> objects, and secondarily over the <a href="https://developer.apple.com/documentation/foundation/nsextensionitem/1416690-attachments">attachments</a> array in each extension item. For each attachment, the predicate evaluates the uniform type identifier (UTI) for each representation in the attachment. When an attachment representation UTI conforms to any of of two different specified UTIs (which you see on the right-hand side of each UTI-CONFORMS-TO operator), collect that UTI for the final comparison test. The final line returns TRUE if the app extension was given exactly one extension item attachment with a supported UTI.</blockquote><blockquote>During development only, you can use the TRUEPREDICATE constant (which always evaluates to true) as a stub predicate statement, to test your code path before you implement your predicate statement. ~ <a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html">App Extension Programming Guide</a></blockquote><p>Now you will notice that the app extension availability on the share sheet is limited to URLs and Maps.</p><h3>App Groups</h3><blockquote>An <strong>App Group</strong> allows multiple apps developed by the same team to access one or more shared containers. You can use an App Group to share data between an app extension and its host app. ~ <a href="https://developer.apple.com/documentation/xcode/configuring-app-groups">Configuring App Groups</a></blockquote><ul><li>The benefit of using App Group is not used in this tutorial, but if you’re using NSUserDefaults, CoreData, or SwiftData, it must be added and enabled.</li></ul><p>Go to <strong>Target → Signing &amp; Capabilities → + Capability → App Groups</strong>, enter name for the new app group like follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXm_9ZOogDZOdqsa5-HkSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*wWLPuVW7HgQ-U8Hdc4Uo3Q.png" /></figure><p>Repeat the same steps for <strong>Extension</strong> target, and select the previously created app group.</p><h3>Extract the Shared Data</h3><p>In the main extension of the project (LocationShare in this example), add new swift file named LocationItem.swift, make sure to check both targets for the new file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*pzt1kOE0ky7j8y1jcANPwA.png" /></figure><p>Then add the following code for LocationItem struct, that contain data structure for location data:</p><ol><li>name, address, phoneNumber, website are info you might need to present to the user.</li><li>placeId is retrieved from Place APIs, and can be used for geocoding, this value won’t be used in case of <strong>Apple Maps</strong>.</li><li>latitude, and longitude are the most important values that needs to be saved for the location.</li></ol><pre>import MapKit<br><br>struct LocationItem: Identifiable {<br>    var id: UUID? { UUID() }<br>    var name: String?<br>    var address: String<br>    var phoneNumber: String?<br>    var website: String?<br>    var placeId: String?<br>    var latitude: Double<br>    var longitude: Double<br><br>    var location: CLLocation {<br>        return CLLocation(latitude: latitude, longitude: longitude)<br>    }<br>    var locationName: String {<br>        return name ?? &quot;Undefined Location&quot;<br>    }<br>}</pre><p>Next, in Extension folder, add new file named ExtensionManager.swift, and add the following code:</p><pre>// 1.<br>enum ItemType {<br>    case appleMaps<br>    case googleMaps<br>    case link<br>    case undefined<br>}<br><br>class ExtensionManager: ObservableObject {<br>    static let shared = ExtensionManager()<br>    private let apiKey = &quot;&lt;YOUR_API_KEY&gt;&quot; // replace this<br><br>    // 2.<br>    func handleUrlType(for itemProvider: NSItemProvider) async -&gt; ItemType {<br>        do {<br>            // 3.<br>            let providedURL = try await itemProvider.loadItem(forTypeIdentifier: UTType.url.identifier, options: nil)<br>            guard let providedURL = providedURL as? URL else { return .undefined }<br>            if let host = providedURL.host(), host.contains(&quot;maps.app.goo.gl&quot;) {<br>                return .googleMaps<br>            }<br>            return .link<br>        }<br>        catch {<br>            // 4.<br>            print(&quot;Unable to load item. \(error.localizedDescription)&quot;)<br>            return .undefined<br>        }<br>    }<br>}</pre><p>Here’s what happens in this code snippet:</p><ol><li>Create ItemType enum, that contains different item types used in this tutorial.</li><li>Create handleUrlType(itemProvider:) function that takes NSItemProvider, and returns ItemType.</li><li>Load data for the given itemProvider, and check if URL host contains maps.app.goo.gl (which is the short URL shared from <strong>Google Maps</strong>), return googleMaps, otherwise return link.</li><li>If loading data from itemProvider failed, then return undefined.</li></ol><p>Next, inside the ExtensionManager class, add the following two functions that handle the shared data and return an optional LocationItem (we will implement these function later):</p><pre>func handleAppleMapsItem(_ mapItem: MKMapItem) async -&gt; LocationItem? {<br>    // TODO: Create LocationItem using given mapItem.<br>}<br><br>func handleGoogleUrl(_ shareUrl: URL) async -&gt; LocationItem? {<br>    // TODO: Fetch data using cid parameter.<br>}</pre><p>As previously mentioned, we need to get the itemProvider that contains data that conforms to com.apple.mapkit.map-item (for Apple Maps), if that isn&#39;t found, then we check for itemProvider that contains data that conforms to URL (for Google Maps &amp; URLs).</p><p>Go back to the ShareViewController class, and add the following functions after viewDidLoad():</p><pre>private func handleAttachments(_ attachments: [NSItemProvider]?) async {<br>    // 1.<br>    if let mapKitItem = attachments?.first(where: { $0.hasItemConformingToTypeIdentifier(&quot;com.apple.mapkit.map-item&quot;) }) {<br>        // 2.<br>        hostMapsShareView(itemProvider: mapKitItem, itemType: .appleMaps)<br>    }<br>    // 3.<br>    else if let googleMapItem = attachments?.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.url.identifier) }) {<br>        // 4.<br>        let itemType = await ExtensionManager.shared.handleUrlType(for: itemProvider)<br>        if itemType == .googleMaps {<br>            // 5.<br>            hostMapsShareView(itemProvider: itemProvider, itemType: .googleMaps)<br>        } else if itemType == .website {<br>            // TODO: Handle link url (will not be included in this tutorial)<br>        } else {<br>            // 6.<br>            self.dismiss()<br>        }<br>    }<br>}<br><br>private func hostMapsShareView(itemProvider: NSItemProvider, urlType: UrlType) {<br>    // 7.<br>    let hostingView = UIHostingController(rootView: MapsShareView(<br>                                    itemProvider: itemProvider,<br>                                    extensionContext: extensionContext,<br>                                    itemType: itemType))<br>    hostingView.view.frame = view.frame<br>    addChild(hostingView)<br>    view.addSubview(hostingView.view)<br><br>    hostingView.view.translatesAutoresizingMaskIntoConstraints = false<br>    hostingView.view.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true<br>    hostingView.view.bottomAnchor.constraint (equalTo: self.view.bottomAnchor).isActive = true<br>    hostingView.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true<br>    hostingView.view.rightAnchor.constraint (equalTo: self.view.rightAnchor).isActive = true<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Get the first attachment that contains data that conforms to com.apple.mapkit.map-item type (Apple Maps)</li><li>If found, then call hostMapsShareView(itemProvider:itemType:) and pass mapKitItem, and ItemType.appleMaps.</li><li>If not, get the first attachment that contains data that conforms to URL type (Google Maps &amp; URLs).</li><li>If found, then check for URL type for the itemProvider by calling the previously created function handleUrlType(for:) in the ExtensionManager class.</li><li>If itemType is .googleMaps, then call hostMapsShareView(itemProvider:itemType:) and pass googleMapItem, and ItemType.googleMaps. Otherwise handle shared URL.</li><li>If itemType is undefined then dismiss controller.</li><li>To integrate SwiftUI view in ShareViewController, create UIHostingController object to present MapShareView (will be created next), then add it to the controller’s view, and set up the constraints.</li></ol><p>Next, create new SwiftUI view named MapsShareView and add the following parameters, and dismiss function:</p><pre>struct MapsShareView: View {<br>    var itemProvider: NSItemProvider<br>    var extensionContext: NSExtensionContext?<br>    var itemType = ItemType.undefined<br><br>    @State private var locationItem: LocationItem? = nil<br><br>    /// body ...<br><br>    func dismiss() {<br>        extensionContext?.completeRequest(returningItems: [])<br>    }<br>}</pre><p>When hosting MapsShareView, using itemProvider, we want to extract data based on itemType (Apple or Google Maps).</p><p>After dismiss() function, add the following loadMapsData() function:</p><pre>func loadMapsData() async {<br>    do {<br>        // 1.<br>        if itemType == .appleMaps <br>           &amp;&amp; itemProvider.hasItemConformingToTypeIdentifier(&quot;com.apple.mapkit.map-item&quot;) {<br>            // 2.<br>            let item = try await itemProvider.loadItem(forTypeIdentifier: &quot;com.apple.mapkit.map-item&quot;)<br>            guard let data = item as? Data else { return }<br>            do {<br>                // 3.<br>                guard let mapItem = try NSKeyedUnarchiver.unarchivedObject(ofClass: MKMapItem.self, from: data as Data) else { return }<br>                // 4.<br>                locationItem = await ExtensionManager.shared.handleAppleMapsItem(mapItem)<br>            } catch {<br>                print(&quot;Error unarchiving mapItems. \(error)&quot;)<br>            }<br>        }<br>        // 5.<br>        else if itemType == .googleMaps <br>                &amp;&amp; itemProvider.hasItemConformingToTypeIdentifier(UTType.url.identifier) {<br>            // 6.<br>            let providedURL = try await itemProvider.loadItem(forTypeIdentifier: UTType.url.identifier)<br>            if let providedURL = providedURL as? URL {<br>                print(&quot;Provided URL: \(providedURL)&quot;)<br>                // 7.<br>                locationItem = await ExtensionManager.shared.handleGoogleUrl(providedURL)<br>            }<br>        }<br>    }<br>    catch {<br>        print(&quot;Error loading map item: \(error)&quot;)<br>    }<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Check if itemType is appleMaps, and itemProvider has data that conforms to com.apple.mapkit.map-item UTI.</li><li>If true, load data from itemProvider using com.apple.mapkit.map-item identifier, cast the retrieved NSSecureCoding item to Data.</li><li>Decode MKMapItem object graph from previously encoded data, using unarchivedObject(ofClass:from:).</li><li>Finally, send decoded mapItem to handleAppleMapsItem(mapItem:), to fetch LocationItem.</li><li>Check if itemType is googleMaps, and itemProvider has data that conforms to URL UTI.</li><li>if true, load data from itemProvider using URL type identifier, cast the retrieved NSSecureCoding item to URL.</li><li>Finally, send providedURL to handleGoogleUrl(shareUrl:), to fetch LocationItem.</li></ol><h4>Apple Maps</h4><p>Now, go back to ExtensionManager to implement handleAppleMapsItem(mapItem:).</p><p>Set a breakpoint in handleAppleMapsItem(mapItem:), and run app extension on <strong>Maps</strong>, I set the location here to <em>Apple Park</em>, if you print mapItem in the debug area, you will see the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojZWUx3V3p9olfoyyl2crQ.png" /><figcaption><strong>MKMapItem</strong></figcaption></figure><p>The given mapItem contains name, phone number, url, &amp; timezone. mapItem.placemark contains address, &amp; coordinates, so using given mapItem data to create LocationItem object as follows:</p><pre>func handleAppleMapsItem(_ mapItem: MKMapItem) async -&gt; LocationItem? {<br>    let appleMaps = LocationItem(<br>        name: mapItem.name,<br>        address: mapItem.placemark.title ?? &quot;Unidentified&quot;,<br>        phoneNumber: mapItem.phoneNumber,<br>        website: mapItem.url?.absoluteString,<br>        latitude: mapItem.placemark.coordinate.latitude,<br>        longitude: mapItem.placemark.coordinate.longitude<br>    )<br><br>    return appleMaps<br>}</pre><ul><li><em>Check </em><a href="https://developer.apple.com/documentation/mapkit/mkmapitem"><em>MKMapItem</em></a><em> and </em><a href="https://developer.apple.com/documentation/corelocation/clplacemark"><em>CLPlacemark</em></a><em> for more data.</em></li></ul><h4>Google Maps</h4><p>Handling shared item from <strong>Google Maps</strong> is a different scenario, the shared URL is shortened to the following form (which can be later converted to a longer URL):</p><pre>https://maps.app.goo.gl/rumaxHfoTS6Tmb1bA?g_st=com.devtutorial.LocationShare.Extension</pre><p>In order to request the details of a place that returns a json output, we’re going to use the following API form:</p><pre>https://maps.googleapis.com/maps/api/place/details/json?parameter</pre><p>As per documentation, place_id is a required parameter to request the details of a place, but since place_id is <em>not</em> available in the shared short URL, and <em>not</em> even when converted to the long URL, and after a lot of search, I found another undocumented parameter that can be used in this scenario, the cid parameter, and to get it, we need to convert the shared short URL back to long URL, and then extract cid from queryItems.</p><p>The following API form requests the details of a place by cid:</p><pre>https://maps.googleapis.com/maps/api/place/details/json?cid={CID}&amp;key={API_Key}</pre><p>In the ExtensionManager class, add the following functions:</p><ol><li>Create getLongerUrl(for:) function, that creates a <strong>HEAD</strong> request by specifying httpMethod of the URLRequest (which won’t download the URL content contrary to <strong>GET</strong>), the returned URLResponse from URLSession.data(for:) contains the requested full URL.</li><li>Then create extractCID(from:) function, that extracts the cid parameter from the given URL using URLComponents(url:) to parse the URL into their constituent parts.</li></ol><pre>private func getLongerUrl(for shareUrl: URL) async -&gt; URL? {<br>    do {<br>        let session = URLSession(configuration: .default)<br>        var urlRequest = URLRequest(url: shareUrl)<br>        urlRequest.httpMethod = &quot;HEAD&quot;<br><br>        let (_, response) = try await session.data(for: urlRequest)<br>        print(&quot;Full URL: \(response.url?.absoluteString ?? &quot;No URL found&quot;)&quot;)<br>        return response.url<br>    }<br>    catch {<br>        print(&quot;Error: \(error)&quot;)<br>        return nil<br>    }<br>}<br><br>private func extractCID(from googleURL: URL) -&gt; String? {<br>    guard let urlComponents = URLComponents(url: googleURL, resolvingAgainstBaseURL: true) else {<br>        return nil<br>    }<br><br>    let queryItems = urlComponents.queryItems<br>    if let ftid = queryItems?.first(where: {$0.name == &quot;ftid&quot;})?.value {<br>        let subString = ftid.components(separatedBy: &quot;:&quot;)<br>        if let cid = subString.last {<br>            print(&quot;CID: \(cid)&quot;)<br>            return cid<br>        }<br>    }<br>    return nil<br>}</pre><p>By setting a breakpoint and print queryItems, you will find the ftid parameter that contains two parts separated by a colon, the second part is the cid parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8kyp4RqEdfT9y2UXPsD0w.png" /><figcaption><strong>ftid &amp; cid parameters</strong></figcaption></figure><p>Now that we have the cid parameter, we can fetch location data, and create LocationItem object.</p><p>But before doing that, you need an <strong>API Key</strong> to be able to use Place Details APIs, follow the steps in the following link:</p><p><a href="https://developers.google.com/maps/documentation/places/ios-sdk/get-api-key">Get an API Key | Places SDK for iOS | Google for Developers</a></p><ul><li>In <strong>API restrictions</strong> section, make sure to select <strong>Places API</strong>, so make sure to enable Places API as well.</li><li>After creating the <strong>API</strong>, replace &lt;YOUR_API_KEY&gt; in the ExtensionManager class with the newly generated API key.</li></ul><p>Next, create fetchGoogleMapsData(cid:) function, that creates a <strong>GET</strong> request, and requests the details of a place, using the previously mentioned Place Details API by cid parameter:</p><pre>private func fetchGoogleMapsData(cid: String) async -&gt; LocationItem? {<br>    do {<br>        let placedDetailsURL = &quot;https://maps.googleapis.com/maps/api/place/details/json?cid=\(cid)&amp;key=\(apiKey)&quot;<br>        // 1.<br>        guard let url = URL(string: placedDetailsURL) else { return nil }<br>        let session = URLSession(configuration: .default)<br>        let (data, _) = try await session.data(for: URLRequest(url: url))<br><br>        // 2.<br>        guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {<br>            return nil<br>        }<br><br>        guard let result = json[&quot;result&quot;] as? [String: AnyObject] else {<br>            // 3.<br>            if let status = json[&quot;status&quot;] as? String, <br>               let errorMessage = json[&quot;error_message&quot;] as? String {<br>                print(&quot;\(status): \(errorMessage)&quot;)<br>            }<br>            return nil<br>        }<br>        guard let result_types = result[&quot;types&quot;] as? [String],<br>              let place_id = result[&quot;place_id&quot;] as? String,<br>              let geometry = result[&quot;geometry&quot;] as? [String: AnyObject],<br>              let location = geometry[&quot;location&quot;] as? [String: Double],<br>              let latitude = location[&quot;lat&quot;], let longitude = location[&quot;lng&quot;]<br>        else {<br>            return nil<br>        }<br><br>        let name = result[&quot;name&quot;] as? String<br>        let address = result[&quot;formatted_address&quot;] as? String<br>        let phone_number = result[&quot;international_phone_number&quot;] as? String<br>        let website = result[&quot;website&quot;] as? String<br><br>        // 4.<br>        let googleLocationItem = LocationItem(<br>            name: name, address: formatted_address,<br>            phoneNumber: phone_number, website: website, placeId: place_id, <br>            latitude: latitude, longitude: longitude, isGoogle: true<br>        )<br>        return googleLocationItem<br>    }<br>    catch {<br>        print(&quot;Error: \(error)&quot;)<br>        return nil<br>    }<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Using Place Details API, create URLRequest to retrieve the details of a place by cid, and apiKey.</li><li>Parse retrieved data to JSON, and check if it contains results dictionary field.</li><li>If json doesn’t contain results dictionary field, check for status and error_message fields to find out the error that occurred.</li><li>Create LocationItem object using returned values.</li></ol><p>Finally, replace <strong>// TODO:</strong> Fetch data using cid parameter. with the following code inside handleGoogleUrl(shareUrl:) function:</p><pre>func handleGoogleUrl(_ shareUrl: URL) async -&gt; LocationItem? {<br>    guard let fullUrl = await getLongerUrl(for: shareUrl) else { return nil }<br>    guard let cid = extractCID(from: fullUrl) else { return nil }<br>    guard let googleMapsData = await fetchGoogleMapsData(cid: cid) else { return nil }<br>    return googleMapsData<br>}</pre><ul><li>After a lot of testing, I found out that by using ftid as a parameter, the same result was retrieved from the Place Details API, the request looks like the following:</li></ul><pre>https://maps.googleapis.com/maps/api/place/details/json?ftid={ftid}&amp;key={API_Key}</pre><p>And so you can return &amp; use the ftid value instead without separating it by a colon to get the cid, like the following:</p><pre>if let ftid = queryItems?.first(where: {$0.name == &quot;ftid&quot;})?.value {<br>    return ftid<br>}</pre><h3>Present Location Details</h3><p>Now that we loaded shared extension items, retrieved the location data, and created LocationItem object from retrieved data, let’s present the data to the user. Add the following code inside body in MapsShareView:</p><pre>struct MapsShareView: View {<br>    /// properties ...<br><br>    var body: some View {<br>        NavigationStack {<br>            VStack(spacing: 16) {<br>                Image(systemName: &quot;map.fill&quot;)<br>                    .font(.system(size: 80))<br>                    .foregroundStyle(Color.accentColor)<br>                    .padding(16)<br><br>                if let locationItem {<br>                    VStack(alignment: .leading, spacing: 8) {<br>                        Text(locationItem.locationName)<br>                            .font(.title3).bold()<br>                            .foregroundStyle(Color.accentColor)<br><br>                        VStack(alignment: .leading, spacing: 4) {<br>                            if let address = locationItem.address {<br>                                HStack(alignment: .firstTextBaseline) {<br>                                    Image(systemName: &quot;mappin&quot;).padding(8)<br>                                        .foregroundStyle(Color.accentColor)<br>                                    Text(address)<br>                                }<br>                            }<br><br>                            if let phone = locationItem.phoneNumber {<br>                                HStack(alignment: .firstTextBaseline) {<br>                                    Image(systemName: &quot;phone.fill&quot;).padding(8)<br>                                        .foregroundStyle(Color.accentColor)<br>                                    Text(phone)<br>                                }<br>                            }<br><br>                            if let website = locationItem.website {<br>                                HStack(alignment: .firstTextBaseline) {<br>                                    Image(systemName: &quot;safari.fill&quot;).padding(8)<br>                                        .foregroundStyle(Color.accentColor)<br>                                    Text(website)<br>                                }<br>                            }<br>                        }<br>                    }<br>                    .padding(.vertical)<br>                    .frame(maxWidth: .infinity, alignment: .leading)<br>                    Spacer()<br>                }<br>                else {<br>                    ProgressView()<br>                        .frame(maxWidth: .infinity, maxHeight: .infinity)<br>                }<br>            }<br>            .padding(10)<br>            .navigationTitle(&quot;Share Map Location&quot;)<br>            .navigationBarTitleDisplayMode(.inline)<br>            .toolbar {<br>                ToolbarItemGroup(placement: .topBarLeading) {<br>                    Button(&quot;Cancel&quot;, action: dismiss)<br>                        .font(.body).tint(.pink)<br>                }<br>            }<br>            .onAppear {<br>                Task {<br>                    await loadMapsData()<br>                }<br>            }<br>        }<br>    }<br><br>    /// functions ...<br>}</pre><h4>Take it for a spin</h4><p>Run Extension on <strong>Apple Maps</strong> and/or <strong>Google Maps</strong> and try different locations, feel free to run the app first and then go to Maps or Google Maps and share location to your app extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*qnRT2ASDFjhn3Ap9VxIHWQ.gif" /><figcaption>Sharing location to app extension</figcaption></figure><h4>Cost 💲</h4><blockquote>If you do not specify at least one field with a request, or if you omit the <strong>fields</strong> parameter from a request, ALL possible fields will be returned, and you will be billed accordingly. This applies only to Place Details requests. ~ <a href="https://developers.google.com/maps/documentation/places/web-service/details">Place Details</a></blockquote><p>There is cost involved in using <strong>Place Details API</strong>, and by specifying the required fields, the cost can be reduced. In this tutorial request the details of a place by cid, and include types, name, formatted_address, international_phone_number, website, place_id, &amp; geometry</p><pre>https://maps.googleapis.com/maps/api/place/details/json<br>    ?fields=types,name,formatted_address,international_phone_number,<br>    website,place_id,geometry<br>    &amp;cid={CID}<br>    &amp;key={API_Key}</pre><p>Check out the following link for more information about usage and billing:</p><p><a href="https://developers.google.com/maps/documentation/places/web-service/usage-and-billing">Places API Usage and Billing | Google for Developers</a></p><h4>And Voilà! 🎉</h4><p>With that you are able to share any location coordinates and details from Apple and Google Maps to your app.<br>Feel free to add/remove fields and make changes that is custom to your needs.</p><blockquote>Enjoy coding 👩🏻‍💻📲</blockquote><h3>Resources</h3><ul><li><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html">Handling Common Scenarios</a></li><li><a href="https://medium.com/@henribredtprivat/create-an-ios-share-extension-with-custom-ui-in-swift-and-swiftui-2023-6cf069dc1209">Create an iOS Share Extension with custom UI in Swift and SwiftUI (2023)</a></li><li><a href="https://developers.google.com/maps/documentation/places/web-service/details">Place Details | Places API | Google for Developers</a></li></ul><blockquote>You can find the project’s full source code on <a href="https://github.com/marwaniaaj/LocationShareSwiftUI.git">GitHub</a> 🚀<br>If you liked this, don’t forget to 👏 and follow 😍.<br>Feedbacks are most welcome, drop them below in the comments section.</blockquote><blockquote><em>“ Everyone has something to learn. Everyone has something to teach.” ~ </em><a href="https://twitter.com/twostraws/status/1613922671523418117"><em>Paul Hudson</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d311e5871c08" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/share-extension-with-apple-google-maps-in-swiftui-d311e5871c08">Share Extension with Apple/Google Maps in SwiftUI</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase Authentication in Jetpack Compose apps]]></title>
            <link>https://blog.stackademic.com/firebase-authentication-in-jetpack-compose-c0584d5d6a03?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0584d5d6a03</guid>
            <category><![CDATA[firebaseauth]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[google-sign-in]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 10:17:02 GMT</pubDate>
            <atom:updated>2024-07-09T10:55:24.273Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZ2xHxOeR6UMWit9E-7TGQ.png" /></figure><h4>The function of good software is to make the complex appear to be simple</h4><h3>Firebase Authentication in Jetpack Compose</h3><h4>Learn how to implement guest account, authenticate user with Google, handle auth errors, delete user account, and revoke access token.</h4><p>In this tutorial series you will learn how to integrate the <strong>Firebase</strong> SDK with a Jetpack Compose project using the Firebase Android <strong>BoM</strong>, implement single sign on using Firebase Authentication through <strong>Google</strong> service provider, as well Anonymous Authentication, and <strong>link</strong> between them, handle common Auth errors, and finally delete <strong>Firebase</strong> user account, and revoke <strong>Google</strong> refresh &amp; access tokens.</p><h4>This tutorial series contains 5 parts:</h4><ol><li><a href="https://medium.com/firebase-developers/add-firebase-to-jetpack-compose-project-9e75a860ceba">Add Firebase SDK</a>: <br>Learn how to add <strong>Firebase</strong> SDK to a <strong>Jetpack Compose</strong> project using Firebase Android <strong>BoM</strong>.</li><li><a href="https://medium.com/firebase-developers/firebase-authentication-in-jetpack-compose-part-1-73cb79d3e744">Firebase Anonymous Authentication</a>: <br>Learn how to implementing guest accounts with <strong>Firebase</strong> Anonymous Authentication.</li><li><a href="https://medium.com/firebase-developers/firebase-authentication-in-jetpack-compose-part-2-c2a766aa5b52">Google Sign-In Authentication</a>: <br>Learn how to authenticate user with <em>Sign in with </em><strong><em>Google</em></strong> and <strong>Firebase</strong> Authentication.</li><li><a href="https://medium.com/firebase-developers/firebase-authentication-in-jetpack-compose-part-3-42d2f219dad9">Handle Firebase Authentication Errors</a>:<br>Learn how to handle <strong>Firebase</strong> Auth Errors when working with <strong>Firebase</strong> Authentication.</li><li><a href="https://medium.com/@marwa.diab/deleting-user-account-revoke-access-token-in-jetpack-compose-7e9e58ddbb02">Deleting User Account &amp; Revoke Access Token</a>:<br>Learn how to delete <strong>Firebase</strong> user, and revoke <strong>Google</strong> access tokens, and check for revoked tokens.</li></ol><h4>Full source code on GitHub 🚀</h4><p><a href="https://github.com/marwaniaaj/AuthLoginJetpackCompose.git">GitHub - marwaniaaj/AuthLoginJetpackCompose: This project is demo on how to use Firebase Authentication in Jetpack Compose project</a></p><blockquote>“ Everyone has something to learn. Everyone has something to teach.” ~ <a href="https://twitter.com/twostraws/status/1613922671523418117">Paul Hudson</a></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0584d5d6a03" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/firebase-authentication-in-jetpack-compose-c0584d5d6a03">Firebase Authentication in Jetpack Compose apps</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deleting User Account & Revoke Access Token in Jetpack Compose apps]]></title>
            <link>https://medium.com/firebase-developers/deleting-user-account-revoke-access-token-in-jetpack-compose-7e9e58ddbb02?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e9e58ddbb02</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[delete-user]]></category>
            <category><![CDATA[firebaseauth]]></category>
            <category><![CDATA[revoke-token]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 14:42:09 GMT</pubDate>
            <atom:updated>2024-04-04T14:56:23.331Z</atom:updated>
            <content:encoded><![CDATA[<h4>Firebase Authentication in Jetpack Compose</h4><h3>Deleting User Account &amp; Revoke Access Token</h3><h4>Learn how to delete Firebase user, and revoke Google access tokens, and check for revoked tokens.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KzH8YTOlJxAO0Sf0" /><figcaption>Photo by <a href="https://unsplash.com/@sepoys?utm_source=medium&amp;utm_medium=referral">Rohit Tandon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the previous parts of this series, we implemented</p><ul><li><a href="https://medium.com/@marwa.diab/firebase-authentication-in-jetpack-compose-part-1-73cb79d3e744">Firebase Anonymous Authentication</a></li><li><a href="https://medium.com/@marwa.diab/firebase-authentication-in-jetpack-compose-part-2-c2a766aa5b52">Google Sign-In Authentication</a></li><li><a href="https://medium.com/@marwa.diab/firebase-authentication-in-jetpack-compose-part-3-42d2f219dad9">Handle Firebase Authentication Errors</a></li></ul><h3>Account Deletion Requirement</h3><p>Google has added a new requirement in the <strong>Account Deletion Requirement </strong>section that requires you to offer an account deletion flow in your app if your app allows users to create accounts.</p><h4>Google</h4><blockquote>If your app allows users to create an account from within your app, our <a href="https://support.google.com/googleplay/android-developer/answer/13316080">User data</a> policy requires that it must also allow users to request for their account to be deleted.</blockquote><blockquote>When you delete an app account based on a user’s request, you must also delete the user data associated with that app account.</blockquote><h4>Google Play Services</h4><blockquote>Applications are required to provide users that are signed in with Google the ability to disconnect their Google account from the app. If the user deletes their account, you must delete the information that your app obtained from the Google APIs. ~ <a href="https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInClient#public-taskvoid-revokeaccess">GoogleSignInClient</a></blockquote><h3>Prepare Authorization Request</h3><p>In HomeScreen add the following code:</p><ol><li>Before the Scaffold, create a ManagedActivityResultLauncher to register a request, and the launch(signInResult:) function.</li><li>After the Scaffold add the OneTapSignIn composable.</li></ol><pre>// 1. <br>val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result -&gt;<br>    if (result.resultCode == Activity.RESULT_OK) {<br>        try {<br>            val credentials = authViewModel.oneTapClient.getSignInCredentialFromIntent(result.data)<br>            // TODO: Delete account<br>        }<br>        catch (e: ApiException) {<br>            Log.e(&quot;HomeScreen:Launcher&quot;,&quot;Re-auth error: $e&quot;)<br>        }<br>    }<br>}<br><br>fun launch(signInResult: BeginSignInResult) {<br>    val intent = IntentSenderRequest.Builder(signInResult.pendingIntent.intentSender).build()<br>    launcher.launch(intent)<br>}<br><br>/// Scaffold content...<br><br>// 2.<br>OneTapSignIn (<br>    launch = {<br>        launch(it)<br>    }<br>)</pre><p>This code snippet was previously explained in <a href="https://medium.com/@marwa.diab/firebase-authentication-in-jetpack-compose-part-2-c2a766aa5b52">Sign in with Google</a> part of this tutorial.</p><h4>Re-authentication requirement</h4><blockquote>Since deleting a user account is a security-sensitive operation, <strong>Firebase</strong> requires that the user has signed in recently. If you try to perform a security-sensitive operation and the user hasn’t signed in recently, <strong>Firebase</strong> will throw a <em>FirebaseAuthRecentLoginRequiredException</em> exception.</blockquote><blockquote>To prevent this, we’ll check if the user has signed-in in the past five minutes, if that’s not the case we will run a re-authentication flow.</blockquote><h3>Delete User Account</h3><p>Create new file named <strong><em>Date-isWithinPast</em></strong> in the <strong>Model</strong> folder and add the following function to Date extension:</p><pre>fun Date.isWithinPast(minutes: Int): Boolean {<br>    val now = Date()<br>    val timeAgo = Date(now.time - (60 * minutes * 1000))<br>    val range = timeAgo..now<br>    return range.contains(this)<br>}</pre><p>Next, In AuthRepositoryImpl add the following code:<br>(Remember to add the functions declaration in AuthRepository interface)</p><pre>// 1.<br>override fun checkNeedsReAuth(): Boolean {<br>    auth.currentUser?.metadata?.lastSignInTimestamp?.let { lastSignInDate -&gt;<br>        return !Date(lastSignInDate).isWithinPast(5)<br>    }<br>    return false<br>}<br><br>override suspend fun deleteUserAccount(googleIdToken: String?): DeleteAccountResponse {<br>    return try {<br>        auth.currentUser?.let { user -&gt;<br>            // 2.<br>            if (user.providerData.map { it.providerId }.contains(&quot;google.com&quot;)) {<br>                // 3. <br>                if (checkNeedsReAuth() &amp;&amp; googleIdToken != null) {<br>                    // TODO: Re-authenticate<br>                }<br>                // TODO: Revoke access<br>            }<br>            // 4. <br>            auth.currentUser?.delete()?.await()<br>            Response.Success(true)<br>        }<br>        Response.Success(false)<br>    }<br>    catch (e: Exception) {<br>        Response.Failure(e)<br>    }<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Check if the user has signed-in in the past five minutes.</li><li>Check if providerData contains <strong>Google</strong> providerId, then re-authenticate if required and revoke access token before deleting the user’s account.</li><li>In case re-authentication is required, and googleIdToken is available, run re-authentication flow, and then revoke the access token.</li><li>Delete Firebase Auth user account.</li></ol><blockquote>silentSignIn() restores a locally cached user so it does not send any server requests if the tokens haven&#39;t expired (less than an hour old).<br>When you force a sign out from <strong>Google</strong> Accounts you are invalidating the token on the server but the client doesn’t know until it requests new tokens.</blockquote><p>If the user deleted the connection between the app and his/her <strong>Google </strong>account — i.e. revoked access token — , it’s still possible to sign-in silently from the locally cached user, after <strong>one hour</strong> when silentSignIn() requests new token, it will throw an exception, and so initiating the sign-in flow is needed for re-authenticating the user.</p><h3>Re-authentication Flow</h3><p>Add the following authorizeGoogleSignIn() function in AuthRepositoryImpl, that will be used later in AuthViewModel, to determine whether to show the user the <strong>One Tap UI</strong> for re-authentication or not.</p><pre>override suspend fun authorizeGoogleSignIn(): String? {<br>    auth.currentUser?.let { user -&gt;<br>        if (user.providerData.map { it.providerId }.contains(&quot;google.com&quot;)) {<br>            try {<br>                // 1.<br>                val account = googleSignInClient.silentSignIn().await()<br>                // 2.<br>                return account.idToken<br>            } catch (e: ApiException) {<br>                Log.e(TAG, &quot;Error: ${e.message}&quot;)<br>            }<br>        }<br>    }<br>    return null<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Check the <strong>Google</strong> credential by calling silentSignIn() on GoogleSignInClient instance that returns the GoogleSignInAccount for the user who is signed in to the app.</li><li>Return idToken from retrieved account.</li><li>Return null otherwise.</li></ol><p>(At this point googleSignInClient is not defined yet, Unresolved reference: googleSignInClient, it will be fixed later)</p><p>Next, add the following reauthenticate(credential:) function to re-authenticate the user with <strong>Google</strong>:</p><ol><li>Using the given googleIdToken to create a fresh auth credential.</li><li>Then call user.reauthenticate(AuthCredential).</li></ol><pre>private suspend fun reauthenticate(googleIdToken: String) {<br>    // 1. <br>    val googleCredential = GoogleAuthProvider<br>        .getCredential(googleIdToken, null)<br>    // 2.<br>    auth.currentUser?.reauthenticate(googleCredential)?.await()<br>}</pre><p>Then replace <strong>// TODO: Re-authenticate</strong> in deleteUserAccount(googleIdToken:) with the following call:</p><pre>reauthenticate(googleIdToken)</pre><p>Next, in AuthViewModel add the following function:</p><pre>fun checkNeedsReAuth() = CoroutineScope(Dispatchers.IO).launch {<br>    // 1.<br>    if (repository.checkNeedsReAuth()) {<br>        // 2.<br>        val idToken = repository.authorizeGoogleSignIn()<br>        if (idToken != null) {<br>            deleteAccount(idToken)<br>        }<br>        else {<br>            // 3.<br>            oneTapSignIn()<br>            // 4.<br>            Log.i(&quot;AuthViewModel:deleteAccount&quot;,&quot;OneTapSignIn&quot;)<br>        }<br>    } else {<br>        // 1.<br>        deleteAccount(null)<br>    }<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Check if user needs re-authentication, if that’s not the case, then call deleteAccount(googleIdToken:) without passing value for credential.</li><li>Call authorizeGoogleSignIn() that was created earlier to fetch idToken, if available, call deleteAccount(googleIdToken:) and pass idToken.</li><li>If failed, initiate oneTapSignIn flow to create new authorization request.</li><li>deleteAccount(googleIdToken:) will be called from <strong>OneTap</strong> result callback.</li></ol><h3>Revoke Access Token</h3><p>Deleting the user’s access and refresh tokens is a very important step in the process of deleting the user from the app.</p><blockquote>When user signs in with <strong>Google</strong>, your app will receive an ID token with information about the user. Your app then will be listed in the third party apps &amp; services dashboard in user’s <strong>Google</strong> Account, in order for the app to be removed from this list, you will have to revoke any refresh tokens that are associated with it.</blockquote><h4>Implement access token revocation</h4><p>In AppModule add the following:</p><ol><li>provide a GoogleSignInOptions instance that will be used to get GoogleSignInClient.</li><li>provide a GoogleSignInClient instance that will be used to sign in silently and to revoke access token.</li></ol><pre>@Provides<br>fun provideGoogleSignInOptions(<br>    app: Application,<br>) = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)<br>    .requestIdToken(app.getString(R.string.web_client_id))<br>    .requestEmail()<br>    .build()<br><br>@Provides<br>fun provideGoogleSignInClient(<br>    app: Application,<br>    options: GoogleSignInOptions<br>) = GoogleSignIn.getClient(app, options)</pre><p>In AuthRepositoryImpl inject the following GoogleSignInClient parameter in constructor:</p><pre>private var googleSignInClient: GoogleSignInClient</pre><p>Then replace <strong>// TODO: Revoke</strong> in deleteUserAccount(googleIdToken:) with the following:</p><pre>googleSignInClient.revokeAccess().await()<br>oneTapClient.signOut().await()</pre><h3>Check Revoked Tokens</h3><p>Since the user can delete the access token from outside the app, from the third party apps &amp; services in the user’s <strong>Google</strong> account, so checking for revoked token is an important step upon app launch.</p><p>Add the following function in AuthRepositoryImpl:</p><pre>override suspend fun verifyGoogleSignIn(): Boolean {<br>    auth.currentUser?.let { user -&gt;<br>        val providersList = user.providerData.map { it.providerId }<br>        if (providersList.contains(&quot;google.com&quot;)) {<br>            return try {<br>                // 1.<br>                googleSignInClient.silentSignIn().await()<br>                true<br>            } catch (e: Exception) {<br>                // 2.<br>                signOut()<br>                false<br>            }<br>        }<br>    }<br>    return false<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Check the <strong>Google</strong> credential by calling silentSignIn() on GoogleSignInClient instance that returns the information for the user who is signed in to the app.</li><li>The attempt to sign in silently will fail if the user revoked authorization for the app, or the user’s credential is not found, so call signOut() function and return false.</li></ol><p>Next, In AuthViewModel, add the following in init after getAuthState():</p><pre>CoroutineScope(Dispatchers.IO).launch {<br>    repository.verifyGoogleSignIn()<br>}</pre><p>Then add the following functions:</p><pre>// 1.<br>fun checkNeedsReAuth() = CoroutineScope(Dispatchers.IO).launch {<br>    if (repository.checkNeedsReAuth()) {<br>        oneTapSignIn()<br>    } else {<br>        deleteAccount(null)<br>    }<br>}<br><br>// 2.<br>fun deleteAccount(googleIdToken: String?) = CoroutineScope(Dispatchers.IO).launch {<br>    DataProvider.deleteAccountResponse = Response.Loading<br>    DataProvider.deleteAccountResponse = repository.deleteUserAccount(googleIdToken)<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Check if user needs re-authentication, then run oneTapSignIn flow to create new authorization request, if that’s not the case, then call deleteAccount(googleIdToken:) without passing value for credential.</li><li>Using given credential, start deleting account process by calling deleteUserAccount(googleIdToken)on repository instance.</li></ol><h3>Delete Account Button</h3><p>Now that the delete user account code is ready, let’s implement the delete button in HomeScreen.</p><p>Inside HomeScreen, add the following property to show an AlertDialog to the user before deleting the account:</p><pre>val openDeleteAccountAlertDialog = remember { mutableStateOf(false) }</pre><p>Next, move the Sign Out button into a Row, and add the following Delete Account button after the Sign Out button, inside the Row.</p><pre>Row() {<br>    /// Sign-out button content...<br><br>    Button(<br>        onClick = {<br>            openDeleteAccountAlertDialog.value = true<br>        },<br>        modifier = Modifier<br>            .size(width = 200.dp, height = 50.dp)<br>            .padding(horizontal = 16.dp),<br>        shape = RoundedCornerShape(10.dp),<br>        colors = ButtonDefaults.buttonColors(<br>            containerColor = MaterialTheme.colorScheme.tertiary,<br>        )<br>    ) {<br>        Text(<br>            text = &quot;Delete Account&quot;,<br>            modifier = Modifier.padding(6.dp),<br>            color = Color.Red<br>        )<br>    }<br>}</pre><p>Next, add the following code for the AlertDialog, inside onClick block of confirmationButton, call authViewModel.checkNeedsReAuth() to start deleting user account process.</p><pre>AnimatedVisibility(visible = openDeleteAccountAlertDialog.value) {<br>    AlertDialog(<br>        onDismissRequest = {<br>            openDeleteAccountAlertDialog.value = false<br>        },<br>        title = { Text(&quot;Delete Account&quot;) },<br>        text = {<br>            Text(&quot;Deleting account is permanent. Are you sure you want to delete your account?&quot;)<br>        },<br>        confirmButton = {<br>            TextButton(<br>                onClick = {<br>                    authViewModel.checkNeedsReAuth()<br>                    openDeleteAccountAlertDialog.value = false<br>                }<br>            ) {<br>                Text(&quot;Yes, Delete&quot;, color = Color.Red)<br>            }<br>        },<br>        dismissButton = {<br>            TextButton(<br>                onClick = {<br>                    openDeleteAccountAlertDialog.value = false<br>                }<br>            ) {<br>                Text(&quot;Dismiss&quot;)<br>            }<br>        }<br>    )<br>}</pre><p>Go back to launcher, and replace <strong>// TODO: Delete account</strong> with the following:</p><pre>authViewModel.deleteAccount(credential.googleIdToken)</pre><h3>Force Refresh Auth Token</h3><h4>As mentioned earlier</h4><blockquote>When you force a sign out from <strong>Google</strong> Accounts you are invalidating the token on the server but the client doesn’t know until it requests new tokens.</blockquote><h4>Edge case</h4><p>If the user is signed in from two devices, and then deletes the account from one device, both the silentSignIn() and the AuthStateListener will retrieve the locally cached user (GoogleSignInAccount and FirebaseUser), and so the auth status will not be reflected on the second device (for an hour), in that case it’s better to force refresh the token to get the updated results.</p><h4>Solution</h4><p>To fix this call getIdToken(forceRefresh:) on currentUser instance to force a token refresh from the server, this function will throw an exception if the token is invalid and so the user will be signed out from the app.</p><p>Add the following verifyAuthTokenResult() function in AuthRepositoryImpl:</p><pre>private suspend fun verifyAuthTokenResult(): Boolean {<br>    return try {<br>        auth.currentUser?.getIdToken(true)?.await()<br>        true<br>    } catch (e: Exception) {<br>        Log.i(TAG, &quot;Error retrieving id token result. $e&quot;)<br>        false<br>    }<br>}</pre><p>Calling this function upon app launch loses the benefit of retrieving locally cached Auth user, that <strong>Firebase</strong> uses so it doesn’t send any server requests if the tokens haven’t expired yet, so it’s not a good practice to call it when the app starts.</p><p>Instead, one of the good practices is to save the user’s profile data in a document in the users collection in <strong>Firestore</strong>, including uid, email, name, creation date, last update date, (gender, age, birthdate — if required in the app).. etc, and retrieve the user’s document when auth state changes, inside the AuthStateListener callback.</p><p>When getting the user’s document in <strong>Firestore</strong>, check if the document exists, if the document <em>does not exist</em>, throw a FirestoreException with DocumentDoesNotExist message.</p><p>Then in the catch block of getUserDocument(user) call, catch the FirestoreException and check for DocumentDoesNotExist error, and call verifyAuthTokenResult() to force refresh auth token.</p><pre>val authStateListener = AuthStateListener { auth -&gt;<br>    auth.currentUser?.let { user -&gt;<br>        try {<br>            userRepository.getUserDocument(user).await()<br>        }<br>        catch (e: FirestoreException) {<br>            if (e.message == &quot;DocumentDoesNotExist&quot;) {<br>                Log.i(TAG, &quot;User Document Does Not Exist!&quot;)<br>                GlobalScope.launch(Dispatchers.IO) {<br>                    verifyAuthTokenResult()<br>                }<br>            }<br>        }<br>    }<br>    /// ...<br>}<br>/// ...</pre><p>That way the call to verifyAuthTokenResult() will <em>only</em> be initiated if you try to get the user’s document after it got deleted.</p><p>To learn how to use <strong>Delete User Data</strong> extension when deleting user’s account, check the following <strong>Firebase</strong> documentation:</p><p><a href="https://firebase.google.com/docs/extensions/official/delete-user-data">Using the Delete User Data extension | Firebase Extensions</a></p><p>Or follow the steps in the “<a href="https://youtu.be/U1PIrZBgv0U?t=662">Deleting the user’s data</a><em>”</em> section in the video tutorial by <a href="https://medium.com/@peterfriese">Peter Friese</a> on <a href="https://medium.com/@firebaseyt">Firebase</a> <strong>YouTube</strong> channel.</p><h4>Take it for a spin</h4><p>Run the app on your phone or on the Emulator. You should now be able to test all the different scenarios since most cases are handled, even the edge cases that might rarely happen — but it still could happen.</p><blockquote>As <strong>Doug Linder</strong> once said: “a good programmer is the kind of person who looks both ways before crossing a one-way street.”</blockquote><h3>Resources</h3><ul><li><a href="https://github.com/marwaniaaj/AuthLoginJetpackCompose">GitHub - marwaniaaj/AuthLoginJetpackCompose: This project is demo on how to use Firebase Authentication in Jetpack Compose project</a></li><li><a href="https://support.google.com/googleplay/android-developer/answer/13327111?sjid=15115276326768301116-EU#zippy=%2Care-there-any-circumstances-where-my-app-can-retain-certain-data-in-the-account-deletion-process">Understanding Google Play&#39;s app account deletion requirements</a></li><li><a href="https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInClient#revokeAccess()">GoogleSignInClient | Google Play services | Google for Developers</a></li><li><a href="https://firebase.google.com/docs/auth/android/manage-users#delete_a_user">Manage Users in Firebase | Firebase Authentication</a></li><li><a href="https://firebase.google.com/docs/extensions/official/delete-user-data">Using the Delete User Data extension | Firebase Extensions</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F664ep0WOgo8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D664ep0WOgo8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F664ep0WOgo8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e274652faf04393d1104ab0148d00549/href">https://medium.com/media/e274652faf04393d1104ab0148d00549/href</a></iframe><blockquote>“ Everyone has something to learn. Everyone has something to teach.” ~ <a href="https://twitter.com/twostraws/status/1613922671523418117">Paul Hudson</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e9e58ddbb02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebase-developers/deleting-user-account-revoke-access-token-in-jetpack-compose-7e9e58ddbb02">Deleting User Account &amp; Revoke Access Token in Jetpack Compose apps</a> was originally published in <a href="https://medium.com/firebase-developers">Firebase Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase Authentication in SwiftUI apps]]></title>
            <link>https://blog.stackademic.com/firebase-authentication-in-swiftui-apps-a828e804a80e?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a828e804a80e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[sign-in-with-apple]]></category>
            <category><![CDATA[google-sign-in]]></category>
            <category><![CDATA[firebaseauth]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 07:03:47 GMT</pubDate>
            <atom:updated>2024-03-15T01:00:44.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhhCGzoC66LVESlZQCHssQ.png" /></figure><h4><strong><em>The function of good software is to make the complex appear to be simple</em></strong></h4><h3>Firebase Authentication in SwiftUI</h3><h4>Learn how to implement guest account, authenticate user with Apple &amp; Google, handle auth errors, delete user account, and revoke access token.</h4><p>In this tutorial series you will learn how to integrate the <strong>Firebase</strong> SDK with a <strong>SwiftUI</strong> project using <strong>SPM</strong> (Swift Package Manager), implement single sign on using <strong>Firebase</strong> Authentication through different service providers (Anonymous, Apple, &amp; Google), and <strong>link</strong> between them, handle common Auth errors, and finally delete <strong>Firebase</strong> user account, and revoke <strong>Apple</strong>/<strong>Google</strong> refresh &amp; access tokens.</p><h4>Firebase Auth tutorial series</h4><ol><li><a href="https://medium.com/@marwa.diab/add-firebase-to-swiftui-project-5eab5af0562b">Add Firebase SDK</a>: <br>Learn how to integrate <strong>Firebase</strong> SDK with a <strong>SwiftUI</strong> project using SPM.</li><li><a href="https://medium.com/firebase-developers/firebase-authentication-in-swiftui-part-1-71a409108d9f">Firebase Anonymous Authentication</a>: <br>Learn how to implementing guest accounts with <strong>Firebase</strong> Anonymous Authentication.</li><li><a href="https://medium.com/firebase-developers/firebase-authentication-in-swiftui-part-2-fdd6ad6608f7">Google Sign-In Authentication</a>: <br>Learn how to authenticate user with <em>Sign in with </em><strong><em>Google</em></strong> and <strong>Firebase</strong> Authentication.</li><li><a href="https://medium.com/firebase-developers/firebase-authentication-in-swiftui-part-3-80be99dbc63d">Apple Authentication</a>: <br>Learn how to authenticate users with <em>Sign in with </em><strong><em>Apple</em></strong> and <strong>Firebase</strong> Authentication.</li><li><a href="https://medium.com/@marwa.diab/firebase-authentication-in-swiftui-part-4-d771a0a30c4c">Handle Firebase Authentication Errors</a>:<br>Learn how to handle <strong>Firebase</strong> Auth Errors when working with <strong>Firebase</strong> Authentication.</li><li><a href="https://medium.com/@marwa.diab/deleting-user-account-revoke-access-token-0e30d7a351bb">Deleting User Account &amp; Revoke Access Token</a>:<br>Learn how to delete <strong>Firebase</strong> user, and revoke <strong>Apple</strong> &amp; <strong>Google</strong> access tokens, and check for revoked tokens.</li></ol><h4>Full source code on GitHub 🚀</h4><p><a href="https://github.com/marwaniaaj/AuthLoginSwiftUI.git">GitHub - marwaniaaj/AuthLoginSwiftUI: This project is demo on how to use Firebase Authentication in SwiftUI project</a></p><blockquote>“ Everyone has something to learn. Everyone has something to teach.” ~ <a href="https://twitter.com/twostraws/status/1613922671523418117">Paul Hudson</a></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a828e804a80e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/firebase-authentication-in-swiftui-apps-a828e804a80e">Firebase Authentication in SwiftUI apps</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deleting User Account & Revoke Access Token in SwiftUI apps]]></title>
            <link>https://medium.com/firebase-developers/deleting-user-account-revoke-access-token-0e30d7a351bb?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e30d7a351bb</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firebaseauth]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 08:39:05 GMT</pubDate>
            <atom:updated>2024-06-11T08:26:10.558Z</atom:updated>
            <content:encoded><![CDATA[<h4>Firebase Authentication in SwiftUI</h4><h3>Deleting User Account &amp; Revoke Access Token</h3><h4>Learn how to delete Firebase users, and revoke Apple &amp; Google access tokens</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nEtQJJY_cROGNlXL" /><figcaption>Photo by <a href="https://unsplash.com/@plhnk?utm_source=medium&amp;utm_medium=referral">Paul Hanaoka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In previous parts of this series, we implemented</p><ul><li><a href="https://medium.com/firebase-developers/firebase-authentication-in-swiftui-part-1-71a409108d9f">Firebase Anonymous Authentication</a></li><li><a href="https://medium.com/firebase-developers/firebase-authentication-in-swiftui-part-2-fdd6ad6608f7">Google Sign-In Authentication</a></li><li><a href="https://medium.com/@marwa.diab/firebase-authentication-in-swiftui-part-3-80be99dbc63d">Apple Authentication</a></li><li><a href="https://medium.com/@marwa.diab/firebase-authentication-in-swiftui-part-4-d771a0a30c4c">Handle Firebase Authentication Errors</a></li></ul><h3>Account Deletion Requirement</h3><p>Apple has added a paragraph to the <strong>App Review Guidelines</strong> that requires you to offer an account deletion flow in your app if your app allows users to create accounts.</p><h4>Apple</h4><blockquote>Apps that support account creation must let users initiate deletion of their account within the app starting June 30, 2022, as described in <a href="https://developer.apple.com/app-store/review/guidelines/#5.1.1v">App Store Review Guideline 5.1.1(v)</a>.</blockquote><h4>Google</h4><blockquote>It is highly recommended that you provide users that signed in with Google the ability to disconnect their Google account from your app. If the user deletes their account, you must delete the information that your app obtained from the Google APIs.</blockquote><p>Feel free to check out the following video tutorial by <a href="https://medium.com/u/ea0b1eb1f5d2">Peter Friese</a> on the <a href="https://medium.com/u/33757dff064a">Firebase</a> YouTube channel, I highly recommend watching it to:</p><ol><li>Understand why it is required to re-authenticate before deleting the <strong>Firebase</strong> User account.</li><li>Setup <strong>Apple</strong> service and key identifiers for the token revocation.</li><li>How to install and use the <a href="https://extensions.dev/extensions/firebase/delete-user-data">Delete User Data Firebase extension</a>. (This part is not covered in this tutorial)</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FU1PIrZBgv0U&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DU1PIrZBgv0U&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FU1PIrZBgv0U%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6109a1f249b49debc4cb926fd10feafe/href">https://medium.com/media/6109a1f249b49debc4cb926fd10feafe/href</a></iframe><h4>As explained in the video</h4><blockquote>Since deleting a user account is a security-sensitive operation, Firebase requires that the user has signed in recently. If you try to perform a security-sensitive operation and the user hasn’t signed in recently, Firebase will throw a FIRAuthErrorCodeCredentialTooOld exception.</blockquote><blockquote>To prevent this, we’ll check if the user has signed-in in the past five minutes, if that’s not the case we will run a re-authentication flow.</blockquote><h3>Prepare Authorization Request</h3><p>Inside AppleSignInManager, add the following code to create a new <strong>AppleID</strong> authorization request, and start the specified authorization flows.</p><pre>class AppleSignInManager: NSObject {<br>    // class properties...<br><br>    private var continuation : CheckedContinuation&lt;ASAuthorizationAppleIDCredential, Error&gt;?<br><br>    func requestAppleAuthorization() async throws -&gt; ASAuthorizationAppleIDCredential {<br>        return try await withCheckedThrowingContinuation { continuation in<br>            self.continuation = continuation<br><br>            let appleIdProvider = ASAuthorizationAppleIDProvider()<br>            let request = appleIdProvider.createRequest()<br>            requestAppleAuthorization(request)<br><br>            let authorizationController = ASAuthorizationController(authorizationRequests: [request])<br>            authorizationController.delegate = self<br>            authorizationController.performRequests()<br>        }<br>    }<br>    // class content...<br>}</pre><p>Then, to handle the <strong>AppleID</strong> authorization response, add the following extension to the AppleSignInManager class that conforms to the ASAuthorizationControllerDelegate.</p><pre>extension AppleSignInManager: ASAuthorizationControllerDelegate {<br>    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {<br>        if case let appleIDCredential as ASAuthorizationAppleIDCredential = authorization.credential {<br>            continuation?.resume(returning: appleIDCredential)<br>        }<br>    }<br><br>    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {<br>        continuation?.resume(throwing: error)<br>    }<br>}</pre><p>Next, inside GoogleSignInManager, replace the signInWithGoogle() method that was previously implemented in <a href="https://medium.com/firebase-developers/firebase-authentication-in-swiftui-part-2-fdd6ad6608f7">Sign in with Google</a> with the following code:</p><pre>@MainActor <br>func signInWithGoogle() async throws -&gt; GIDGoogleUser? {<br>    if GIDSignIn.sharedInstance.hasPreviousSignIn() {<br>        do {<br>            try await GIDSignIn.sharedInstance.restorePreviousSignIn()<br>            // 1.<br>            return try await GIDSignIn.sharedInstance.currentUser?.refreshTokensIfNeeded()<br>        }<br>        catch {<br>            // 2.<br>            return try await googleSignInFlow()<br>        }<br>    } else {<br>        return try await googleSignInFlow()<br>    }<br>}<br><br>@MainActor <br>private func googleSignInFlow() async throws -&gt; GIDGoogleUser? {<br>    guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return nil }<br>    guard let rootViewController = windowScene.windows.first?.rootViewController else { return nil }<br><br>    let result = try await GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController)<br>    return result.user<br>}</pre><p>Here is what <em>changed</em> in this code snippet:</p><ol><li>After restoring the user’s sign-in, get a refreshed token by calling refreshTokensIfNeeded() in case the access token has expired.</li><li>If restorePreviousSignIn() failed, possibly because of a previous revocation of the access token, then initiate the sign-in flow.</li></ol><blockquote>restorePreviousSignIn() restores a locally cached user so it does not send any server requests if the tokens haven&#39;t expired (less than an hour old).<br>When you force a sign out from <strong>Google</strong> Accounts you are invalidating the token on the server but the client doesn’t know until it requests new tokens.</blockquote><p>If the user deleted the connection between the app and their <strong>Google</strong> account — i.e. revoked access token — , it’s still possible to retrieve the previous sign-in from the locally cached user. After one hour when restorePreviousSignIn() requests new token, it will throw &quot;invalid_grant&quot;: &quot;Token has been expired or revoked&quot; exception, and so initiating the sign-in flow is needed for re-authenticating the user.</p><h3>Delete User Account</h3><p>Create a new Swift file named AuthManager-DeleteAccount.swift in the Model folder, and add the following code:</p><pre>extension AuthManager {<br>    func deleteUserAccount() async throws {<br>        guard let user = Auth.auth().currentUser,<br>              let lastSignInDate = user.metadata.lastSignInDate else { return }<br>        // 1.<br>        let needsReAuth = !lastSignInDate.isWithinPast(minutes: 5)<br>        // 2.<br>        let providers = user.providerData.map { $0.providerID }<br><br>        do {<br>            if providers.contains(&quot;apple.com&quot;)  {<br>                // 3.<br>                let appleIDCredential = try await AppleSignInManager.shared.requestAppleAuthorization()<br>                // 4.<br>                if needsReAuth {<br>                    // TODO: Re-authenticate AppleID<br>                }<br>                // TODO: Revoke AppleID<br>            }<br>            if providers.contains(&quot;google.com&quot;) {<br>                // 4.<br>                if needsReAuth {<br>                    // TODO: Re-authenticate Google Account<br>                }<br>                // TODO: Revoke Google Account<br>            }<br>            // 5.<br>            try await user.delete()<br>            // 6.<br>            updateState(user: user)<br>        }<br>        catch {<br>            print(&quot;FirebaseAuthError: Failed to delete auth user. \(error)&quot;)<br>            throw error<br>        }<br>    }<br>}<br><br>extension Date {<br>    func isWithinPast(minutes: Int) -&gt; Bool {<br>        let now = Date.now<br>        let timeAgo = Date.now.addingTimeInterval(-1 * TimeInterval(60 * minutes))<br>        let range = timeAgo...now<br>        return range.contains(self)<br>    }<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Check if the user has signed-in in the past five minutes.</li><li>Fetch the list of providers the user used to sign in to the app. This list will be used to check which provider needs to be re-authenticated and revoked before deleting the user’s account.</li><li>In case the providers contain apple.com, request the <strong>AppleID</strong> credential by calling the previously created requestAppleAuthorization(), the returned appleIDCredential will be used to re-authenticate if required, and to revoke the <strong>AppleID</strong> token.</li><li>In case re-authentication is required, run the re-authentication flow for <strong>AppleID</strong>/<strong>Google</strong>, and then revoke the access token.</li><li>Delete the Firebase Auth user account.</li><li>Update authState to refresh the UI.</li></ol><p>Add the following AuthErrors enum in the same file, these error will be used later to display different error messages to the user.</p><pre>enum AuthErrors: Error {<br>    case ReauthenticateApple<br>    case ReauthenticateGoogle<br>    case RevokeAppleID<br>    case RevokeGoogle<br>}</pre><h3>Re-authentication Flow</h3><p>Add the following reauthenticateAppleID(_:for:) function to re-authenticate the user with <strong>AppleID</strong>:</p><ol><li>Get the identityToken from the given appleIDCredential, and the nonce used in the authorization flow.</li><li>Using the identityToken and the nonce from the provider to create a fresh credential and then call user.reauthenticate(with:).</li></ol><pre>private func reauthenticateAppleID(<br>    _ appleIDCredential: ASAuthorizationAppleIDCredential,<br>    for user: User<br>) async throws {<br>    do {<br>        // 1.<br>        guard let appleIDToken = appleIDCredential.identityToken else { return }<br>        guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else { return }<br>        let nonce = AppleSignInManager.nonce<br>        // 2. <br>        let credential = OAuthProvider.credential(<br>            withProviderID: &quot;apple.com&quot;,<br>            idToken: idTokenString,<br>            rawNonce: nonce<br>        )<br>        try await user.reauthenticate(with: credential)<br>    }<br>    catch {<br>        throw AuthErrors.ReauthenticateApple<br>    }<br>}</pre><p>Add the following reauthenticateGoogleAccount(for:) function to re-authenticate the user with <strong>Google</strong>:</p><ol><li>Get the googleUser by calling the signInWithGoogle(), and the idToken.</li><li>Using the idToken and the accessToken strings form the provider to create a fresh credential and then call user.reauthenticate(with:).</li></ol><pre>private func reauthenticateGoogleAccount(for user: User) async throws {<br>    do {<br>        // 1.<br>        guard let googleUser = try await GoogleSignInManager.shared.signInWithGoogle() else {<br>            return<br>        }<br>        guard let idToken = googleUser.idToken?.tokenString else { return }<br>        // 2.<br>        let credential = GoogleAuthProvider.credential(<br>            withIDToken: idToken,<br>            accessToken: googleUser.accessToken.tokenString<br>        )<br>        try await user.reauthenticate(with: credential)<br>    }<br>    catch {<br>        throw AuthErrors.ReauthenticateGoogle<br>    }<br>}</pre><h3>Revoke Access Token</h3><p>Deleting the user’s access and refresh tokens is a very important step in the process of deleting the user from the app.</p><h4>As Peter explained in the previously mentioned video</h4><blockquote>When user signs in with Apple, your app will receive an ID token with information about the user, along with an authorization code. Your app then will be listed in the user’s Apple ID dashboard, in order for the app to be removed from this list, you will have to revoke any refresh tokens that are associated with it.</blockquote><p>Same thing goes for <strong>Google Sign in</strong>, your app will be listed in the user’s third party apps &amp; services dashboard.</p><p>(Note: Make sure to follow the steps in the “<a href="https://youtu.be/U1PIrZBgv0U?t=360">Setting up Sign in with Apple for Token Revocation</a><em>”</em> part of the previously mentioned video.)</p><h4>Implement access token revocation</h4><p>Add the following revokeAppleIDToken(for:) function to revoke the user’s <strong>AppleID</strong> access token:</p><p>Using the authenticationCode from the given appleIDCredential to call revokeToken(withAuthorizationCode:) on auth object to revoke the <strong>AppleID</strong> tokens.</p><blockquote><strong>Firebase</strong> will retrieve the access token associated with this user and then call Apple’s token revocation endpoint to revoke the token.</blockquote><pre>private func revokeAppleIDToken(_ appleIDCredential: ASAuthorizationAppleIDCredential) async throws {<br>    guard let authorizationCode = appleIDCredential.authorizationCode else { return }<br>    guard let authCodeString = String(data: authorizationCode, encoding: .utf8) else { return }<br><br>    do {<br>        try await Auth.auth().revokeToken(withAuthorizationCode: authCodeString)<br>    }<br>    catch {<br>        throw AuthErrors.RevokeAppleID<br>    }<br>}</pre><p>Add the following revokeGoogleAccount() function to revoke the user’s <strong>Google</strong> access token:</p><p>Call disconnect() on GIDSignIn instance to sign the user out and disconnect their account and revoke tokens.</p><pre>private func revokeGoogleAccount() async throws {<br>    do {<br>        try await GIDSignIn.sharedInstance.disconnect()<br>    }<br>    catch {<br>        throw AuthErrors.RevokeGoogle<br>    }<br>}</pre><p>Finally, replace each <strong>// TODO</strong> in the deleteUserAccount() function with the corresponding function call, code should look like the following:</p><pre>if providers.contains(&quot;apple.com&quot;)  {<br>    let appleIDCredential = try await AppleSignInManager.shared.requestAppleAuthorization()<br><br>    if needsReAuth {<br>        try await reauthenticateAppleID(appleIDCredential, for: user)<br>    }<br>    try await revokeAppleIDToken(appleIDCredential)<br>}<br>if providers.contains(&quot;google.com&quot;) {<br>    if needsReAuth {<br>        try await reauthenticateGoogleAccount(for: user)<br>    }<br>    try await revokeGoogleAccount()<br>}</pre><h3>Check Revoked Tokens</h3><p>Since the user can delete the access token from outside the app (e.g., from the AppleID dashboard in the user’s <strong>AppleID</strong> account, or from the third party apps &amp; services in the user’s <strong>Google</strong> account), checking for revoked token is an important step upon app launch.</p><p><strong>Checking AppleID Credential</strong> was already implemented in <a href="https://medium.com/firebase-developers/firebase-authentication-in-swiftui-part-3-80be99dbc63d">Sign in with Apple</a> part of this tutorial series, but checking for the <strong>AppleID</strong> credential alone might lead to an unexpected results, for example if the user is signed in with <strong>Google</strong> only, the app will always sign out because the <strong>AppleID</strong> credential was not found!</p><p>The following code includes checking for both the <strong>AppleID</strong> and the <strong>Google</strong> credentials, and signs the user out only if both are not available or have been revoked.</p><pre>class AuthManager: ObservableObject {<br>    // ...<br><br>    private func verifySignInWithAppleID() async -&gt; Bool {<br>        let appleIDProvider = ASAuthorizationAppleIDProvider()<br><br>        guard let providerData = Auth.auth().currentUser?.providerData,<br>              let appleProviderData = providerData.first(where: { $0.providerID == &quot;apple.com&quot; }) else {<br>            return false<br>        }<br><br>        do {<br>            // 1. <br>            let credentialState = try await appleIDProvider.credentialState(forUserID: appleProviderData.uid)<br>            return credentialState != .revoked &amp;&amp; credentialState != .notFound<br>        }<br>        catch {<br>            return false<br>        }<br>    }<br><br>    private func verifyGoogleSignIn() async -&gt; Bool {<br>        guard let providerData = Auth.auth().currentUser?.providerData,<br>              providerData.contains(where: { $0.providerID == &quot;google.com&quot; }) else { return false }<br><br>        do {<br>            // 2.<br>            try await GIDSignIn.sharedInstance.restorePreviousSignIn()<br>            return true<br>        }<br>        catch {<br>            return false<br>        }<br>    }<br><br>    private func verifySignInProvider() async {<br>        guard let providerData = Auth.auth().currentUser?.providerData else { return }<br>        // 3. <br>        var isAppleCredentialRevoked = false<br>        var isGoogleCredentialRevoked = false<br><br>        if providerData.contains(where: { $0.providerID == &quot;apple.com&quot; }) {<br>            isAppleCredentialRevoked = await !verifySignInWithAppleID()<br>        }<br><br>        if providerData.contains(where: { $0.providerID == &quot;google.com&quot; }) {<br>            isGoogleCredentialRevoked = await !verifyGoogleSignIn()<br>        }<br><br>        // 4.<br>        if isAppleCredentialRevoked &amp;&amp; isGoogleCredentialRevoked {<br>            if authState != .signedIn {<br>                do {<br>                    try await self.signOut()<br>                }<br>                catch {<br>                    print(&quot;FirebaseAuthError: verifySignInProvider() failed. \(error)&quot;)<br>                }<br>            }<br>        }<br>    }<br>    // ...<br>}</pre><p>Here is what happens in this code snippet:</p><ol><li>Check the <strong>AppleID</strong> credentials using the credentialState(forUserID:) function that retrieves the state of the user identifier saved in provider data, the verifySignInWithAppleID() function will return false if the user revoked authorization for the app, or the user’s credential state is not found.</li><li>Check the <strong>Google</strong> credential by calling restorePreviousSignIn() on GIDSignIn instance to try to restore a previous user sign-in, the attempt to restore the previous user sign-in will fail if the user revoked authorization for the app, or the user’s credential is not found, so function will return false.</li><li>Create isAppleCredentialRevoked and isGoogleCredentialRevoked to check if the <strong>AppleID</strong>/<strong>Google</strong> tokens are revoked or not found.</li><li>If both tokens are not available, then sign out if the user is not signed out, or signed in anonymously.</li><li>Replace verifySignInWithAppleID() with verifySignInProvider() in init right after configureAuthStateChanges(). Make sure to put it inside Task { await }.</li></ol><h3>Delete Account Button</h3><p>Now that the delete user account code is ready, let’s implement the delete button in the HomeView.</p><p>Inside HomeView, add the following @State property to show a confirmationDialog to the user before deleting the account:</p><pre>@State private var showDeleteAccountAlert = false</pre><p>Next, move the Sign Out button into a HStack, and add the following Delete Account button after the Sign Out button, inside the HStack.</p><pre>HStack {<br>    // Sign out button... <br><br>    Button {<br>        showDeleteAccountAlert = true<br>    } label: {<br>        Text(&quot;Delete Account&quot;)<br>            .font(.body.bold())<br>            .frame(width: 150, height: 45, alignment: .center)<br>            .foregroundStyle(.red)<br>            .background(Color(.loginBlue))<br>            .cornerRadius(10)<br>    }<br>}</pre><p>Then, add the following code for the confirmationDialog, catch the AuthErrors thrown from the re-authenticating and the revoking, and present a descriptive message to the user explaining the issue and how to solve it.</p><pre>NavigationStack {<br>    // VStack content...<br>    .confirmationDialog(&quot;Delete Account&quot;, isPresented: $showDeleteAccountAlert) {<br>        Button(&quot;Yes, Delete&quot;, role: .destructive) {<br>            Task {<br>                do {<br>                    try await authManager.deleteUserAccount()<br>                }<br>                catch AuthErrors.ReauthenticateApple {<br>                    // AppleID re-authentication failed<br>                }<br>                catch AuthErrors.RevokeAppleID {<br>                    // AppleID token revocation failed<br>                }<br>                catch AuthErrors.ReauthenticateGoogle {<br>                    // Google re-authentication failed<br>                }<br>                catch AuthErrors.RevokeGoogle {<br>                    // Google token revocation failed<br>                }<br>                catch {<br>                    // Show generic error message<br>                }<br>            }<br>        }<br>    } message: {<br>        Text(&quot;Deleting account is permanent. Are you sure you want to delete your account?&quot;)<br>    }<br>}</pre><h3>Force Refresh Auth Token</h3><h4>As mentioned earlier</h4><blockquote>When you force a sign out from <strong>Google</strong> Accounts you are invalidating the token on the server but the client doesn’t know until it requests new tokens.</blockquote><h4>Edge case</h4><p>If the user is signed in using <strong>Google</strong> provider from two devices, and then deletes the account from one device, both the restorePreviousSignIn() and the auth().addStateDidChangeListener will retrieve the locally cached user (GoogleUser and AuthUser), and so the auth status will not be reflected on the second device (for an hour), in that case it’s better to force refresh the token to get the updated results.</p><h4>Solution</h4><p>To fix this call getIDTokenResult(forcingRefresh:) on currentUser instance to force a token refresh from the server, this function will throw the following exception if the token is invalid and so the user will be signed out from the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1a0XEeY2-uHT1PyE4CLQw.png" /><figcaption>ERROR_USER_NOT_FOUND</figcaption></figure><p>Add the following verifyAuthTokenResult() function in AuthManager:</p><pre>private func verifyAuthTokenResult() async -&gt; Bool {<br>    do {<br>        try await Auth.auth().currentUser?.getIDTokenResult(forcingRefresh: true)<br>        return true<br>    }<br>    catch {<br>        print(&quot;Error retrieving id token result. \(error)&quot;)<br>        return false<br>    }<br>}</pre><p>Calling this function upon app launch loses the benefit of retrieving locally cached Auth user that <strong>Firebase</strong> uses so it doesn’t send any server requests if the tokens haven’t expired yet, so it’s not a good practice to call it when the app starts.</p><p>Instead, one of the good practices is to save the user’s profile data in a document in the users collection in <strong>Firestore</strong>, including uid, email, name, creation date, last update date, (gender, age, birthdate — if required in the app).. etc, and retrieve the user’s document when auth state changes, inside the addStateDidChangeListener(_:) callback.</p><p>When getting the user’s document in <strong>Firestore</strong>, check if the document exists, if the document <em>does not exist</em>, throw a DocumentDoesNotExist exception.</p><pre>func getUserDocument(_ user: User) async throws -&gt; Bool {<br>    let userDocumentReference = db.collection(Collection.Users).document(user.uid)<br>    let document = try await userDocumentReference.getDocument()<br>    guard document.exists else {<br>        throw FirestoreErrors.DocumentDoesNotExist<br>    }<br>    // function content...<br>}</pre><p>Then in the catch block of getUserDocument(user) call, check for DocumentDoesNotExist error, and call verifyAuthTokenResult() to force refresh auth token.</p><pre>addStateDidChangeListener { auth, user in<br>    // ...<br>    if let user {<br>        do {<br>            try await firestore.getUserDocument(user)<br>        }<br>        catch FirestoreErrors.DocumentDoesNotExist {<br>            print(&quot;User Document Does Not Exist!&quot;)<br>            await verifyAuthTokenResult()<br>            return<br>        }<br>        catch {<br>            // Other errors<br>        }<br>    }<br>}</pre><p>That way the call to verifyAuthTokenResult() will only be initiated if you try to get the user’s document after it got deleted.</p><p>(Make sure to follow the steps in the “<a href="https://youtu.be/U1PIrZBgv0U?t=662">Deleting the user’s data</a><em>”</em> part of the previously mentioned video.)</p><h4>Take it for a spin</h4><p>Run the app on your phone or on the iOS Simulator. You should now be able to test all the different scenarios since most cases are handled, even the edge cases that might rarely happen — but it still could happen.</p><blockquote>As <strong>Doug Linder</strong> once said: “a good programmer is the kind of person who looks both ways before crossing a one-way street.”</blockquote><h3>Resources</h3><ul><li><a href="https://github.com/marwaniaaj/AuthLoginSwiftUI.git">GitHub - marwaniaaj/AuthLoginSwiftUI: This project is demo on how to use Firebase Authentication in SwiftUI project</a></li><li><a href="https://developers.google.com/identity/sign-in/ios/disconnect">Revoking access tokens and disconnecting the app | Authentication | Google for Developers</a></li><li><a href="https://github.com/google/GoogleSignIn-iOS/issues/346">GIDSignIn.sharedInstance.restorePreviousSignIn is not working as expected · Issue #346 · google/GoogleSignIn-iOS</a></li><li><a href="https://firebase.google.com/docs/auth/ios/apple#token_revocation">Authenticate Using Apple | Firebase</a></li><li><a href="https://developer.apple.com/news/?id=12m75xbj">Account deletion requirement starts June 30 - Latest News - Apple Developer</a></li></ul><blockquote>“ Everyone has something to learn. Everyone has something to teach.” ~ <a href="https://twitter.com/twostraws/status/1613922671523418117">Paul Hudson</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e30d7a351bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebase-developers/deleting-user-account-revoke-access-token-0e30d7a351bb">Deleting User Account &amp; Revoke Access Token in SwiftUI apps</a> was originally published in <a href="https://medium.com/firebase-developers">Firebase Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Alert in Jetpack Compose]]></title>
            <link>https://blog.stackademic.com/custom-alert-in-jetpack-compose-47c367879147?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/47c367879147</guid>
            <category><![CDATA[custom-controls]]></category>
            <category><![CDATA[alert-dialog-android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 14:14:17 GMT</pubDate>
            <atom:updated>2024-03-14T01:06:10.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*dxAeF2CMpV6zpVcJZpvTfA.png" /></figure><h4>Create custom &amp; reusable alert dialog that can be used in any Composable.</h4><p>I’v been working on a project recently and I’m implementing for both <strong>iOS </strong>and <strong>Android</strong>, and so when I create a custom view in <strong>SwiftUI</strong>, I try to implement the same look and feel in <strong>Jetpack compose</strong>. one of those views is the <strong>CustomAlert</strong>.</p><blockquote>If you want to read the <strong>SwiftUI</strong> version, check out this article 👇🏻:</blockquote><p><a href="https://medium.com/@marwa.diab/custom-alert-in-swiftui-df860da27e57">Custom Alert in SwiftUI</a></p><p>In this article we will explore how we can build our own customized and reusable <strong>CustomAlert</strong> composable.</p><p>Final output should look like the following 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*dxAeF2CMpV6zpVcJZpvTfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*7mQhCdC4FzaqrmDTvlCtYw.png" /><figcaption>Custom Alert</figcaption></figure><p>Feel free to download starter project <a href="https://github.com/marwaniaaj/CustomAlertJetpackCompose/tree/main">here</a>, if you want to follow along — it is just a simple MainScreen() composable to test our custom alert — , or make the changes in your own project.</p><h4>TL;TR;</h4><blockquote>If you don’t want the explanation part, feel free to jump to the end of the article, you will find the full source code, download or copy CustomAlert.kt and <em>CustomAlertDialog.kt</em> files and customize CustomAlert to match your app’s look and feel, or even add your ideas to match your need.</blockquote><h4>Let’s Start 👩🏻‍💻:</h4><p>❶ Create new Kotlin file named CustomAlert, create a generic @Composable function that takes the following parameters:</p><ol><li>title: String that describes the title of the alert.</li><li>message: String that describes the message for the alert.</li><li>actionText: String that describes the text of action button.</li><li>data: An optional value of generic type T, this data will populate the fields of an alert that will be displayed to the user.</li><li>showAlert: MutableState of Boolean value that determines whether to present the alert.</li><li>actionWithValue: The alert’s action given the currently available data.</li><li>action: The alert’s action without data.</li></ol><pre>@Composable<br>fun &lt;T&gt; CustomAlert(<br>    // 1.<br>    title: String, <br>    // 2.<br>    message: String,<br>    // 3.<br>    actionText: String,<br>    // 4.<br>    data: T?,<br>    // 5.<br>    showAlert: MutableState&lt;Boolean&gt;,<br>    // 6.<br>    actionWithValue: ((T) -&gt; Unit)?,<br>    // 7.<br>    action: (() -&gt; Unit)?,<br>) {<br>    // TODO: Alert<br>}</pre><p>In case data is <em>not</em> null, then we will return actionWithValue, otherwise, we will return action — without a value.</p><p>❷ Next, create new Kotlin file named CustomAlertDialog, create two @Composable functions, that will wrap CustomAlert in a Dialog.</p><p>𝟷 The first function will be generic, and will have data parameter of type T, and the action parameter of type (T) -&gt; Unit, note that action here is null.</p><p>𝟸 The second function will <em>not</em> have data, and action will be of type () -&gt; Unit, note that data and actionWithValue are both null here.</p><pre>@Composable<br>fun &lt;T&gt; CustomAlertDialog(<br>    title: String,<br>    message: String,<br>    actionText: String,<br>    data: T?,<br>    showAlert: MutableState&lt;Boolean&gt;,<br>    action: (T) -&gt; Unit<br>) {<br>    Dialog(<br>        onDismissRequest = { showAlert.value = false },<br>        properties = DialogProperties(usePlatformDefaultWidth = false)<br>    ) {<br>        CustomAlert(<br>            title = title, message = message, actionText = actionText,<br>            data = data, showAlert = showAlert,<br>            actionWithValue = action, action = null<br>        )<br>    }<br>}<br><br>@Composable<br>fun CustomAlertDialog(<br>    title: String,<br>    message: String,<br>    actionText: String,<br>    showAlert: MutableState&lt;Boolean&gt;,<br>    action: () -&gt; Unit<br>) {<br>    Dialog(<br>        onDismissRequest = { showAlert.value = false },<br>        properties = DialogProperties(usePlatformDefaultWidth = false)<br>    ) {<br>        CustomAlert(<br>            title = title, message = message, actionText = actionText,<br>            data = null, showAlert = showAlert,<br>            actionWithValue = null, action = action<br>        )<br>    }<br>}</pre><h4>Let’s continue with the UI</h4><p>❸ Inside CustomAlert composable, add the following:</p><pre>Column(<br>    modifier = Modifier.fillMaxSize(),<br>    verticalArrangement = Arrangement.Center,<br>    horizontalAlignment = Alignment.CenterHorizontally<br>) {<br>    Card(<br>        modifier = Modifier.padding(8.dp),<br>        shape = RoundedCornerShape(35.dp)<br>    ) {<br>        Column(<br>            modifier = Modifier<br>                .background(MaterialTheme.colorScheme.background)<br>                .padding(16.dp),<br>            verticalArrangement = Arrangement.spacedBy(16.dp),<br>            horizontalAlignment = Alignment.CenterHorizontally<br>        ) {<br>            // TODO: components<br>        }<br>    }<br>}</pre><p>Inside second Column, add the following:</p><pre>/// Title<br>Text(<br>    title,<br>    modifier = Modifier.fillMaxWidth(),<br>    color = AlertCyan, //--&gt; Color(0xFF47B0EC)<br>    fontWeight = FontWeight.Bold,<br>    style = MaterialTheme.typography.headlineMedium,<br>    textAlign = TextAlign.Center<br>)<br><br>/// Message<br>Text(<br>    message,<br>    modifier = Modifier<br>        .fillMaxWidth()<br>        .padding(vertical = 8.dp),<br>    fontSize = 19.sp,<br>    textAlign = TextAlign.Center,<br>    style = MaterialTheme.typography.titleLarge<br>)<br><br>// TODO: Add Buttons...</pre><p>Now, replace <strong>// TODO:</strong> Add Buttons… with the following Row containing cancel and action buttons:</p><p>In onClick of action button, if actionWithValue is <em>not</em> null, and we have data, return actionWithValue(data), otherwise return action().</p><pre>Row(<br>    modifier = Modifier.padding(16.dp).fillMaxWidth(),<br>    horizontalArrangement = Arrangement.spacedBy(8.dp),<br>    verticalAlignment = Alignment.CenterVertically<br>) {<br>    // Cancel button<br>    Button(<br>        onClick = { showAlert.value = false },<br>        modifier = Modifier<br>            .background(<br>                MaterialTheme.colorScheme.surface,<br>                shape = RoundedCornerShape(35.dp)<br>            )<br>            .height(55.dp)<br>            .weight(1f),<br>        colors = ButtonDefaults.buttonColors(<br>            containerColor = Color.Transparent<br>        ),<br>    ) {<br>        Text(<br>            text = &quot;Cancel&quot;, color = AlertCyan,<br>            fontWeight = FontWeight.SemiBold,<br>            style = MaterialTheme.typography.titleMedium<br>        )<br>    }<br><br>    // Action button<br>    Button(<br>        onClick = {<br>            showAlert.value = false<br><br>            /// Action...<br>            if (actionWithValue != null) {<br>                data?.let {<br>                    actionWithValue(data)<br>                }<br>            } else if (action != null) {<br>                action()<br>            }<br>        },<br>        modifier = Modifier<br>            .background(<br>                AlertCyan,<br>                shape = RoundedCornerShape(35.dp)<br>            )<br>            .height(55.dp)<br>            .weight(1f),<br>        colors = ButtonDefaults.buttonColors(<br>            containerColor = Color.Transparent,<br>        ),<br>    ) {<br>        Text(<br>            text = actionText,<br>            fontWeight = FontWeight.SemiBold,<br>            style = MaterialTheme.typography.titleMedium<br>        )<br>    }<br>}</pre><blockquote>Note: I’m using <em>data?.let { }</em> here, to guarantee returned data is <em>T</em> not <em>T?</em>, and if passed data is <em>null</em>, <em>action</em> block will not be performed.</blockquote><p>Now, the UI is ready…</p><p>❹ Go to MainScreen composable and replace <strong>// TODO: Show Book Alert</strong> with the following:</p><pre>CustomAlertDialog(<br>    &quot;Random Book&quot;,<br>    &quot;You have selected ${randomBook?.title} by ${randomBook?.author}&quot;,<br>    &quot;Yes, Done&quot;,<br>    data = randomBook,<br>    showAlert = showBookAlert,<br>) {<br>    selectedBook.value = it<br>}</pre><p>replace <strong>// TODO: Show Credits Alert</strong> with the following:</p><pre>CustomAlertDialog(<br>    &quot;Credits&quot;,<br>    &quot;This custom alert tutorial was implemented by Marwa&quot;,<br>    &quot;OK&quot;,<br>    showAlert = showCreditsAlert<br>) {<br>    // Some action here…<br>}</pre><p>Run code 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*nXfuMJyiW69EkWlCfbn0cQ.gif" /></figure><h4>Let’s add some animation ✨</h4><p>❺ In CustomAlert add the following:</p><ol><li>Create animateState variable of type MutableTransitionState with false initial state.</li><li>set targetState of animationState with showAlert value, and in order to run this only once when the composition starts, put it inside LaunchEffect(Unit).</li></ol><pre>@Composable<br>fun &lt;T&gt; CustomAlert(<br>    // parameters…<br>) {<br>    // 1.<br>    val animationState = remember { MutableTransitionState(false) }<br><br>    // Run only once<br>    LaunchedEffect(Unit) {<br>        // 2.<br>        animationState.targetState = showAlert.value<br>    }<br><br>    // Column content…<br>}</pre><p>Next, wrap Card with AnimatedVisibility, define slideInHorizontally for enter transition, and slideOutHorizontally for exit transition — feel free to choose whichever transition animation you like:</p><pre>AnimatedVisibility(<br>    animationState,<br>    enter = slideInHorizontally(<br>        animationSpec = tween(200)<br>    ),<br>    exit = slideOutHorizontally(<br>        animationSpec = tween(200)<br>    )<br>) {<br>    // Card content…<br>}</pre><p>Inside onClick of both buttons, add the following before showAlert.value = false:</p><pre>animationState.targetState = false</pre><p>Run code 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*TrcYG6jS8boJPt6tyXmyAA.gif" /></figure><p>As you can see alert is presented using the slideInHorizontally enter transition, but when alert is being dismissed, the slideOutHorizontally exit transition did not work.. that’s because we dismissed the alert before animation finishes by setting showAlert value to false.</p><p>To solve that first remove showAlert.value = false from onClick in both buttons, then after AnimatedVisibility, add the following:</p><ol><li>CurrentState changes after animation finishes.</li><li>Animation is completed when currentState is the same as targetState, and currentState is false.</li><li>Set showAlert to false to dismiss.</li></ol><pre>// 1.<br>LaunchedEffect(animationState.currentState) {<br>    // 2.<br>    if (!animationState.currentState &amp;&amp; animationState.targetState == animationState.currentState) {<br>        // 3.<br>        showAlert.value = false<br>    }<br>}</pre><p>Run code 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*0DKwNX2G9BFc7BxuLwEQ7g.gif" /></figure><p>Now the exit transition work correctly, but we want it to slide out to the other side, to do so add targetOffsetX in the exit transition like follows:</p><pre>exit = slideOutHorizontally(<br>    animationSpec = tween(200),<br>    targetOffsetX = { fullWidth -&gt; fullWidth }<br>)</pre><blockquote><strong>Note</strong>: animation transition seems sluggish on the <strong>Emulator</strong>, but it should look good on a real device.</blockquote><p>Run code 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*c6qxJe9Q0x0jK03wdT1bKw.gif" /></figure><h4>And Voilà! 🎉</h4><p>With that we’ve created custom, generic &amp; reusable alert dialog, with animation and transition.<br>Feel free to add any ideas and changes to make it custom to your needs.</p><blockquote>You can find the project’s full source code on <a href="https://github.com/marwaniaaj/CustomAlertJetpackCompose">GitHub</a> 🚀<br>If you liked this, don’t forget to 👏 and follow 😍.<br>Feedbacks are most welcome, drop them below in the comments section.</blockquote><blockquote><em>“ Everyone has something to learn. Everyone has something to teach.” ~ </em><a href="https://twitter.com/twostraws/status/1613922671523418117"><em>Paul Hudson</em></a></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47c367879147" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/custom-alert-in-jetpack-compose-47c367879147">Custom Alert in Jetpack Compose</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Alert in SwiftUI]]></title>
            <link>https://blog.stackademic.com/custom-alert-in-swiftui-df860da27e57?source=rss-ef56d0d0bdcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/df860da27e57</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[alerts]]></category>
            <category><![CDATA[custom]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Marwa Diab]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 13:02:26 GMT</pubDate>
            <atom:updated>2024-03-21T11:15:18.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*ybcqKegzrqzl18aHHWUiVQ.png" /></figure><h4>Create custom &amp; reusable alert that can be called from any View.</h4><p>The purpose of this tutorial is implement custom alert view and use it the same way you would use Apple’s <a href="https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:actions:message:)-3rabc">alert(_:isPresented:actions:message:)</a> and <a href="https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:message:)-8584l">alert(_:isPresented:presenting:actions:message:)</a> functions on your Views, except for actions, I will be implementing one action with a default Cancel action.</p><p>And so instead of calling alert(_:isPresented:presenting:actions:message:) and alert(_:isPresented:actions:message:) like follows:</p><pre>/// content ...<br>.alert(<br>    &quot;Random Book&quot;,<br>    isPresented: $showAlert,<br>    presenting: randomBook<br>) { book in<br>    Button(&quot;Yes, Done&quot;) {<br>        selectedBook = book<br>    }<br>} message: { book in<br>    Text(&quot;You have selected \(book.title) by \(book.author)&quot;)<br>}<br>.alert(<br>    &quot;Credits&quot;,<br>    isPresented: $showCreditAlert<br>) {<br>    Button(&quot;OK&quot;) {}<br>} message: {<br>    Text(&quot;This custom alert tutorial was implemented by **Marwa**.&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*Bgs8qIwy8c8dud7c-fKtnQ.gif" /><figcaption>Apple’s Alert</figcaption></figure><p>We can call customAlert(_:isPresented:presenting:actionTextKey:action:message:), and customAlert(_:isPresented:actionTextKey:action:message:) like follows:</p><pre>/// content ...<br>.customAlert(<br>    &quot;Random Book&quot;,<br>    isPresented: $showAlert,<br>    presenting: randomBook,<br>    actionTextKey: &quot;Yes, Done&quot;<br>) { book in<br>    selectedBook = book<br>} message: { book in<br>    Text(&quot;You have selected \(book.title) by \(book.author)&quot;)<br>}<br>.customAlert(<br>    &quot;Credits&quot;,<br>    isPresented: $showCreditAlert,<br>    actionText: &quot;OK&quot;<br>) {<br>    // OK Action<br>} message: {<br>    Text(&quot;This custom alert tutorial was implemented by **Marwa**.&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*eaSsbFo6eZ0TxGtxcG6Jbg.gif" /><figcaption>Custom alert</figcaption></figure><h4>Let’s Start 👩🏻‍💻:</h4><p>Feel free to download starter project <a href="https://github.com/marwaniaaj/CustomAlertSwiftUI/tree/main">here</a>, if you want to follow along — it is just a simple ContentView to test our custom alert — , or make the changes in your own project.</p><h4>TL;TR;</h4><blockquote>If you don’t want the explanation part, feel free to jump to the end of the article, you will find the full source code, download or copy CustomAlertView.swift and View-CustomAlert.swift files and customize CustomAlertView to match your app’s look and feel, or even add your ideas to match your need.</blockquote><p>❶ First, Create new SwiftUIView file named CustomAlertView, in struct header define generic type T that conforms to Hashable, and generic type M that conforms to View, and then declare the following variables:</p><ol><li>isPresented: A binding to a Boolean value that determines whether to present the alert.</li><li>titleKey: The key for the localized string that describes the title of the alert.</li><li>actionTextKey: The key for the localized string that describes the text of action button.</li><li>data: An optional binding of generic type T value, this data will populate the fields of an alert that will be displayed to the user.</li><li>actionWithValue: The alert’s action given the currently available data.</li><li>messageWithValue: A ViewBuilder returning the message for the alert given the currently available data.</li><li>action: Returning the alert’s action.</li><li>message: A ViewBuilder returning the message for the alert.</li></ol><pre>struct CustomAlertView&lt;T: Hashable, M: View&gt;: View {<br>    // 1.<br>    @Binding private var isPresented: Bool<br>    // 2.<br>    @State private var titleKey: LocalizedStringKey<br>    // 3.<br>    @State private var actionTextKey: LocalizedStringKey<br><br>    // 4.<br>    private var data: T?<br>    // 5.<br>    private var actionWithValue: ((T) -&gt; ())?<br>    // 6.<br>    private var messageWithValue: ((T) -&gt; M)?<br><br>    // 7.<br>    private var action: (() -&gt; ())?<br>    // 8.<br>    private var message: (() -&gt; M)?<br><br>    // TODO: init()<br>}</pre><p>In case data is not nil, then we will return actionWithValue and messageWithValue, otherwise, we will return action and message — without a value.</p><p>❷ Next, we are going to create two different initializers for CustomAlertView.</p><p>In the first initializer, because we have data of generic type T, we will define data, actionWithValue, and messageWithValue. <br>action and message will be nil in this case.</p><pre>init(<br>    _ titleKey: LocalizedStringKey,<br>    _ isPresented: Binding&lt;Bool&gt;,<br>    presenting data: T?,<br>    actionTextKey: LocalizedStringKey,<br>    action: @escaping (T) -&gt; (),<br>    @ViewBuilder message: @escaping (T) -&gt; M<br>) {<br>    _titleKey = State(wrappedValue: titleKey)<br>    _actionTextKey = State(wrappedValue: actionTextKey)<br>    _isPresented = isPresented<br><br>    self.data = data<br>    self.action = nil<br>    self.message = nil<br>    self.actionWithValue = action<br>    self.messageWithValue = message<br>}</pre><p>For the second initializer, add an extension to CustomAlertView, where T equals to Never.<br>In this initializer where data is not available, we will define action and message.<br>data and actionWithValue, and messageWithValue will be nil.</p><p><strong>Note</strong>: the additional constraint where T == Never, can be added either on extension or on init().</p><pre>extension CustomAlertView where T == Never {<br>    init(<br>        _ titleKey: LocalizedStringKey,<br>        _ isPresented: Binding&lt;Bool&gt;,<br>        actionTextKey: LocalizedStringKey,<br>        action: @escaping () -&gt; (),<br>        @ViewBuilder message: @escaping () -&gt; M<br>    ) where T == Never {<br>        _titleKey = State(wrappedValue: titleKey)<br>        _actionTextKey = State(wrappedValue: actionTextKey)<br>        _isPresented = isPresented<br><br>        self.data = nil<br>        self.action = action<br>        self.message = message<br>        self.actionWithValue = nil<br>        self.messageWithValue = nil<br>    }<br>}</pre><p>The reason I separated actionText and action, instead of implementing action(s) as @ViewBuilder and send it from caller View the same way you would send it to Apple’s alert, is that I wanted the action button to be controlled by the custom alert and not by the caller.<br>Also I wanted it to be specifically one action button.</p><p>Feel free to add your ideas to make it more customizable and flexible.</p><h4>Let’s continue with the UI</h4><p>❸ Inside body, add the following ZStack that will contain the gray background and the alert VStack:</p><pre>ZStack {<br>    Color.gray<br>        .ignoresSafeArea()<br>        .opacity(isPresented ? 0.6 : 0) // Choose the opacity you like.<br>    VStack { <br>        // TODO: Alert<br>    }<br>    .padding()<br>}<br>.ignoresSafeArea()<br>.zIndex(.greatestFiniteMagnitude)</pre><p>Add the following inside the VStack:<br>If data and messageWithValue is conditionally unwrapped, return messageWithValue(data), otherwise return message().</p><pre>VStack {<br>    /// Title<br>    Text(titleKey)<br>        .font(.title2).bold()<br>        .foregroundStyle(.tint)<br>        .padding(8)<br><br>    /// Message<br>    Group {<br>        if let data, let messageWithValue {<br>            messageWithValue(data)<br>        } else if let message {<br>            message()<br>        }<br>    }<br>    .multilineTextAlignment(.center)<br><br>    /// Buttons<br>    HStack {<br>        CancelButton<br>        DoneButton<br>    }<br>    .fixedSize(horizontal: false, vertical: true)<br>    .padding()<br>    .frame(maxWidth: .infinity)<br>}<br>.padding()<br>.frame(maxWidth: .infinity)<br>.background(.background)<br>.cornerRadius(35)</pre><p>And the following for cancelButton and DoneButton:<br>In DoneButton’s action, if data and actionWithValue is conditionally unwrapped, return actionWithValue(data), otherwise return action().</p><pre>var CancelButton: some View {<br>    Button {<br>        isPresented = false<br>    } label: {<br>        Text(&quot;Cancel&quot;)<br>            .font(.headline)<br>            .foregroundStyle(.tint)<br>            .padding()<br>            .lineLimit(1)<br>            .frame(maxWidth: .infinity)<br>            .background(Material.regular)<br>            .background(.gray)<br>            .clipShape(RoundedRectangle(cornerRadius: 30))<br>    }<br>}<br><br>var DoneButton: some View {<br>    Button {<br>        isPresented = false<br>        if let data, let actionWithValue {<br>            actionWithValue(data)<br>        } else if let action {<br>            action()<br>        }<br>    } label: {<br>        Text(actionTextKey)<br>            .font(.headline).bold()<br>            .foregroundStyle(Color.white)<br>            .padding()<br>            .multilineTextAlignment(.center)<br>            .frame(maxWidth: .infinity)<br>            .background(.tint)<br>            .clipShape(RoundedRectangle(cornerRadius: 30.0))<br>    }<br>}</pre><p>Now, the UI is ready…</p><p>❹ Next, we are going to add two customAlert functions in View extension, the first overload will include T that conforms to Hashable, and M that conforms to View.<br>The second overload will only include M that conforms to View.</p><pre>extension View {<br>    func customAlert&lt;M, T: Hashable&gt;(<br>        _ titleKey: LocalizedStringKey,<br>        isPresented: Binding&lt;Bool&gt;,<br>        presenting data: T?,<br>        actionText: LocalizedStringKey,<br>        action: @escaping (T) -&gt; (),<br>        @ViewBuilder message: @escaping (T) -&gt; M<br>    ) -&gt; some View where M: View {<br><br>        fullScreenCover(isPresented: isPresented) {<br>            CustomAlertView(<br>                titleKey,<br>                isPresented,<br>                presenting: data,<br>                actionTextKey: actionText,<br>                action: action,<br>                message: message<br>            )<br>            .presentationBackground(.clear)<br>        }<br>        // TODO: Disable fullScreenCover transition animation.<br>    }<br>    /// TODO: customAlert&lt;M&gt;...<br>}</pre><p>The best solution to present CustomAlertView — in my opinion — is to use fullScreenCover with a transparent presentation background.</p><p>Then, in ContentView replace the first .alert function with the following:</p><pre>.customAlert(<br>    &quot;Random Book&quot;,<br>    isPresented: $showAlert,<br>    presenting: randomBook,<br>    actionText: &quot;Yes, Done&quot;<br>) { book in<br>    selectedBook = book<br>} message: { book in<br>    Text(&quot;You have selected \(book.title) by \(book.author)&quot;)<br>}</pre><p>Run code 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*CmkXJll4APosSiEpsZ5gQQ.gif" /></figure><p>As you can see, the transition animation is not exactly how we want, so to disable the default transition animation of fullScreenCover add the following in place of <strong>// TODO: Disable fullScreenCover transition animation.</strong>:</p><pre>/// fullScreenCover content...<br>.transaction { transaction in<br>    if isPresented.wrappedValue {<br>        // disable the default fullScreenCover animation<br>        transaction.disablesAnimations = true<br>    <br>        // add custom animation for presenting and dismissing the fullScreenCover<br>        transaction.animation = .linear(duration: 0.1)<br>    }<br>}</pre><p>Checking first on isPresented.wrappedValue, to make sure CustomAlertView is being presented before changing transaction animation. This is because transaction animation is affecting the ContentView animation behavior with first appearance.</p><p>Now run code 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*br0GChqVqfrsf0lzEzcXyA.gif" /></figure><p>❺ Now let’s add the second extension function, add the following customAlert&lt;M&gt; function after customAlert&lt;M, T: Hashable&gt;:</p><pre>extension View {<br>    /// func customAlert&lt;M, T: Hashable&gt; content ...<br><br>    func customAlert&lt;M&gt;(<br>        _ titleKey: LocalizedStringKey,<br>        isPresented: Binding&lt;Bool&gt;,<br>        actionText: LocalizedStringKey,<br>        action: @escaping () -&gt; (),<br>        @ViewBuilder message: @escaping () -&gt; M<br>    ) -&gt; some View where M: View {<br>        fullScreenCover(isPresented: isPresented) {<br>            CustomAlertView(<br>                titleKey,<br>                isPresented,<br>                actionTextKey: actionText,<br>                action: action,<br>                message: message<br>            )<br>            .presentationBackground(.clear)<br>        }<br>        .transaction { transaction in<br>            if isPresented.wrappedValue {<br>                // disable the default FullScreenCover animation<br>                transaction.disablesAnimations = true<br>    <br>                // add custom animation for presenting and dismissing the FullScreenCover<br>                transaction.animation = .linear(duration: 0.1)<br>            }<br>        }<br>    }<br>}</pre><p>Then, in ContentView replace the second .alert function with the following:</p><pre>/// content...<br>.customAlert(<br>    &quot;Credits&quot;,<br>    isPresented: $showCreditAlert,<br>    actionText: &quot;OK&quot;<br>) {<br>    // TODO: OK Action<br>} message: {<br>    Text(&quot;This custom alert tutorial was implemented by **Marwa**.&quot;)<br>}</pre><p>Run code 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*qG5I-HKiHtLZQ8bO-13roQ.gif" /></figure><h4>Let’s add some animation ✨</h4><p>❻ In CustomAlertView, add the following two variables:</p><pre>/// Animation<br>@State private var isAnimating = false<br>private let animationDuration = 0.5</pre><p>Next, after buttons declaration add the following functions:</p><pre>func dismiss() {<br>    withAnimation(.easeInOut(duration: animationDuration)) {<br>        isAnimating = false<br>    }<br>    isPresented = false<br>}<br><br>func show() {<br>    withAnimation(.easeInOut(duration: animationDuration)) {<br>        isAnimating = true<br>    }<br>}</pre><p>Next, call show() inside onAppear on ZStack:</p><pre>ZStack {<br>    // content...<br>}<br>.onAppear {<br>    show()<br>}</pre><p>And replace isPresenting = false in both buttons with dismiss().</p><p>Finally, wrap the outer VStack with isAnimating condition check, and add .transition(.slide) on the same VStack— feel free to choose whichever transition animation you like:</p><pre>if isAnimating {<br>    VStack {<br>        /// Alert VStack content ...<br>    }<br>    .padding()<br>    .transition(.slide)<br>}</pre><p>Run code 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*GzCzAcOOqkdF57TtDuathw.gif" /></figure><p>As you can see Alert is <em>sliding in</em> but not <em>sliding out</em>! That’s because isAnimating and isPresenting are both being set at the same time, so what we need to do here is to wait for animation to complete and then set isPresenting to false.</p><p>in <strong>iOS 17</strong>, <a href="https://developer.apple.com/documentation/swiftui/withanimation(_:completioncriteria:_:completion:)">withAnimation(_:completionCriteria:_:completion:)</a> now includes a completion closure, so withAnimation can be modified like follows:</p><pre>withAnimation(.easeInOut(duration: animationDuration)) {<br>    isAnimating = false<br>} completion: {<br>    isPresented = false<br>}</pre><p>If your iOS target is prior to<strong> iOS 17</strong>, then use asyncAfter instead:</p><pre>if #available(iOS 17.0, *) {<br>    withAnimation(.easeInOut(duration: animationDuration)) {<br>        isAnimating = false<br>    } completion: {<br>        isPresented = false<br>    }<br>} else {<br>    withAnimation(.easeInOut(duration: animationDuration)) {<br>        isAnimating = false<br>    }<br>    DispatchQueue.main.asyncAfter(deadline: .now() + animationDuration) {<br>        isPresented = false<br>    }<br>}</pre><p>Run code 📲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*4VV_BfvFZ5DWAHvnlUkcyA.gif" /></figure><p>The sliding transition works fine now, but the order of gray background and alert view is not correct!!</p><p>to solve this, add .zIndex(1) on gray background, and .zIndex(2) on the VStack like follows:</p><pre>ZStack {<br>    Color.gray<br>        .ignoresSafeArea()<br>        .opacity(isPresented ? 0.6 : 0)<br>        .zIndex(1)<br><br>    if isAnimating {<br>        VStack { /* content ...*/ }<br>        .padding()<br>        .transition(.slide)<br>        .zIndex(2)<br>}</pre><h4>Take it for a spin 📲</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*Uqpw-h3IHdroDBYbmB1kvA.gif" /></figure><h4>And Voilà! 🎉</h4><p>With that you’ve created custom &amp; reusable alert, with animation and transition.<br>Feel free to add any ideas and changes to make it custom to your needs.</p><blockquote>You can find the project’s full source code on <a href="https://github.com/marwaniaaj/CustomAlertSwiftUI">GitHub</a> 🚀<br>If you liked this, don’t forget to 👏 and follow 😍.<br>Feedbacks are most welcome, drop them below in the comments section.</blockquote><blockquote>“ Everyone has something to learn. Everyone has something to teach.” ~ <a href="https://twitter.com/twostraws/status/1613922671523418117">Paul Hudson</a></blockquote><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df860da27e57" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/custom-alert-in-swiftui-df860da27e57">Custom Alert in SwiftUI</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>