<?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 Desilio Neto on Medium]]></title>
        <description><![CDATA[Stories by Desilio Neto on Medium]]></description>
        <link>https://medium.com/@desilio?source=rss-4cdbd2a1a82d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DIiuZWjGf4PBK3RQVsHzAQ.jpeg</url>
            <title>Stories by Desilio Neto on Medium</title>
            <link>https://medium.com/@desilio?source=rss-4cdbd2a1a82d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 11:47:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@desilio/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[Getting user location with SwiftUI]]></title>
            <link>https://medium.com/@desilio/getting-user-location-with-swiftui-1f79d23c2321?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f79d23c2321</guid>
            <category><![CDATA[uselocation]]></category>
            <category><![CDATA[getting-user-location]]></category>
            <category><![CDATA[cllocationmanager]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 20:31:03 GMT</pubDate>
            <atom:updated>2024-03-21T20:31:03.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDs84GWc7mEJazhn6u--Eg.png" /></figure><p>Today we will get the user location using Core Location and SwiftUI. Let’s start, as the user location is a sensible information you need to ask the user permission for it, so we need to add a entry in the project Info.plist file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVH94-zH5wmn6bnXgDokAA.png" /></figure><p>The plist file can be found clicking in your project name as image above and then select Info tab. There’s 2 level of permission you can ask: <strong>always</strong> and <strong>when in use</strong>. You have to choose according to your app necessities. We need to add a new entry on Info.plist, so hit the plus button and search for <strong>Privacy — Location When In Use Usage Description</strong>. This is the permission that we will use on the article and it is suitable to get the user locations when using the app. You also have to provide a description explaining the user why your app needs the location (this text will appear in a dialog asking for user permission) in the article a used the following one: “<strong>The app needs access to your location to provide location-based services.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3y3L2Ic3jHL_m-dH9tgt0A.png" /></figure><p>Next step is create a class that will handle it:</p><pre>import Foundation<br>import CoreLocation<br><br>final class LocationManager: NSObject, CLLocationManagerDelegate, ObservableObject {<br>    <br>    @Published var lastKnownLocation: CLLocationCoordinate2D?<br>    var manager = CLLocationManager()<br>    <br>    <br>    func checkLocationAuthorization() {<br>        <br>        manager.delegate = self<br>        manager.startUpdatingLocation()<br>        <br>        switch manager.authorizationStatus {<br>        case .notDetermined://The user choose allow or denny your app to get the location yet<br>            manager.requestWhenInUseAuthorization()<br>            <br>        case .restricted://The user cannot change this app’s status, possibly due to active restrictions such as parental controls being in place.<br>            print(&quot;Location restricted&quot;)<br>            <br>        case .denied://The user dennied your app to get location or disabled the services location or the phone is in airplane mode<br>            print(&quot;Location denied&quot;)<br>            <br>        case .authorizedAlways://This authorization allows you to use all location services and receive location events whether or not your app is in use.<br>            print(&quot;Location authorizedAlways&quot;)<br>            <br>        case .authorizedWhenInUse://This authorization allows you to use all location services and receive location events only when your app is in use<br>            print(&quot;Location authorized when in use&quot;)<br>            lastKnownLocation = manager.location?.coordinate<br>            <br>        @unknown default:<br>            print(&quot;Location service disabled&quot;)<br>        <br>        }<br>    }<br>    <br>    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {//Trigged every time authorization status changes<br>        checkLocationAuthorization()<br>    }<br>    <br>    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {<br>        lastKnownLocation = locations.first?.coordinate<br>    }<br>}</pre><p>The class is a bit extensive but let’s break it down. First we need to import <strong>CoreLocation. </strong>The our class should conform with <strong>NSObject, CLLocationManagerDelegate and ObservableObject</strong> protocols. <strong>@Published var lastKnownLocation: CLLocationCoordinate2D? </strong>is used to store the user location and <strong>var manager = CLLocationManager() </strong>will allow get access to location services.</p><p>On <strong>checkLocationAuthorization() </strong>function we conform to <strong>CLLocationManagerDelegate</strong> and start to get location updates. There’s also a switch case to handle <strong>authorization status,</strong> I just added prints to show you all the options you have to handle it. I our case you are just using <strong>.authorizedWhenInUse </strong>to update our <strong>lastKnownLocation</strong> variable.</p><p>Next we have <strong>locationManagerDidChangeAuthorization() </strong>function that is trigged every time <strong>authorization status</strong> changes.</p><p>The last function is <strong>locationManager() </strong>function the is called every time the location change.</p><p>Now our UI:</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @StateObject private var locationManager = LocationManager()<br>    <br>    var body: some View {<br>        VStack {<br>            if let coordinate = locationManager.lastKnownLocation {<br>                Text(&quot;Latitude: \(coordinate.latitude)&quot;)<br>                <br>                Text(&quot;Longitude: \(coordinate.longitude)&quot;)<br>            } else {<br>                Text(&quot;Unknown Location&quot;)<br>            }<br>            <br>            <br>            Button(&quot;Get location&quot;) {<br>                locationManager.checkLocationAuthorization()<br>            }<br>            .buttonStyle(.borderedProminent)<br>        }<br>        .padding()<br>    }<br>}</pre><p>The UI is very simple, we have a instance of our <strong>LocationManger()</strong> class and a VStack with 3 Texts to show latitude, longitude and unknown location message if isn’t possible get the location. Last peace of our design is a Button where we call the checkLocationAuthorization() to get the location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LhE-sVlZR8_yoKhLcOdGw.png" /><figcaption>This is the result</figcaption></figure><p>You can test the result using the canvas and emulator, but according with my experience only on a physical device it works 100%. That’s all for today, the example showed can be found <a href="https://github.com/netolobo/GettingUserLocation">here</a>. If this article was useful for you give me a clap and follow me to be updated about next contents. Until next time, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f79d23c2321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to check internet connection with SwiftUI]]></title>
            <link>https://medium.com/@desilio/how-to-check-internet-connection-with-swiftui-9426454027f5?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9426454027f5</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[internet-connection]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 18:24:55 GMT</pubDate>
            <atom:updated>2024-03-31T02:19:45.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6rKeRtIpPw8RTHZCdhewA.png" /></figure><p>Checking for internet connection is a vital part in many apps, today I’ll show how to do it using the class <strong>NWPathMonitor</strong> from the Apple <strong>Network </strong>framework. Let’s start my idea is create a very simple app that shows the internet connection status in realtime. First step is create a Observable class, I called this <strong>NetworkMonitor</strong>:</p><pre>import Foundation<br>import Network<br><br>@Observable<br>final class NetworkMonitor {<br>    private let networkMonitor = NWPathMonitor()<br>    private let workerQueue = DispatchQueue(label: &quot;Monitor&quot;)<br>    var isConnected = false<br>    <br>    init() {<br>        networkMonitor.pathUpdateHandler = { path in<br>            self.isConnected = path.status == .satisfied<br>        }<br>        networkMonitor.start(queue: workerQueue)<br>    }<br>}</pre><p>The code is simple, we have an instance of the<strong> NWPathMonito</strong>r class that is used to track network path changes.<strong> DispachQueue</strong> is used to handle network monitoring operations. The<strong> label</strong> parameter specifies the name of the dispatch queue, so you can use whatever name you want.<strong> isConnected</strong> is a public property that will be used to check the internet connection in our view.</p><p>Than we have the constructor that is used to set network monitoring functionality. networkMonitor.pathUpdateHandler = { path in ... }: This line sets a closure as the pathUpdateHandler property of the networkMonitor. This closure is called whenever there is an update to the network path. It takes a parameter path, which represents the current network path.</p><p>self.isConnected = path.status == .satisfied: Inside the closure, the isConnected property is updated based on the status property of the path. If the status is .satisfied, it means that the device is connected to the network, so isConnected is set to true. Otherwise, it is set to false.</p><p>networkMonitor.start(queue: workerQueue): Finally, the start(queue:) method of networkMonitor is called to begin monitoring the network path.</p><p>Second step is decide how you will use the NetworkMonitor, I chose use it as an Environment object if you don’t know what it is, take a look at this other <a href="https://medium.com/@desilio/how-to-use-environment-to-share-data-between-views-in-swiftui-dd62802aaa11">article</a> that I wrote. Here how I set it up:</p><pre>import SwiftUI<br><br>@main<br>struct HowToCheckInternetConnectionSwiftUIApp: App {<br>    @State private var networkMonitor = NetworkMonitor()<br>    <br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .environment(networkMonitor)<br>        }<br>    }<br>}</pre><p>The last part is the view that is very simple there’s just a VStack with 2 Text and 1 image that changes according the internet connection status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*mEl6oAYiRPRu4DSwB7N7aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*42GC1JXqCywRCPJYYXj23w.png" /></figure><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @Environment(NetworkMonitor.self) private var newtworkMonitor<br>    <br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Text(&quot;Internet status:&quot;)<br>                .font(.title)<br>            <br>            Image(systemName: newtworkMonitor.isConnected ? &quot;wifi&quot; : &quot;wifi.slash&quot;)<br>                    .font(.title)<br>                    .foregroundStyle(newtworkMonitor.isConnected ? .green : .red)<br>                <br>            Text(newtworkMonitor.isConnected ? &quot;Connected&quot; : &quot;Disconnected&quot;)<br>                    .font(.title)<br>                    .fontWeight(.bold)<br>                    .foregroundStyle(newtworkMonitor.isConnected ? .green : .red)<br>            }<br>        }<br>    <br>}<br><br>#Preview {<br>    ContentView()<br>        .environment(NetworkMonitor())<br>}</pre><p>You can test it using the canvas or simulator disabling your computer network, but it isn’t very reliable according my tests, so is better test it with a real device.</p><p>That’s it for today, the project I created for the article can be found <a href="https://github.com/netolobo/HowToCheckInternetConnectionSwiftUI">here.</a> I hope it were useful for you, give me a clap if you like and follow me to not miss the next articles. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9426454027f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use @Environment to share data between views in SwiftUI]]></title>
            <link>https://medium.com/@desilio/how-to-use-environment-to-share-data-between-views-in-swiftui-dd62802aaa11?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd62802aaa11</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[environmentobject]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 13:17:36 GMT</pubDate>
            <atom:updated>2024-02-13T13:17:36.835Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMFuo7dYCvIJohkvcBLDQw.jpeg" /></figure><p>If you need to have access to data in different views SwiftUI provides the property wrapper @Environment for this propose. To use it first you need to create a class that is observable. I create a very simple one with just one field:</p><pre>import Foundation<br>import SwiftUI<br><br>@Observable<br>class BackgroundColor {<br>    var value: Color = .red<br>}</pre><p>I will use it to share this value set the background of 2 views. Next step is go to the entry screen of your app, this file is located usually on the top of you project and the name is “name of your project”App in my case the file is named <strong>SharingDataWithEnvironmentSwiftUIApp</strong>. After open the file I added one instance of the class that I created before and also added the modifier <strong>.environment</strong> to the <strong>ContentView()</strong> and passed the object created.</p><pre>import SwiftUI<br><br>@main<br>struct SharingDataWithEnvironmentSwiftUIApp: App {<br>    @State private var label = BackgroundColor()<br>    <br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .environment(label)<br>        }<br>    }<br>}</pre><p>Now is time to use our the Environment in our views. I created 2 simple views one with a Text and a Button, this button call the Second Screen that have also a Text and a button that changes the value of the Environment object to green. Boot views receives the background color from the Environment variable. Pay attention that <strong>before</strong> <strong>use it</strong> you should setup the preview first, <strong>otherwise it will crash</strong>, so let’s do it. To setup the preview is easy, you just need to use the <strong>environment</strong> modifier and pass a instance of the observable class that we created before, in our case BackgroundColor():</p><pre>#Preview {<br>    ContentView()<br>        .environment(BackgroundColor())<br>}</pre><p>You should do it with <strong>every</strong> view that you will use the Environment property. Last step is call the Environment property on our views, so you can use it. We just declare an <strong>@Environment</strong> passing the type we created as reference <strong>BackgroundColor.self</strong>. I named the variable as <strong>backgroundColor</strong> but you can use any name your want.</p><pre>@Environment(BackgroundColor.self) private var backgroundColor</pre><p>This is the complete code of the <strong>ContentView</strong>:</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @Environment(BackgroundColor.self) private var backgroundColor<br>    <br>    var body: some View {<br>        NavigationStack {<br>            VStack {<br>                Text(&quot;Background color from environment&quot;)<br>                <br>                NavigationLink(&quot;Go to second screen&quot;) {<br>                    SecondView()<br>                }<br>            }<br>            .frame(maxWidth: .infinity, maxHeight: .infinity)<br>            .background(backgroundColor.value)<br>        }<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>        .environment(BackgroundColor())<br>}</pre><p>As you can see I am setting the background color using the variable that I declared before. And finally the code of the <strong>SecondView</strong>:</p><pre>import SwiftUI<br><br>struct SecondView: View {<br>    @Environment(BackgroundColor.self) private var backgroundColor<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;Background color from environment&quot;)<br>            <br>            Button(&quot;change color to green &quot;) {<br>                backgroundColor.value = .green<br>            }<br>        }<br>        .frame(maxWidth: .infinity, maxHeight: .infinity)<br>        .background(backgroundColor.value)<br>    }<br>}<br><br>#Preview {<br>    SecondView()<br>        .environment(BackgroundColor())<br>}</pre><p>In this view if you press the button you will update the value of the Environment object and it will update the background color of this view and also of our ContentView. In our example you use just 2 view but if you have a lots of views it would updated all of them at the same time, this is useful when you is working with app settings for example. This is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*ebsIx5BLFtPzEn9kpv5oMw.gif" /></figure><p>That’s all for today if you enjoy give me a clap and follow to be updated about the next tutorials, the code of this tutorial can be found on my <a href="https://github.com/netolobo/SharingDataWithEnvironmentSwiftUI">GitHub</a>, if you have any question please let me know on the comments. Until next time, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd62802aaa11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to open a link in Safari with SwiftUI]]></title>
            <link>https://medium.com/@desilio/how-to-open-a-link-in-safari-with-swiftui-1938e39545ca?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1938e39545ca</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 00:36:25 GMT</pubDate>
            <atom:updated>2024-01-19T00:36:25.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5DvXNwPmWD5KLg1fhmH8Q.jpeg" /></figure><p>There’s 2 ways of opening a link with SwiftUI, on is using <strong>Link</strong> and Other one is using <strong>openURL</strong> environment key. Let’s start with the first option using <strong>Link</strong>:</p><pre>Link(&quot;Link&quot;, destination: URL(string: &quot;https://www.apple.com/&quot;)!)</pre><p><strong>Link’s</strong> struct receives a title and a destination URL, I used the Apple website as example and forced unwrap because I know that theString I’m using will be aways valid, if you receive this string dynamically is always a good idea unwrap it first. This is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*sbPXpzLhhtbaXZ95aBhzeg.gif" /></figure><p>It’s possible customise the <strong>Link</strong> if you want:</p><pre>Link(destination: URL(string: &quot;https://www.apple.com/&quot;)!) {<br>                    HStack {<br>                        Image(systemName: &quot;swift&quot;)<br>                        <br>                        Text(&quot;Custom link&quot;)<br>                    }<br>                }<br>                .foregroundStyle(.orange)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*zGsxAe5xE6Bms1qkff6xfg.gif" /></figure><p>The second way of opening a link is using <strong>openURL</strong> <strong>environment key</strong>, you just need to declare the environment variable:</p><pre>@Environment(\.openURL) var openLink</pre><p>And use the variable inside a button like this:</p><pre>Button {<br>    openLink(URL(string: &quot;https://www.apple.com/&quot;)!)<br>} label: {<br>    Text(&quot;Button link&quot;)<br>         .frame(width: 120, height: 60)<br>         .background(.purple)<br>         .foregroundStyle(.white)<br>         .fontWeight(.heavy)<br>         .fontDesign(.rounded)<br>         .clipShape(.capsule)<br>}</pre><p>The code is self explained, I just made some customisations on the button and here’s the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*ShhiBCo9outC3p5A4DU5PQ.gif" /></figure><p>That’s all, if the tutorial was useful for you give it a clap, the repository with code of this tutorial can be found on my <a href="https://github.com/netolobo/OpeningLinkSwiftUI">Github</a>. If you have any question use the comments. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1938e39545ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to ask for user permission with Jetpack Compose]]></title>
            <link>https://medium.com/@desilio/how-to-ask-for-user-permission-with-jetpack-compose-124df4b65638?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/124df4b65638</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[permission]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 18:24:13 GMT</pubDate>
            <atom:updated>2024-01-16T18:24:13.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ovj7Ajoxe1ydFUqFFQjj4Q.jpeg" /></figure><p>In this tutorial I gonna show you how to ask user permission, if the user denny the permission a dialog will be showed to explain why you app need this permission, if the user denny the permission, it will show the dialog again, if the user denny the permission and check “Don’t ask me again” then it will show a new dialog explain again why the permission is important for the app with an option to go to app settings so the user can change the permission manually. Enough of explanations, let’s code:</p><p>Firstly I created an interface to provide the title, description and label of our permission dialog:</p><pre>interface PermissionDialogTextProvider {<br>    fun getTitle() : String<br>    fun getDescription(isPermanentlyDeclined: Boolean): String<br>    fun getButtonLabel(isPermanentlyDeclined: Boolean): String<br>}</pre><p>In this example I’ll be asking for the permission to access the camera, so we need to add this permission to the AndroidManifest.xml</p><pre>&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot;/&gt;</pre><p>Next step I created a class that extends <strong>PermissionDialogTextProvider</strong> to provide the text we need for the Permission dialog according the permission I asking:</p><pre>class StoragePermissionDialogTextProvider : PermissionDialogTextProvider {<br>    override fun getTitle(): String = &quot;Permission required&quot;<br>    override fun getDescription(isPermanentlyDeclined: Boolean): String {<br>        return if (isPermanentlyDeclined) {<br>            &quot;It seems you permanently declined the app to access your phone gallery. You can go to the app settings to grant it.&quot;<br>        } else {<br>            &quot;This app need to access your camera so it can capture image and videos to use on the app.&quot;<br>        }<br>    }<br>    override fun getButtonLabel(isPermanentlyDeclined: Boolean): String {<br>        return if (isPermanentlyDeclined) &quot;Go to settings&quot; else &quot;OK&quot;<br>    }<br>}</pre><p>Next I created the Permission Dialog itself, what is basically an dialog with that receives as input the description of the dialog, if the dialog is permanently declined and 3 lambda functions one to dismiss the dialog, other to handle ok or go to app settings button click according if the dialog was permanently declined or not.</p><pre>@Composable<br>fun PermissionDialog(<br>    permissionDialogTextProvider: PermissionDialogTextProvider,<br>    isPermanentlyDeclined: Boolean,<br>    onDismiss: () -&gt; Unit,<br>    onOkClick: () -&gt; Unit,<br>    onGoToAppSettingsClick: () -&gt; Unit<br>) {<br>    Dialog(<br>        onDismissRequest = onDismiss<br>    ) {<br>        Surface(shape = RoundedCornerShape(20.dp)) {<br>            Column(<br>                verticalArrangement = Arrangement.Center,<br>                horizontalAlignment = Alignment.CenterHorizontally,<br>                modifier = Modifier.padding(16.dp)<br>            ) {<br>                Text(<br>                    text = permissionDialogTextProvider.getTitle(),<br>                    fontWeight = FontWeight.Bold<br>                )<br><br>                Spacer(modifier = Modifier.height(20.dp))<br><br>                Text(<br>                    text = permissionDialogTextProvider.getDescription(isPermanentlyDeclined)<br>                )<br><br>                Spacer(modifier = Modifier.height(20.dp))<br><br>                Button(onClick = {<br>                    if (isPermanentlyDeclined) {<br>                        onGoToAppSettingsClick()<br>                    } else {<br>                        onOkClick()<br>                    }<br>                }) {<br>                    Text(text = permissionDialogTextProvider.getButtonLabel(isPermanentlyDeclined))<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>The last part of our puzzle is our main screen that is basically um button to ask the permission, if the permissions has already granted it will show a Toast message otherwise it will show the permission dialog as I explained before:</p><pre>class MainActivity : ComponentActivity() {<br><br>    private val permissionRequired = Manifest.permission.CAMERA<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            JetpackComposePermissionsTheme {<br>                var showPermissionDialog by remember { mutableStateOf(false) }<br><br>                val storagePermissionResultLauncher = rememberLauncherForActivityResult(<br>                    contract = ActivityResultContracts.RequestPermission(),<br>                    onResult = { isGranted -&gt;<br>                        if (isGranted) {<br>                            Toast<br>                                .makeText(this, &quot;Permission granted&quot;, Toast.LENGTH_SHORT)<br>                                .show()<br>                        }<br>                        showPermissionDialog = !isGranted<br>                    }<br>                )<br><br>                Scaffold { paddingValues -&gt;<br>                    Column(<br>                        modifier = Modifier<br>                            .fillMaxSize()<br>                            .padding(paddingValues),<br>                        verticalArrangement = Arrangement.Center,<br>                        horizontalAlignment = Alignment.CenterHorizontally,<br><br>                    ) {<br>                        Button(onClick = {<br>                            storagePermissionResultLauncher.launch(permissionRequired)<br>                        }) {<br>                            Text(text = &quot;Request permission&quot;)<br>                        }<br>                    }<br>                }<br><br>                if (showPermissionDialog) {<br>                    PermissionDialog(StoragePermissionDialogTextProvider(),<br>                        isPermanentlyDeclined = !shouldShowRequestPermissionRationale(permissionRequired),<br>                        onDismiss = { showPermissionDialog = false },<br>                        onOkClick = {<br>                            storagePermissionResultLauncher.launch(permissionRequired)<br>                            showPermissionDialog = false<br>                        },<br>                        onGoToAppSettingsClick = {<br>                            openAppSettings()<br>                            showPermissionDialog = false<br>                        }<br>                    )<br>                }<br>            }<br>        }<br>    }<br>    private fun openAppSettings() {<br>        val intent = Intent(<br>            Settings.ACTION_APPLICATION_DETAILS_SETTINGS,<br>            Uri.fromParts(&quot;package&quot;, packageName, null)<br>        )<br>        startActivity(intent)<br>    }<br>}</pre><p>That’s it this is the code to ask for a single permission, there’s also the option to ask for multiples permissions at the same time but I won’t cover it today because I wanna leave it as simple as possible. The complete code can be found on this <a href="https://github.com/netolobo/JetpackComposePermissions">repository</a>. If the tutorial was useful for you give me a clap here and also give the project a star on Github. Feel free to answer any question on the comments. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=124df4b65638" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capturing and cropping images from gallery or camera with Jetpack Compose]]></title>
            <link>https://medium.com/@desilio/capturing-and-cropping-images-from-gallery-or-camera-with-jetpack-compose-385cb1173702?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/385cb1173702</guid>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 00:26:10 GMT</pubDate>
            <atom:updated>2023-12-25T00:38:04.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*BfH0vrPXigcPUPgct3aqug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*F1GV4CSu1jEI4U4CJZqZwQ.png" /><figcaption>Result</figcaption></figure><p>I will show you the easiest way to get this work done, so let’s go. First of all we will be using a third party library do achieve our goals, the name of the library is <a href="https://github.com/CanHub/Android-Image-Cropper">Android-Image-Cropper</a>, so add it on your <strong>build.gradle.kts</strong> (app level)</p><pre>implementation(&quot;com.vanniktech:android-image-cropper:4.5.0&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCmjnBZdHNvKj-qMIw1P7A.png" /></figure><p>I also added a Material Icons extended dependency to the project to use some extras icons that isn’t included by default in Material Design 3 library, but it is not required.</p><p>Next step is add CropImageActivity to your <strong>AndroidManifest.xml</strong>:</p><pre>&lt;activity<br>    android:name=&quot;com.canhub.cropper.CropImageActivity&quot;<br>    android:theme=&quot;@style/Base.Theme.AppCompat&quot;/&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7KZKre9E2E6eBwNhsfiJQ.png" /></figure><p>With all set up I created a very simple composable layout to get an image from the gallery or the camera and show it on screen:</p><pre>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun MyApp() {<br>    var bitmap: Bitmap? by remember { mutableStateOf(null) }<br>    val context = LocalContext.current as Activity<br><br>    val imageCropLauncher =<br>        rememberLauncherForActivityResult(contract = CropImageContract()) { result -&gt;<br>            if (result.isSuccessful) {<br>                result.uriContent?.let {<br><br>                    //getBitmap method is deprecated in Android SDK 29 or above so we need to do this check here<br>                    bitmap = if (Build.VERSION.SDK_INT &lt; 28) {<br>                        MediaStore.Images<br>                            .Media.getBitmap(context.contentResolver, it)<br>                    } else {<br>                        val source = ImageDecoder<br>                            .createSource(context.contentResolver, it)<br>                        ImageDecoder.decodeBitmap(source)<br>                    }<br>                }<br><br>            } else {<br>                //If something went wrong you can handle the error here<br>                println(&quot;ImageCropping error: ${result.error}&quot;)<br>            }<br>        }<br><br>    Scaffold(<br>        topBar = {<br>            TopAppBar(<br>                title = { Text(&quot;Crop Image&quot;) },<br>                actions = {<br>                    IconButton(<br>                        onClick = {<br>                            val cropOptions = CropImageContractOptions(<br>                                null,<br>                                CropImageOptions(imageSourceIncludeCamera = false)<br>                            )<br>                            imageCropLauncher.launch(cropOptions)<br>                        }<br>                    ) {<br>                        Icon(<br>                            Icons.Filled.Image,<br>                            contentDescription = &quot;Background from gallery&quot;<br>                        )<br>                    }<br><br>                    IconButton(<br>                        onClick = {<br>                            val cropOptions = CropImageContractOptions(<br>                                null,<br>                                CropImageOptions(imageSourceIncludeGallery = false)<br>                            )<br>                            imageCropLauncher.launch(cropOptions)<br>                        }<br>                    ) {<br>                        Icon(<br>                            Icons.Filled.CameraEnhance,<br>                            contentDescription = &quot;Background from camera&quot;<br>                        )<br>                    }<br>                }<br>            )<br>        }<br>    ) { paddingValues -&gt;<br>        Box(modifier = Modifier.padding(paddingValues)) {<br>            bitmap?.let {<br>                Image(<br>                    bitmap = it.asImageBitmap(),<br>                    contentDescription = null,<br>                    modifier = Modifier.fillMaxSize()<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>I will explain what I did here first about the design itself, we have a Scaffold with a TopAppBar and 2 action buttons, on button to get the image from the camera and other button to get the image from the gallery, pay attention to @OptIn(ExperimentalMaterial3Api::class) annotation I had to do this because TopAppBar is not stable yet.</p><p>We also have 3 variables, this first one is <strong>bitmap</strong> that is used to store the image from the gallery or the camera:</p><pre>var bitmap: Bitmap? by remember { mutableStateOf(null) }</pre><p>The second one is the constant <strong>context</strong> to get the context of our Activity:</p><pre>val context = LocalContext.current as Activity</pre><p>The last, but not least important is <strong>imageCropper</strong> variable that receives a rememberLauncherForActivityResult with the CropImageContract() as parameter. This variable will be used to get the image from the camera or gallery or return an error with the operation won’t successful:</p><pre>val imageCropLauncher =<br>        rememberLauncherForActivityResult(contract = CropImageContract()) { result -&gt;<br>            if (result.isSuccessful) {<br>                result.uriContent?.let {<br><br>                    //getBitmap method is deprecated in Android SDK 29 or above so we need to do this check here<br>                    bitmap = if (Build.VERSION.SDK_INT &lt; 28) {<br>                        MediaStore.Images<br>                            .Media.getBitmap(context.contentResolver, it)<br>                    } else {<br>                        val source = ImageDecoder<br>                            .createSource(context.contentResolver, it)<br>                        ImageDecoder.decodeBitmap(source)<br>                    }<br>                }<br><br>            } else {<br>                //If something went wrong you can handle the error here<br>                println(&quot;ImageCropping error: ${result.error}&quot;)<br>            }<br>        }</pre><p>If the result is successful we update the <strong>bitmap</strong> variable, otherwise we can handle the error.</p><p>Inside the action buttons I added the following code:</p><pre>val cropOptions = CropImageContractOptions(null, CropImageOptions(imageSourceIncludeCamera = false))<br><br>imageCropLauncher.launch(cropOptions)</pre><p>The constant <strong>cropOptions</strong> is used to set a wide range of option you should need, this first parameter is <strong>URI</strong>, as we don’t have one yet we pass <strong>null</strong>, the second is CropImageOptions and I am passing<strong> imageSourceIncludeCamera</strong> as false just to open the gallery directly, on the camera button action I made the contrary to open the camera, if you don’t pass any parameter it will ask you to choose what option do you want. <strong>CropImageOptions</strong> has a lot of options (more than 20) I encourage you take a look at it documentation.</p><p>The last part we have an <strong>Image</strong> composable to show the image captured, if we don’t have image yet it shows nothing, otherwise shows our image.</p><pre>bitmap?.let {<br>    Image(<br>        bitmap = it.asImageBitmap(),<br>        contentDescription = null,<br>        modifier = Modifier.fillMaxSize()<br>    )<br>}</pre><p>That’s it, I hope this tutorial was useful for you, the source code of the project used can be found <a href="https://github.com/netolobo/ImageCroppingJetpackCompose">here</a>, give me a clap if you like. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=385cb1173702" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add a SwiftUI Search Bar]]></title>
            <link>https://medium.com/@desilio/how-to-add-a-swiftui-search-bar-1028d1a6b937?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1028d1a6b937</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[searchbar]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 01:24:23 GMT</pubDate>
            <atom:updated>2025-01-17T13:08:02.467Z</atom:updated>
            <content:encoded><![CDATA[<p>Adding a Search Bar with SwiftUI is very simple. I created an small app to show how simple it is. Our app has just one view with a list of countries and we can filter this countries based on a search text. This is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*VN1HAS4pJ_plYzxCSGnLVQ.gif" /></figure><p>The code is small and simple:</p><pre>    @State private var searchText = &quot;&quot;<br>    <br>    private let countries = [<br>        &quot;Afghanistan&quot;, &quot;Albania&quot;, &quot;Algeria&quot;, &quot;Andorra&quot;, &quot;Angola&quot;, &quot;Antigua and Barbuda&quot;, &quot;Argentina&quot;, &quot;Armenia&quot;, &quot;Australia&quot;, &quot;Austria&quot;<br>    ]<br>    <br>    private var searchResults : [String] {<br>        searchText.isEmpty ? countries : countries.filter { $0.contains(searchText) }<br>    }<br><br>    var body: some View {<br>        NavigationStack {<br>            VStack {<br>                List(searchResults, id: \.self) { country in<br>                    Text(country)<br>                }<br>            }<br>            .searchable(text: $searchText)<br>        }<br>    }</pre><p>We have the <strong>searchText</strong> that is used to input the word you want to search, than we have the <strong>countries </strong>array, and last but not least important we have the <strong>searchResults</strong> array that is a computed property that receives <strong>countries</strong> array when the <strong>searchText</strong> variable is empty or receives the <strong>countries</strong> array filtered according to the word passed to <strong>searchText</strong>.</p><p>In our view part we need a <strong>NavigationStack</strong> to use the<strong> .searchable</strong> modifier, that receives the <strong>$searchText</strong> as input. Inside the the <strong>NavigationStack</strong> we have a <strong>VStack</strong> with a <strong>List</strong>. The searchResult is passed to the <strong>List</strong> and a simple <strong>Tex</strong>t is showed with a country.</p><p>That’s it! the repository with the source code used on the example can be found <a href="https://github.com/netolobo/SearchBarSwiftUI">here</a>. More information about Search Bar can be found <a href="https://developer.apple.com/documentation/swiftui/adding-a-search-interface-to-your-app">here</a>. Any question let me know on the comments, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1028d1a6b937" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loading a json file with SwiftUI]]></title>
            <link>https://medium.com/@desilio/loading-a-json-file-with-swiftui-18f0486f8de9?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/18f0486f8de9</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 19:14:53 GMT</pubDate>
            <atom:updated>2023-12-03T19:14:53.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I’ll show how to load a simple json file and show on screen. First we need a json file I’ve create this very simple one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLxbqfecAqAfWctXfm_hFw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLxbqfecAqAfWctXfm_hFw.jpeg" /></figure><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;first&quot;: &quot;Nicole&quot;,<br>        &quot;last&quot;: &quot;Adelstein&quot;<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;first&quot;: &quot;Pleuni&quot;,<br>        &quot;last&quot;: &quot;Pennings&quot;<br>    },<br>    {<br>        &quot;id&quot;: 3,<br>        &quot;first&quot;: &quot;Rori&quot;,<br>        &quot;last&quot;: &quot;Rohlfs&quot;<br>    }<br>]</pre><p>This json file is a simple array of person, with id, first, and last that represent fist and last names.</p><p>The first step is create our model that represent a person, so go to file -&gt; new file and choose swift file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kpt8QwPWeAN4dghRiwY7jA.png" /><figcaption>now click on the next button</figcaption></figure><p>Name the file as Person. This is how our file looks like:</p><pre>import Foundation<br><br>struct Person : Identifiable, Codable {<br>    let id: Int<br>    let first: String<br>    let last: String<br>}</pre><p>This is our Person struct, we need to conform to <strong>Codable</strong> protocol to decode the json, I’m also conforming to <strong>Identifiable</strong> protocol what is not really necessary, but I’m doing it to load the Person array on the view without passing a second parameter to the List that I will create.</p><p>Next step is create a function to try load the json file, I created the function on the ContentView for sake of practicality, in a real project you will want it in a extension or in a model class or struct.</p><pre>func decode(_ file: String) -&gt; [Person] {<br>        guard let url = Bundle.main.url(/service/forresource: file, withExtension: nil) else {<br>            fatalError(&quot;Faliled to locate \(file) in bundle&quot;)<br>        }<br>        <br>        guard let data = try? Data(contentsOf: url) else {<br>            fatalError(&quot;Failed to load file from \(file) from bundle&quot;)<br>        }<br>        <br>        let decoder = JSONDecoder()<br>        <br>        guard let loadedFile = try? decoder.decode([Person].self, from: data) else {<br>            fatalError(&quot;Failed to decode \(file) from bundle&quot;)<br>        }<br>        <br>        return loadedFile<br>    }</pre><p>Our function receives a String as input and returns an array of Person. The String we pass is the name of your json file with the extension, with our case it will be “<strong>people.json</strong>”. In the first <strong>guard let</strong> I try to get the url of our file using <strong>Bundle</strong>, if the operation fails it will throw a <strong>fatalError</strong>, I decided to do it because our code can’t continue without this information, pay attention that I’m throwing a <strong>fatalError</strong> more 2 times if the operation fail for the same reason.</p><p>In the second guard let I’m trying to get the data from url using <strong>Data. </strong>In the last part I created an instance of <strong>JSONDecoder</strong> and then I try to load the file using <strong>.decode</strong> method that takes the type we are trying to get from the data, in our case <strong>[Person] </strong>and the <strong>data</strong> that we wrapped before, lastly we return our <strong>array of Person</strong> and that’s it for this function.</p><p>Know the last part of the puzzle is create the view to load and show our data:</p><pre>//People variable starting with a empty array of Person<br>@State private var people = [Person]()<br>    <br>    var body: some View {<br>        VStack {<br>            List(people) { person in<br>                HStack(spacing: 20) {<br>                    Text(person.first)<br>                    <br>                    Spacer()<br>                    <br>                    Text(person.last)<br>                }<br>            }<br>        }<br>        .onAppear {<br>            people = decode(&quot;people.json&quot;)<br>        }<br>    }</pre><p>The layout is very simple, just a <strong>VStack</strong> with a <strong>List</strong> and a <strong>HStack</strong> with two <strong>Text</strong> to show Person first and last name. Look at the <strong>List</strong>, we’re passing just the array because our Person struct conforms with Identifiable protocol, so we don’t need to pass <strong>id:</strong> parameter. In the <strong>onAppear</strong> modifier I call the function <strong>decode</strong> with the name of our <strong>json file</strong> and update the people array. That’s all, I hope the post helps you, if have any question let me know on the comments. The source code for this project can be found <a href="https://github.com/netolobo/LoadingDataFromJsonSwiftUI/tree/main/LoadingDataFromJsonSwiftUI">here</a>. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18f0486f8de9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding custom font to a SwiftUI Text]]></title>
            <link>https://medium.com/@desilio/adding-custom-font-to-a-swiftui-text-a2033e7ff6df?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2033e7ff6df</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[custom-fonts]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 23:27:57 GMT</pubDate>
            <atom:updated>2023-11-15T23:27:57.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90ODjCJCAaSABVe86VEKtg.png" /></figure><p>If you need customize your SwiftUI Text with a custom font you came to the right place. Firstly you need some fonts to use I recommend you take a look at the Google Font <a href="https://fonts.google.com/">website </a>where you can find a lot of fonts for free.</p><p>I created a new project from scratch to show you what to do. After you choose the font that fits with your design, download it, in my case I downloaded 3 fonts, created a folder named fonts and put all the fonts there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JBO8Vo3qibitJuf2s2hng.png" /><figcaption>These are the fonts that I downloaded inside the fonts folder that I’ve just created</figcaption></figure><p>Next step is drag and drop the fonts folder to your project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okF83TaqAaNZBvYqnWMz1w.png" /><figcaption>Make sure you will drop the fonts inside your project folder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eDZtyj_sXK3uImolPV90Kg.png" /><figcaption>Make sure you check the options<strong> Copy items if needed</strong> and <strong>create groups</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ri_i0mEr4JQviSFozthVaQ.png" /></figure><p>Now it’s time for the second step, you need to open your <strong>info.plist</strong> file, click on the name of your project, left side, <strong>blue icon</strong>, customFontSwiftUI in my case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhaZACiXaRWBstieY2Akgw.png" /></figure><p>On <strong>Custom iOS Target properties</strong> add a new entrance and select <strong>Fonts provided by application.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6bYm4eOtS0sXE3EBAGdtw.png" /></figure><p>Add the 3 fonts as showed bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsqYZiPj0u9s7rw7AJoq9Q.png" /><figcaption>Pay attention to include the exactly name of the font and also the extension in our case .ttf</figcaption></figure><p>Next step is show our fonts, for this propose I’ve just created a simple screen using a VStack and 3 Texts.</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    var body: some View {<br>        VStack (spacing: 40) {<br>            Text(&quot;Give me a clap&quot;)<br>                .font(.custom(&quot;Agbalumo-Regular&quot;, size: 35))<br>            <br>            Text(&quot;if this tutorial&quot;)<br>                .font(.custom(&quot;Lobster-Regular&quot;, size: 35))<br>            <br>            Text(&quot;was useful for you!&quot;)<br>                .font(.custom(&quot;Zeyada&quot;, size: 35))<br>        }<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><p>To load our fonts I use <strong>.font </strong>modifier with .<strong>custom</strong> parameter that receives the <strong>name of the font</strong> (you don’t need to put the extension or the path to the font) and its <strong>size</strong> as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQ8m6xlhFPoIzNxfKPmfSg.png" /><figcaption>This is the result</figcaption></figure><p>That’s it, I hope this tutorial was useful for you, the project used is available on my <a href="https://github.com/netolobo/CustomFontSwiftUI/tree/main">Github</a> repository, if you have any question please let me know on the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2033e7ff6df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to play videos from an URL with AVPlayer and SwiftUI]]></title>
            <link>https://medium.com/@desilio/how-to-play-videos-from-an-url-with-avplayer-and-swiftui-bd4fb076b82d?source=rss-4cdbd2a1a82d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd4fb076b82d</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[vi̇deo]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[avplayer]]></category>
            <dc:creator><![CDATA[Desilio Neto]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 05:26:09 GMT</pubDate>
            <atom:updated>2024-04-03T16:07:15.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqndO_uer7C4-iox6eQ79A.png" /></figure><p>Today I gonna show you how to play videos from an URL using AVPlayer and SwiftUI, just to let you know is also possible play videos from the AppBundle but it’s a subject to another post.</p><p>Let’t start, playing videos using AVPlayer is very easy, I created a sample project to show you how it works. We need basically two Views, the first view has the NavigationLink to our second view that is the video player itself:</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    var body: some View {<br>        NavigationStack {<br>            VStack {<br>                NavigationLink(&quot;Play Video&quot;) {<br>                    VideoPlayerView()<br>                }<br>                .buttonStyle(.bordered)<br>            }<br>        }<br>        <br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><p>This is the first screen, I just wrapped a NavigationLink with a VStack and a NavigationStack, to navigate to VideoPlayerView (the view that’s really matter for us)</p><pre>import SwiftUI<br>import AVKit<br><br>struct VideoPlayerView: View {<br>    @State private var player = AVPlayer()<br>    <br>    var body: some View {<br>        VideoPlayer(player: player)<br>            .edgesIgnoringSafeArea(.all)<br>            .navigationBarBackButtonHidden()<br>            .onAppear {<br>                let url = URL(string: &quot;https://embed-ssl.wistia.com/deliveries/cc8402e8c16cc8f36d3f63bd29eb82f99f4b5f88/accudvh5jy.mp4&quot;)!<br>                <br>                player = AVPlayer(url: url)<br>                player.play()<br>                <br>            }<br>            .onDisappear {<br>                player.pause()<br>            }<br>    }<br>}<br><br>#Preview {<br>    VideoPlayerView()<br>}</pre><p>This is our VideoPlayerView and I’ll explain everything we need to new about it. First of all I imported <strong>AVkit</strong> framework, this framework is already included in iOS SDK. Secondly a declared a @State property of <strong>AVPlayer</strong> with the default initialiser.</p><p>To our video to be showed we need a instance of<strong> VideoPlayer</strong> struct passing the <strong>player </strong>property previously created as parameter, then I set 2 modifiers <strong>.edgesIgnoringSafeArea(.all)</strong> and <strong>.navigationBarBackButtonHidden()</strong> just for design propose you don’t need then to play your video, the <strong>first one</strong> make the video screen background fill all the screen including the safe area and the <strong>second one</strong>, hide the backButton from the screen.</p><p>And last but not least you have the <strong>.onAppear</strong> and <strong>onDisappear </strong>modifiers, on <strong>.onAppear</strong> I set the video URL and update the property player and then I called the play() method, It’ll make the video to be player as soon as the view appear and on <strong>onDisappear</strong> modifier I call the pause() method to pause the video as soon as the view disappear.</p><p>That’s all, I’ve tried to make this post as simple as possible, of course VideoPlayer has more method that you can use and you can find the full documentation <a href="https://developer.apple.com/documentation/avfoundation/avplayer">here</a>. I also created a repository of this project on my <a href="https://github.com/netolobo/VideoPlayerSwiftUI/tree/main/VideoPlayerSwiftUI">GitHub</a>.</p><p>I hope the post was useful to you, if you have any doubt, let me know on the comments, happy coding and until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd4fb076b82d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>