<?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 Cagrigider on Medium]]></title>
        <description><![CDATA[Stories by Cagrigider on Medium]]></description>
        <link>https://medium.com/@cagrigider?source=rss-e41cad8721b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eOl6QUXzMx6U-_vo</url>
            <title>Stories by Cagrigider on Medium</title>
            <link>https://medium.com/@cagrigider?source=rss-e41cad8721b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:50:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cagrigider/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[SwiftUI App Intents and Navigation with Speech — Part-2]]></title>
            <link>https://medium.com/@cagrigider/swiftui-app-intents-and-navigation-with-speech-part-2-e05ea697326c?source=rss-e41cad8721b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e05ea697326c</guid>
            <dc:creator><![CDATA[Cagrigider]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 10:51:48 GMT</pubDate>
            <atom:updated>2026-03-28T10:51:48.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhqblybG7W5CCrtcJRN92A.jpeg" /></figure><p>This is the second part of the article on Speech Navigation in iOS apps. In this part, we will add a custom sheet to our app and in this sheet, we will implement Apple’s Speech recognition example to our app to move our feature one more step further, “Navigation with Speech”.</p><p>If you missed the first part you can read from <a href="https://medium.com/@cagrigider/swiftui-app-intents-and-navigation-with-speech-part-1-ad7fba84aa58"><strong>here</strong></a>.</p><p>Firstly, we will add Apple’s example SpeechRecognizer class to our app. You can find it from <a href="https://developer.apple.com/tutorials/app-dev-training/transcribing-speech-to-text"><strong>here</strong></a>.</p><pre>import Foundation<br>import AVFoundation<br>import Speech<br>import SwiftUI<br><br><br>/// A helper for transcribing speech to text using SFSpeechRecognizer and AVAudioEngine.<br>actor SpeechRecognizer: ObservableObject {<br>    enum RecognizerError: Error {<br>        case nilRecognizer<br>        case notAuthorizedToRecognize<br>        case notPermittedToRecord<br>        case recognizerIsUnavailable<br>        <br>        var message: String {<br>            switch self {<br>            case .nilRecognizer: return &quot;Can&#39;t initialize speech recognizer&quot;<br>            case .notAuthorizedToRecognize: return &quot;Not authorized to recognize speech&quot;<br>            case .notPermittedToRecord: return &quot;Not permitted to record audio&quot;<br>            case .recognizerIsUnavailable: return &quot;Recognizer is unavailable&quot;<br>            }<br>        }<br>    }<br>    <br>    @MainActor var transcript: String = &quot;&quot;<br>    <br>    private var audioEngine: AVAudioEngine?<br>    private var request: SFSpeechAudioBufferRecognitionRequest?<br>    private var task: SFSpeechRecognitionTask?<br>    private let recognizer: SFSpeechRecognizer?<br>    <br>    /**<br>     Initializes a new speech recognizer. If this is the first time you&#39;ve used the class, it<br>     requests access to the speech recognizer and the microphone.<br>     */<br>    init() {<br>        recognizer = SFSpeechRecognizer()<br>        guard recognizer != nil else {<br>            transcribe(RecognizerError.nilRecognizer)<br>            return<br>        }<br>        <br>        Task {<br>            do {<br>                guard await SFSpeechRecognizer.hasAuthorizationToRecognize() else {<br>                    throw RecognizerError.notAuthorizedToRecognize<br>                }<br>                guard await AVAudioSession.sharedInstance().hasPermissionToRecord() else {<br>                    throw RecognizerError.notPermittedToRecord<br>                }<br>            } catch {<br>                transcribe(error)<br>            }<br>        }<br>    }<br>    <br>    @MainActor func startTranscribing() {<br>        Task {<br>            await transcribe()<br>        }<br>    }<br>    <br>    @MainActor func resetTranscript() {<br>        Task {<br>            await reset()<br>        }<br>    }<br>    <br>    @MainActor func stopTranscribing() {<br>        Task {<br>            await reset()<br>        }<br>    }<br>    <br>    /**<br>     Begin transcribing audio.<br>     <br>     Creates a `SFSpeechRecognitionTask` that transcribes speech to text until you call `stopTranscribing()`.<br>     The resulting transcription is continuously written to the published `transcript` property.<br>     */<br>    private func transcribe() {<br>        guard let recognizer, recognizer.isAvailable else {<br>            self.transcribe(RecognizerError.recognizerIsUnavailable)<br>            return<br>        }<br>        <br>        do {<br>            let (audioEngine, request) = try Self.prepareEngine()<br>            self.audioEngine = audioEngine<br>            self.request = request<br>            self.task = recognizer.recognitionTask(with: request, resultHandler: { [weak self] result, error in<br>                self?.recognitionHandler(audioEngine: audioEngine, result: result, error: error)<br>            })<br>        } catch {<br>            self.reset()<br>            self.transcribe(error)<br>        }<br>    }<br>    <br>    /// Reset the speech recognizer.<br>    private func reset() {<br>        task?.cancel()<br>        audioEngine?.stop()<br>        audioEngine = nil<br>        request = nil<br>        task = nil<br>    }<br>    <br>    private static func prepareEngine() throws -&gt; (AVAudioEngine, SFSpeechAudioBufferRecognitionRequest) {<br>        let audioEngine = AVAudioEngine()<br>        <br>        let request = SFSpeechAudioBufferRecognitionRequest()<br>        request.shouldReportPartialResults = true<br>        <br>        let audioSession = AVAudioSession.sharedInstance()<br>        try audioSession.setCategory(.playAndRecord, mode: .measurement, options: .duckOthers)<br>        try audioSession.setActive(true, options: .notifyOthersOnDeactivation)<br>        let inputNode = audioEngine.inputNode<br>        <br>        let recordingFormat = inputNode.outputFormat(forBus: 0)<br>        inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in<br>            request.append(buffer)<br>        }<br>        audioEngine.prepare()<br>        try audioEngine.start()<br>        <br>        return (audioEngine, request)<br>    }<br>    <br>    nonisolated private func recognitionHandler(audioEngine: AVAudioEngine, result: SFSpeechRecognitionResult?, error: Error?) {<br>        let receivedFinalResult = result?.isFinal ?? false<br>        let receivedError = error != nil<br>        <br>        if receivedFinalResult || receivedError {<br>            audioEngine.stop()<br>            audioEngine.inputNode.removeTap(onBus: 0)<br>        }<br>        <br>        if let result {<br>            transcribe(result.bestTranscription.formattedString)<br>        }<br>    }<br>    <br>    <br>    nonisolated private func transcribe(_ message: String) {<br>        Task { @MainActor in<br>            transcript = message<br>        }<br>    }<br>    nonisolated private func transcribe(_ error: Error) {<br>        var errorMessage = &quot;&quot;<br>        if let error = error as? RecognizerError {<br>            errorMessage += error.message<br>        } else {<br>            errorMessage += error.localizedDescription<br>        }<br>        Task { @MainActor [errorMessage] in<br>            transcript = &quot;&lt;&lt; \(errorMessage) &gt;&gt;&quot;<br>        }<br>    }<br>}<br><br><br>extension SFSpeechRecognizer {<br>    static func hasAuthorizationToRecognize() async -&gt; Bool {<br>        await withCheckedContinuation { continuation in<br>            requestAuthorization { status in<br>                continuation.resume(returning: status == .authorized)<br>            }<br>        }<br>    }<br>}<br><br><br>extension AVAudioSession {<br>    func hasPermissionToRecord() async -&gt; Bool {<br>        await withCheckedContinuation { continuation in<br>            requestRecordPermission { authorized in<br>                continuation.resume(returning: authorized)<br>            }<br>        }<br>    }<br>}</pre><p>Firstly, we will add a new parameter to our NavigationRouter to track whether SpeechView is shown or not.</p><pre>@Published var speechPresented = false</pre><p>Then, we will create our new View to handle speech recognition. This view will be accessible from all tabs and navigate through the app.</p><pre>struct SpeechView: View {<br>    @StateObject var speechRecognizer = SpeechRecognizer()<br>    @State var confirmationPopupShowed = false<br>    @State private var isRecording = false<br>    @State private var tab: Tab?<br><br>    var body: some View {<br>        VStack(alignment: .leading) {<br>            Text(&quot;Transcript: \n\(speechRecognizer.transcript)&quot;)<br>                .font(.headline)<br>                .padding()<br>            Spacer()<br>            HStack {<br>                Button(action: {<br>                    startListening()<br>                }, label: {<br>                    Text(&quot;Start&quot;)<br>                })<br>                .padding()<br>                .disabled(isRecording)<br><br>                Button(action: {<br>                    stopListening()<br>                }, label: {<br>                    Text(&quot;Stop&quot;)<br>                })<br>                .padding()<br>                .disabled(!isRecording)<br>            }<br>            .frame(maxWidth: .infinity)<br>        }<br>        .frame(maxWidth: .infinity, maxHeight: .infinity)<br>        .alert(&quot;Confirm \(tab?.rawValue ?? &quot;nil&quot;)&quot;,<br>               isPresented: $confirmationPopupShowed) {<br>            HStack {<br>                Button(role: .destructive, action: {<br>                    navigate()<br>                }, label: {<br>                    Text(&quot;Confirm&quot;)<br>                })<br>                Button(role: .cancel, action: {<br>                }, label: {<br>                    Text(&quot;Cancel&quot;)<br>                        .foregroundStyle(Color.yellow)<br>                })<br>            }<br>        }<br>    }<br><br>    private func startListening() {<br>        isRecording = true<br>        speechRecognizer.resetTranscript()<br>        speechRecognizer.startTranscribing()<br>    }<br><br>    private func stopListening() {<br>        isRecording = false<br>        speechRecognizer.stopTranscribing()<br>        checkTranscriptRoutes()<br>    }<br><br>    private func checkTranscriptRoutes() {<br>        let tabs = Tab.allCases.map { $0.rawValue }<br><br>        var words = speechRecognizer.transcript.split(separator: &quot; &quot;).map { String($0) }<br>        let selectedTab = words.first { word in<br>            tabs.contains(word)<br>        }<br><br>        tab = Tab(rawValue: selectedTab ?? &quot;&quot;)<br>        confirmationPopupShowed = true<br>    }<br><br>    private func navigate() {<br>        NavigationRouter.shared.speechPresented = false<br>        NavigationRouter.shared.push(tab, screen: nil)<br>    }<br>}</pre><p>Now our view is ready for use. This view should be accessible from every view like an emergency button to change the screen. For this, we will implement a new view modifier to make our view reachable through the Navigation Stack. We will add Speakable.swift view modifier to our project. By using this view modifier we will automatically add a mic icon to our navigation stack and we will be able to reach SpeechView from anywhere.</p><pre>import SwiftUI<br><br>struct SpeakableView: ViewModifier {<br>    @StateObject private var router = NavigationRouter.shared<br><br>    func body(content: Content) -&gt; some View {<br>        NavigationStack {<br>            content<br>                .toolbar {<br>                    Button(action: {<br>                        NavigationRouter.shared.speechPresented = true<br>                    }, label: {<br>                        Image(systemName: &quot;mic&quot;)<br>                    })<br>                }<br>                .sheet(isPresented: $router.speechPresented, content: {<br>                    SpeechView()<br>                })<br>        }<br>    }<br>}<br><br>extension View {<br>    func speakable() -&gt; some View {<br>        modifier(SpeakableView())<br>    }<br>}</pre><p>Now, add “speakable” to our views. In our MoviesView and TVSeriesView, we will add the following code under the “.navigatable(…)” part.</p><pre>.speakable()</pre><p>After adding this, we have only 1 more step to finish our Speech Recognition process. We need to add the necessary requests to our Info.plist. file as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIuCx8E6QqUA6qWjTklqkw.png" /></figure><p>After this last update, our app is ready to run. Our app will look like that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KMsSdhlVmJkCqyVF_zsk4w.gif" /></figure><h3>Conclusion</h3><p>In this article, we learned how to add the Speech Recognition feature to our application. We also learned how to create a view that can be opened from all pages by using View Modifier.</p><p>Speech recognition and speech navigation can be very necessary and important in some scenarios. Learning these features and adding them to your applications will take you one step ahead.</p><p>You can review the codes of the app via the link below.</p><p>Happy Coding!</p><p><a href="https://github.com/cagrigider/SpeechDemo.git">https://github.com/cagrigider/SpeechDemo.git</a></p><h3><strong>Resources</strong></h3><p><a href="https://developer.apple.com/tutorials/app-dev-training/transcribing-speech-to-text">Apple Speech Recognition Tutorial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e05ea697326c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI App Intents and Navigation with Speech — Part-1]]></title>
            <link>https://medium.com/adessoturkey/swiftui-app-intents-and-navigation-with-speech-part-1-ad7fba84aa58?source=rss-e41cad8721b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad7fba84aa58</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[siri]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Cagrigider]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 08:21:03 GMT</pubDate>
            <atom:updated>2023-12-25T08:21:03.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>SwiftUI App Intents and Navigation with Speech — Part-1</h3><p>Boost your iOS app with the use of Siri and App Intents features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhqblybG7W5CCrtcJRN92A.jpeg" /></figure><p>Its applications change and develop over time. Nowadays, ease of use and speed are the most important factors for an app. Among the things we can do to increase our app’s ease of use and speed are App Intents, use of Siri, and speech navigation methods. We will touch on these three topics in this article.</p><p>Let’s start exploring.</p><h3><strong>1. Siri Setup</strong></h3><p>To use Siri in our app or launch our app, we need to add the Siri capability to our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2JY1R90tnOdlzGgZ_m-YA.png" /><figcaption>Adding Siri Capability</figcaption></figure><p>Then we need to add the required info.plist key-value pair for “Siri Usage Description”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wz31ru6RPlFQaBfurxWeVQ.png" /><figcaption>Adding Siri Usage Permission Request to Info.plist</figcaption></figure><p>When we try launching our app by using Siri with the command “Open SpeechDemo”, we will get this error. It is because we haven’t added the authentication request for Siri usage yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zybal-MvhJqlqbVQvyNSvg.png" /><figcaption>Error for Siri Usage</figcaption></figure><p>Now let’s add the authentication request. To do this, we will add the AppDelegate file to our project and make the request when the app launches. In the AppDelegate file, we will use Apple’s Intents library and make our authentication request through it.</p><pre>import UIKit<br>import Intents<br><br>class AppDelegate: NSObject, UIApplicationDelegate {<br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -&gt; Bool {<br>        INPreferences.requestSiriAuthorization { status in<br>            if status == .authorized {<br>                print(&quot;Hey, Siri!&quot;)<br>            } else {<br>                print(&quot;Nay, Siri!&quot;)<br>            }<br>        }<br><br>        return true<br>    }<br>}</pre><p>We will also add this AppDelegate to our SpeechDemoApp class to use it.</p><pre>import SwiftUI<br><br>@main<br>struct SpeechDemoApp: App {<br>    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate<br><br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>}</pre><p>Now we can run our app, and then we can start launching our app by using Siri.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPmTwzwiEVQJ9Gbd0n8Ibg.png" /><figcaption>Siri Usage Authentication Request</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*Uyg__WhStUayCzZ3LvDayA.gif" /><figcaption>Launching the app by using Siri</figcaption></figure><p>Now we have succesfully launched our app by using Siri. But it is only capable of opening the app. What if we want to open the app and then navigate to another screen? We can also do this, but we need to make some changes in our code and add navigation logic to our app.</p><h3><strong>2. Navigation Logic</strong></h3><p>We will add a simple navigation logic to our app. It will have two tabs: Movies and TV Series. We won’t add complex UI for them. We will just present the related list in every tab.</p><p>First, we create a simple data model named “DetailItem” to use on our screens. And we make it Identifiable, so we can use it easily in our lists.</p><pre>import Foundation <br><br>struct DetailItem: Identifiable {<br>    let id = UUID()<br>    let name: String<br>    let detail: String<br>}</pre><p>And we add some example data for our tests.</p><pre>extension Array where Element == DetailItem {<br>    static let exampleMovies: [DetailItem] = [<br>        .init(name: &quot;Five Nights at Freddy&#39;s&quot;, detail: &quot;Recently fired and desperate for work, a troubled young man named Mike agrees to take a position as a night security guard at an abandoned theme restaurant: Freddy Fazbear&#39;s Pizzeria. But he soon discovers that nothing at Freddy&#39;s is what it seems.&quot;),<br>        .init(name: &quot;Muzzle&quot;, detail: &quot;LAPD K-9 officer Jake Rosser has just witnessed the shocking murder of his dedicated partner by a mysterious assailant. As he investigates the shooter’s identity, he uncovers a vast conspiracy that has a chokehold on the city in this thrilling journey through the tangled streets of Los Angeles and the corrupt bureaucracy of the LAPD.&quot;),<br>        .init(name: &quot;Saw X&quot;, detail: &quot;Between the events of &#39;Saw&#39; and &#39;Saw II&#39;, a sick and desperate John Kramer travels to Mexico for a risky and experimental medical procedure in hopes of a miracle cure for his cancer, only to discover the entire operation is a scam to defraud the most vulnerable. Armed with a newfound purpose, the infamous serial killer returns to his work, turning the tables on the con artists in his signature visceral way through devious, deranged, and ingenious traps.&quot;),<br>        .init(name: &quot;Retribution&quot;, detail: &quot;When a mysterious caller puts a bomb under his car seat, Matt Turner begins a high-speed chase across the city to complete a specific series of tasks- all with his kids trapped in the back seat.&quot;)<br>    ]<br>    static let exampleSeries: [DetailItem] = [<br>        .init(name: &quot;Tagesschau&quot;, detail: &quot;German daily news program, the oldest still existing program on German television.&quot;),<br>        .init(name: &quot;Elas por Elas&quot;, detail: &quot;Seven friends who met in their youth at an English course meet again 25 years later; Lara, Taís, Helena, Adriana, Renée, Natália and Carol, each of them has a different personality and origin, but they share a deep affection.&quot;),<br>        .init(name: &quot;Law &amp; Order: Special Victims Unit&quot;, detail: &quot;In the criminal justice system, sexually-based offenses are considered especially heinous. In New York City, the dedicated detectives who investigate these vicious felonies are members of an elite squad known as the Special Victims Unit. These are their stories.&quot;),<br>        .init(name: &quot;NCIS&quot;, detail: &quot;From murder and espionage to terrorism and stolen submarines, a team of special agents investigates any crime that has a shred of evidence connected to Navy and Marine Corps personnel, regardless of rank or position.&quot;)<br>    ]<br>}</pre><p>Now we can create our Movies and TVSeries views.</p><pre>import SwiftUI<br><br>struct MoviesView: View {<br>    let exampleMovies: [DetailItem] = .exampleMovies<br><br>    var body: some View {<br>        List(exampleMovies) { movie in<br>            Text(movie.name)<br>        }<br>    }<br>}</pre><pre>import SwiftUI<br><br>struct TVSeriesView: View {<br>    let exampleSeries: [DetailItem] = .exampleSeries<br><br>    var body: some View {<br>        List(exampleSeries) { movie in<br>            Text(movie.name)<br>        }<br>    }<br>}</pre><p>After this, we can change our “ContentView” to show our tabs.</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    var body: some View {<br>        TabView {<br>            MoviesView()<br>                .tabItem { Image(systemName: &quot;movieclapper&quot;) }<br><br>            TVSeriesView()<br>                .tabItem { Image(systemName: &quot;tv&quot;) }<br>        }<br>    }<br>}</pre><p>Now, we need a navigation logic to navigate between screens in the app. First, we will create a Tab enum to have our tabs; second, we will create a Navigation Router class to control and save the navigation status in the app.</p><pre>import Foundation<br><br>enum Tab {<br>    case movies<br>    case tvSeries<br>}</pre><p>Then, we can create our NavigationRouter class.</p><pre>import Foundation<br>import SwiftUI<br><br>final class NavigationRouter: ObservableObject {<br>    @Published var selectedTab: Tab = .movies<br><br>    static var shared: NavigationRouter = NavigationRouter()<br>}</pre><p>After these changes, we also need to update our ContentView to track changes on the router.</p><pre>struct ContentView: View {<br>    @StateObject var router = NavigationRouter.shared<br><br>    var body: some View {<br>        TabView(selection: $router.selectedTab) {<br>            MoviesView()<br>                .tabItem { Image(systemName: &quot;movieclapper&quot;) }<br>                .tag(Tab.movies)<br><br>            TVSeriesView()<br>                .tabItem { Image(systemName: &quot;tv&quot;) }<br>                .tag(Tab.tvSeries)<br>        }<br>    }<br>}</pre><p>After all these changes, our app will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuu_W_yX5qUQNfuyg1mB-A.png" /></figure><p>Let’s add a basic detail screen to show movie or TV series details and improve our navigation logic. To do this, first we create a Route enum and add our “detail” screen to it as a case, and then we write the necessary extensions to make it easy to use.</p><pre>import SwiftUI<br><br>struct DetailView: View {<br>    var item: DetailItem<br><br>    var body: some View {<br>        VStack {<br>            Text(item.name)<br>                .font(.title)<br>            Text(item.detail)<br>                .font(.subheadline)<br>        }<br>    }<br>}</pre><pre>import SwiftUI<br>import Foundation<br><br>enum Route {<br>    case detail(item: DetailItem)<br>}<br><br>extension Route: View {<br>    var body: some View {<br>        switch self {<br>        case .detail(let item):<br>            DetailView(item: item)<br>        }<br>    }<br>}<br><br>extension Route: Hashable {<br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(self.hashValue)<br>    }<br><br>    static func == (lhs: Route, rhs: Route) -&gt; Bool {<br>        switch (lhs, rhs) {<br>        case (.detail(let lhsValue), .detail(let rhsValue)):<br>            return lhsValue.id == rhsValue.id<br>        }<br>    }<br>}</pre><p>New NavigationRouter.swift ;</p><pre>final class NavigationRouter: ObservableObject {<br>    @Published var selectedTab: Tab = .movies<br>    @Published var moviesRoutes = NavigationPath()<br>    @Published var tvSeriesRoutes = NavigationPath()<br><br>    static var shared: NavigationRouter = NavigationRouter()<br><br>    func push(_ tab: Tab? = nil, screen: Route?) {<br>        if let tab {<br>            selectedTab = tab<br>        }<br><br>        guard let screen else { return }<br><br>        switch selectedTab {<br>        case .movies:<br>            moviesRoutes.append(screen)<br>        case .tvSeries:<br>            tvSeriesRoutes.append(screen)<br>        }<br>    }<br>}</pre><p>After these changes, we will add some “Swifty” codes to make our app tabs navigatable with individual NavigationStacks. For this, we will create a “NavigatableView” view modifier and make our tabs “navigatable”.</p><pre>struct NavigatableView: ViewModifier {<br>    @Binding var route: NavigationPath<br><br>    func body(content: Content) -&gt; some View {<br>        NavigationStack(path: $route) {<br>            content<br>                .navigationDestination(for: Route.self) { value in<br>                    value<br>                }<br>        }<br>    }<br>}<br><br>extension View {<br>    func navigatable(route: Binding&lt;NavigationPath&gt;) -&gt; some View {<br>        modifier(NavigatableView(route: route))<br>    }<br>}</pre><p>Then we will add these two lines of code to our MoviesView and apply the same exact changes to the TVSeriesView file.</p><pre>struct MoviesView: View {<br>    @StateObject var router = NavigationRouter.shared  // To have router<br><br>    let exampleMovies: [DetailItem] = .exampleMovies<br><br>    var body: some View {<br>        List(exampleMovies) { movie in<br>            Text(movie.name)<br>        }<br>        .navigatable(route: $router.moviesRoutes)  // To make this view navigatable<br>    }<br>}</pre><p>After this, we can move to the second part, where we will use the App Intent feature.</p><h3><strong>3. App Intents</strong></h3><p>Now that we have an app with two tabs and one detail screen, we have good navigation logic. So, let’s open our app by using Siri with the TVSeries tab. By creating App Intent, we will be able to launch our app with Siri and App Shortcuts.</p><p>Let’s start by creating our AppIntent named “Open Screen Intent”.</p><p>This struct needs to conform to the AppIntent protocol. To do this, we must have the two following parts:</p><ul><li>Title: To define the name of the App Intent.</li><li>perform(): To handle operations and logic after the Intent is called.</li></ul><p>Also, we will add another static parameter named “openAppWhenRun” with a true value to show that we want our app to open directly after the intent is called.</p><pre>import AppIntents<br><br>struct OpenScreenIntent: AppIntent {<br>    static var title: LocalizedStringResource = &quot;Open Speech Screen&quot;<br>    static var description: IntentDescription? = .init(stringLiteral: &quot;Open a screen in Speech Demo App&quot;)<br><br>    static var openAppWhenRun: Bool = true<br><br>    func perform() async throws -&gt; some IntentResult {<br>        return .result()<br>    }<br>}</pre><p>Now, we have our basic AppIntent, but we are not using it yet. To use it, we will add an AppShortcutsProvider. In this struct, we will define which shortcuts our app will have and how they will be called. Define our “SpeechAppShortcutProvider” as below. Then we will have an App Shortcut listen in the device.</p><pre>struct SpeechAppShortcutProvider: AppShortcutsProvider {<br>    static var appShortcuts: [AppShortcut] {<br>        AppShortcut(<br>            intent: OpenScreenIntent(),<br>            phrases: [<br>                &quot;Open \(.applicationName)&quot;<br>            ],<br>            shortTitle: &quot;Open app screen&quot;,<br>            systemImageName: &quot;popcorn.fill&quot;<br>        )<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Px_H3wLUdI-DzwmfMImyzQ.png" /><figcaption>App Shortcut</figcaption></figure><h3><strong>4. Customize Shortcut and Intent</strong></h3><p>We created our App Intent and shortcuts, but it can only launch our app as the default Siri action. It is time to customize our App Intent and Shortcut.</p><p>First, we will change our shortcut’s caller a little bit to make it different than the default open command for Siri.</p><pre>struct SpeechAppShortcutProvider: AppShortcutsProvider {<br>    static var appShortcuts: [AppShortcut] {<br>        AppShortcut(<br>            intent: OpenScreenIntent(),<br>            phrases: [<br>                &quot;Open \(.applicationName) with custom screen&quot;<br>            ],<br>            shortTitle: &quot;Open Speech App&quot;,<br>            systemImageName: &quot;popcorn.fill&quot;<br>        )<br>    }<br>}</pre><p>Then, we will modify our Tab enum to conform to String and AppEnum. So, we can create a question for the user to select the tab.</p><pre>enum Tab: String, AppEnum {<br>    static var typeDisplayRepresentation: TypeDisplayRepresentation = &quot;Tab&quot;<br>    static var caseDisplayRepresentations: [Tab : DisplayRepresentation] =  [<br>        .movies: .init(stringLiteral: &quot;movies&quot;),<br>        .tvSeries: .init(stringLiteral: &quot;tvSeries&quot;)<br>    ]<br><br>    case movies<br>    case tvSeries<br>}</pre><p>Now we need to modify our App Intent to request parameters and use them to navigate in the app.</p><pre>struct OpenScreenIntent: AppIntent {<br>    static var title: LocalizedStringResource = &quot;Open Speech Screen&quot;<br>    static var description: IntentDescription? = .init(stringLiteral: &quot;Open a screen in Speech Demo App&quot;)<br><br>    static var openAppWhenRun: Bool = true<br><br>    @Parameter(<br>        title: &quot;tab&quot;,<br>        requestDisambiguationDialog: &quot;Which Tab?&quot;<br>    )<br>    var appTab: Tab<br><br><br>    func perform() async throws -&gt; some IntentResult {<br>        NavigationRouter.shared.push(appTab, screen: nil)<br><br>        return .result()<br>    }<br>}</pre><p>Now this intent can be used to open our app with a provided tab. Let’s move one step further and add another App Intent to open the detail screen for given movie or TV series.</p><h3><strong>5. App Intent for Detail</strong></h3><p>First, we need to add a new variable to our NavigationRouter so that we can track the changes to the item in the app. Add the below code to “NavigationRouter.swift”.</p><pre>@Published var detailItemName: String?</pre><p>Then we need to modify our “MoviesView.swift” and make the same changes to the “TVSeriesView.swift”.</p><pre>struct MoviesView: View {<br>    @StateObject var router = NavigationRouter.shared<br><br>    let exampleMovies: [DetailItem] = .exampleMovies<br><br>    var body: some View {<br>        List(exampleMovies) { movie in<br>            Text(movie.name)<br>        }<br>        .navigatable(route: $router.moviesRoutes)<br>        .onAppear {<br>            self.checkForDetail()<br>        }<br>    }<br><br>    private func checkForDetail() {<br>        guard let detailItemName = router.detailItemName,<br>              let detailItem = exampleMovies.first(where: { $0.name == detailItemName }) else { return }<br><br>        router.detailItemName = nil<br>        router.moviesRoutes.append(Route.detail(item: detailItem))<br>    }<br>}</pre><p>Now our views are ready to check the detail item and open it on the detail screen. We also need to add a new App Intent and a new App Shortcut to use the intent.</p><pre>struct OpenDetailScreenIntent: AppIntent {<br>    static var title: LocalizedStringResource = &quot;Open Detail Screen&quot;<br>    static var description: IntentDescription? = .init(stringLiteral: &quot;Open detail screen in Speech Demo App&quot;)<br><br>    static var openAppWhenRun: Bool = true<br><br>    @Parameter(<br>        title: &quot;tab&quot;,<br>        requestDisambiguationDialog: &quot;Which Tab?&quot;<br>    )<br>    var appTab: Tab<br><br><br>    @IntentParameter(title: &quot;itemName&quot;, requestValueDialog: &quot;Which movie/tv series would you like to see?&quot;)<br>    var itemName: String<br><br>    func perform() async throws -&gt; some IntentResult {<br>        NavigationRouter.shared.detailItemName = itemName<br><br>        NavigationRouter.shared.push(appTab, screen: nil)<br><br>        return .result()<br>    }<br>}</pre><pre>AppShortcut(<br>    intent: OpenDetailScreenIntent(),<br>    phrases: [<br>        &quot;Open \(.applicationName) detail screen&quot;<br>    ],<br>    shortTitle: &quot;Open Speech App&quot;,<br>    systemImageName: &quot;popcorn.fill&quot;<br>)</pre><p>After all the changes, opening the app should be looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5kPjCRXOGRpQHlh2Vy-1JQ.gif" /><figcaption>Final</figcaption></figure><h3>Conclusion</h3><p>It is important that we use innovations to keep up with the changing and accelerating world conditions. App Intent and App Shortcut features are nice features offered to us by Apple. We saw how we can increase the quality and ease of use of our applications by using these features.</p><p>You can review the codes of the app via the link below.</p><p>Happy Coding!</p><p><a href="https://github.com/cagrigider/SpeechDemo.git">https://github.com/cagrigider/SpeechDemo.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad7fba84aa58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/swiftui-app-intents-and-navigation-with-speech-part-1-ad7fba84aa58">SwiftUI App Intents and Navigation with Speech — Part-1</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MapKit — Next Level Map Experience]]></title>
            <link>https://medium.com/adessoturkey/mapkit-next-level-map-experience-5eb8fc8870ba?source=rss-e41cad8721b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eb8fc8870ba</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mapkit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Cagrigider]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 11:29:40 GMT</pubDate>
            <atom:updated>2023-09-12T10:38:44.004Z</atom:updated>
            <content:encoded><![CDATA[<h3>MapKit — Next Level Map Experience</h3><p>Take your app’s user experience to the next level using custom annotations and clustering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*ws9NPQeeZev5XhO3X6AHvA.png" /><figcaption>Map with custom annotations and custom cluster annotations</figcaption></figure><p>Today, maps are used in most applications. Even if the map does not constitute the entire application, it takes up a very important place in applications. For this reason, it is very important to use the map and map features correctly in practice. The pin design and colors to be displayed on the map should be specific to the application, ensuring cohesion with the application and making the map pleasing to the eye.</p><p>Let’s go over how to use a map in an iOS app.</p><h3><strong>Map Setup</strong></h3><p>First, we add the map to our storyboard, which belongs to our ViewController that we will use. Then we complete the connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAaqFuJ80UDVtQxQ_QeSOg.png" /></figure><p>After we finish setting up the storyboard, we can continue preparing our view controller class.</p><p>For this, we first create a function called “setupMapView”. In this function, we set the required properties of the map and the delegate. We also set the location where we want the map to open. Since we do not take the user’s location, we give a fixed point for testing.</p><pre>private func setupMapView() {<br>  mapView.delegate = self<br>  mapView.showsUserLocation = false<br><br>  let region = MKCoordinateRegion(center: .init(latitude: 35.278259, longitude: -119.5), latitudinalMeters: 500000, longitudinalMeters: 500000)<br>  mapView.setRegion(region, animated: false)<br>}</pre><p>After this, we create a CustomAnnotation class and two new functions in the ViewController.swift to create example annotation data to show on the map.</p><pre>private func addExamplePoints() {<br>        /// Removing existing annotations before adding new ones<br>        let oldAnnotations = self.mapView.annotations<br>        mapView.removeAnnotations(oldAnnotations)<br><br>        /// Generating and adding new annotations to the map<br>        let points = generateExamplePoints(40)<br>        mapView.addAnnotations(points)<br>}<br><br>private func generateExamplePoints(_ pointsCount: Int) -&gt; [CustomAnnotation] {<br>        var points: [CustomAnnotation] = []<br><br>        /// Generating sample points based on the given count<br>        for _ in 0..&lt;pointsCount {<br>            let latitude = Double.random(in: 34.0 ... 36.0)<br>            let longitude = Double.random(in: -121.0 ... -119.0)<br>            let annotation = CustomAnnotation(latitude: latitude, longitude: longitude)<br>            points.append(annotation)<br>        }<br><br>        return points<br>}</pre><pre>import MapKit<br><br>class CustomAnnotation: NSObject, MKAnnotation {<br>    var coordinate: CLLocationCoordinate2D<br><br>    init(latitude: Double, longitude: Double){<br>        self.coordinate = CLLocationCoordinate2DMake(latitude, longitude)<br>    }<br>}</pre><p>After adding our new class and new functions, we can call setupMapView, addExamplePoints functions in the viewDidLoad function of our ViewController.swift file.</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        setupMapView()<br>        addExamplePoints()<br>}</pre><p>Now we can create our MKMapViewDelegate with ViewController class file, to reach map features and complete the initial setup of our map.</p><p>We simply create a new file named ViewController+Map.swift, and in the file, we create our ViewController extension to use MKMapViewDelegate functions as shown in the below code.</p><pre>import MapKit<br><br>extension ViewController: MKMapViewDelegate {<br>    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -&gt; MKAnnotationView? {<br>        if annotation is MKUserLocation {<br>            return nil<br>        }<br>        return MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)<br>    }<br>}</pre><p>After this, we can run and see the first output of our map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*03nrs48XpZJl-uWaUK1MYQ.png" /><figcaption>Map with example pins.</figcaption></figure><p>Now we can start customizing our map and user experience.</p><h3>Custom Annotations</h3><p>To use custom annotations on the map in Swift, we need to create a custom class from MKAnnotationView. For this project, we will create a CustomAnnotationView.swift file, and for the design of the annotation, we will create a CustomAnnotationView.xib file. Also, for making our imageView circle, we will create a IBDesignable class for UIImageView.</p><pre>import MapKit<br><br>class CustomAnnotationView: MKAnnotationView {<br>    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {<br>        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)<br>        commonInit()<br>    }<br><br>    required init?(coder aDecoder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br><br>    private func commonInit() {<br>        let view = self.nibInstantiate(autoResizingMask: [.flexibleHeight, .flexibleWidth])<br>        self.frame = view.frame<br>        addSubview(view)<br>    }<br>}</pre><pre>import UIKit<br><br>@IBDesignable<br>class CircleImageView: UIImageView {<br><br>    @IBInspectable<br>    var circle: Bool {<br>        set {<br>            self.isCircle = newValue<br>            self.setCircle()<br>        }<br>        get { self.isCircle }<br>    }<br>    <br>    private var isCircle: Bool = false<br><br>    private func setCircle() {<br>        if isCircle {<br>            layer.cornerRadius = bounds.size.width / 2<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrh8iaFExcUbEVBSKxmyXg.png" /><figcaption>CustomAnnotationView.xib</figcaption></figure><p>Now we need to tell the map that we will use our new CustomAnnotationView instead of the default marker on the map. To do this, we need to edit the delegate function in the ViewController as shown below.</p><pre>import MapKit<br><br>extension ViewController: MKMapViewDelegate {<br>    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -&gt; MKAnnotationView? {<br>        if annotation is MKUserLocation {<br>            return nil<br>        }<br><br>        if annotation is CustomAnnotation {<br>            guard let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier) as? CustomAnnotationView else {<br>                return CustomAnnotationView(annotation: annotation, reuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)<br>            }<br>            annotationView.annotation = annotation<br>            return annotationView<br>        }  else {<br>            return MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)<br>        }<br>    }<br>}</pre><p>And now we can see our beautiful custom pins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*NvB9BJlYDutcW_2ZewfRxQ.png" /><figcaption>Map with custom pins</figcaption></figure><h3>Clustering</h3><p>Another feature that needs to be done for more visually pleasing and easy-to-use maps is “Clustering”. Clustering is enabled by default for the default markers of Apple. However, since we are using custom annotations, we need to create custom clustered annotations.</p><p>To use the clustering feature, we will first create our CustomClusterAnnotationView.swift and CustomClusterAnnotationView.xib files. We will also add a UILabel to our custom-designed pins to show how many pins are clustered under this cluster pin.</p><pre>import UIKit<br>import MapKit<br><br>class CustomClusterAnnotationView: MKAnnotationView {<br>    @IBOutlet private weak var countLabel: UILabel!<br><br>    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {<br>        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)<br>        let clusterAnnotation = annotation as? MKClusterAnnotation<br>        commonInit()<br>        setUI(with: clusterAnnotation)<br>    }<br><br>    required init?(coder aDecoder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br><br>    private func commonInit() {<br>        let view = self.nibInstantiate(autoResizingMask: [.flexibleHeight, .flexibleWidth])<br>        self.frame = view.frame<br>        addSubview(view)<br>    }<br><br>    private func setUI(with clusterAnnotation: MKClusterAnnotation?) {<br>        if let count = clusterAnnotation?.memberAnnotations.count {<br>            countLabel.text = count.description<br>        } else {<br>            countLabel.text = nil<br>            countLabel.isHidden = true<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfW-bwaeXNrwczLjtD8sPw.png" /><figcaption>CustomClusterAnnotationView.xib</figcaption></figure><p>After this, we need to change some code in our MapView delegate function. Then we need to identify that all our pins can be clustered under the same pin, because we have only one type of annotation now.</p><pre>import MapKit<br><br>extension ViewController: MKMapViewDelegate {<br>    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -&gt; MKAnnotationView? {<br>        if annotation is MKUserLocation {<br>            return nil<br>        }<br><br>        if annotation is CustomAnnotation {<br>            guard let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier) as? CustomAnnotationView else {<br>                return CustomAnnotationView(annotation: annotation, reuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)<br>            }<br>            annotationView.annotation = annotation<br>            annotationView.clusteringIdentifier  = MKMapViewDefaultClusterAnnotationViewReuseIdentifier<br>            return annotationView<br>        } else if annotation is MKClusterAnnotation {<br>            return CustomClusterAnnotationView(annotation: annotation, reuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)<br>        } else {<br>            return MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)<br>        }<br>    }<br>}</pre><p>Now, we will be able to see our annotations clustered when we zoom out of the map, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*3_abkJCrRf9uL_-prcK08w.png" /><figcaption>Final looking of the map</figcaption></figure><h4>Conclusion</h4><p>As you can see, we have brought the usability and readability of the map used in the application to the next level in a short time. You can make different designs for pins and clustered pins and take your application further.</p><p>Today, the designs of applications play a very important role, so fine details in this way will positively affect both the memorability and the user experience.</p><p>You can review the codes of the application via the link below.</p><p>Happy Coding!</p><p><a href="https://github.com/cagrigider/Map-UIKit">https://github.com/cagrigider/Map-UIKit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eb8fc8870ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/mapkit-next-level-map-experience-5eb8fc8870ba">MapKit — Next Level Map Experience</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Previews: Supercharge Your Development]]></title>
            <link>https://medium.com/@cagrigider/swiftui-previews-supercharge-your-development-7dd77d71454f?source=rss-e41cad8721b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dd77d71454f</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[preview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Cagrigider]]></dc:creator>
            <pubDate>Mon, 29 May 2023 16:02:41 GMT</pubDate>
            <atom:updated>2023-05-29T16:02:41.901Z</atom:updated>
            <content:encoded><![CDATA[<p>SwiftUI provides developers with a powerful feature called “previews.” With SwiftUI previews, you can instantly visualize your views and layouts directly in Xcode without the need to run your app. This powerful tool not only saves you time but also enhances your development workflow by allowing you to iterate quickly and visually test your user interfaces. In this article, we’ll explore how to make the most of SwiftUI previews, leverage the Modifier system, and uncover the secrets to efficiently enhancing your development workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8Rqu5F6ym5iEmLj2qZXnA.png" /></figure><h3>Instantaneous Feedback</h3><p>One of the key advantages of SwiftUI previews is the ability to receive immediate feedback on your UI changes. As you make modifications to your views, SwiftUI previews update in real-time, providing you with instant feedback on how your changes impact the overall layout and appearance. This feature significantly accelerates your development process by eliminating the need to rebuild and run your app repeatedly. Take advantage of this feature by leveraging the live preview canvas to make iterative adjustments and fine-tune your user interfaces. Let’s add some list and text to our project and see the changes without run the application.</p><pre>let exampleList = [<br>        &quot;apples&quot;,<br>        &quot;oranges&quot;,<br>        &quot;carrots&quot;,<br>        &quot;mango&quot;,<br>        &quot;brocoli&quot;,<br>        &quot;chillipowder&quot;,<br>        &quot;onions&quot;<br>    ]<br>    var body: some View {<br>        VStack {<br>            Text(&quot;I ❤️ SwiftUI&quot;)<br><br>            List {<br>                ForEach(exampleList, id: \.self) { value in<br>                    Text(value)<br>                }<br>            }<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*504mjetv7kVrFg4J9z2VpA.png" /></figure><h3>Configuration and Environment</h3><p>SwiftUI previews allow you to configure various aspects of your interface, enabling you to test your views under different scenarios. By customizing device types, orientations, accessibility settings, and even language localization, you can ensure that your app works seamlessly across different configurations. For example, you can preview your views in different device sizes to ensure proper responsiveness. By exploring different configurations, you can identify any layout issues or UI inconsistencies that may arise in specific scenarios and optimize your views accordingly. Let’s check how is the application is looking in dark and light mode devices. To see this, we need to change the view at the bottom left of the preview screen. Under “Variants” section, we will select “Color Variants”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQAunSxCPyrzm19WYPsB0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NuZhE4xkHiQKtEkImlIQ0g.png" /></figure><h3>Parameterized Previews</h3><p>In addition to static previews, SwiftUI offers parameterized previews. This feature allows you to pass specific data or configurations to your views during the preview phase, simulating different scenarios and states. By utilizing parameterized previews, you can evaluate how your views respond to different inputs, such as varying data sets or user interactions. This capability is particularly useful for testing edge cases and ensuring the robustness of your UI components. For example, you can test how your view behaves when it receives different data types or handles user interactions like tapping, scrolling, or gestures. Now let’s change our view to get count of the array as parameter.</p><pre>var arrayCount: Int = 1<br>    var body: some View {<br>        VStack {<br>            Text(&quot;I ❤️ SwiftUI&quot;)<br><br>            List {<br>                ForEach((0..&lt;arrayCount), id: \.self) { value in<br>                    Text(value.description)<br>                }<br>            }<br>        }<br>    }</pre><p>Also we need to add a different version of our view, to see how it works with different parameters.</p><pre>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>        ContentView(arrayCount: 30)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFr7I2IIvPf9bcknUbpQkA.png" /></figure><p>Now we see there is 2 Content View on the top of the preview screen. 1 preview for each ContentView we used under the preview variable on the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*so5SKxZgIMbVX8QToHDW2A.png" /></figure><h3>Preview Groups and Compositions</h3><p>SwiftUI provides the ability to group and compose multiple views together in previews, mimicking complex view hierarchies and component interactions. By using preview groups, you can examine how different views interact with one another, ensuring proper alignment and behavior. This feature is particularly useful when working with intricate layouts or nested view structures. Furthermore, you can create reusable preview compositions, simplifying the process of visualizing commonly used components across different screens or modules in your app. This promotes code reusability and improves the overall maintainability of your SwiftUI projects.</p><h3>Preview Providers</h3><p>If your views rely on external data sources or dependencies, SwiftUI allows you to provide custom preview data using preview providers. This feature lets you mock or simulate data dependencies within your previews, ensuring that your views render correctly even when external data sources are unavailable. By using preview providers, you can cover various scenarios and verify that your views handle data dependencies gracefully. This helps you identify and fix potential issues related to data integration early on in the development process, providing a smoother experience when integrating real data into your app. For example, let’s change our device’s orientation and color scheme values.</p><pre>static var previews: some View {<br>        ContentView()<br>            .previewInterfaceOrientation(.landscapeLeft)<br>            .preferredColorScheme(.dark)<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGBzX48fpHcXuGK5aVzY9g.png" /></figure><h3>Conclusion</h3><p>SwiftUI previews revolutionize the development workflow by providing instant visual feedback and allowing you to iterate quickly. By leveraging this powerful tool, you can streamline your development process, identify and resolve layout issues early on, and create robust user interfaces. Experiment with different configurations, use parameterized previews for edge case testing, explore preview groups and compositions, and utilize preview providers to simulate data dependencies. With SwiftUI previews at your disposal, you’ll be well-equipped to create visually stunning and highly functional apps.</p><p>Remember, SwiftUI previews are not only a time-saving feature but also a catalyst for creativity and innovation. Embrace this tool and let it empower your development process to new heights. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dd77d71454f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Actions with Swift]]></title>
            <link>https://medium.com/adessoturkey/github-actions-with-swift-5b3da0dbad00?source=rss-e41cad8721b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b3da0dbad00</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Cagrigider]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 13:57:27 GMT</pubDate>
            <atom:updated>2022-12-26T15:41:18.538Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Use automated functions when pull requests are created or changes are pushed on certain branches</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k99_arb0x9B7LI4I5hhCPw.png" /></figure><p>GitHub Actions is <strong>a continuous integration and continuous delivery (CI/CD) platform that allows you to automate your build, test, and deployment pipelines.</strong></p><p>On GitHub Actions, we can create our own custom actions as well as use default actions provided by GitHub. We will use the default actions provided by Github in this article.</p><h4>Action for Building and Testing iOS App</h4><p>To start creating GitHub Actions, first, we need to move to the “Actions” tab on GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*E6wsZWioAOgk_vz5WeNS6Q.png" /><figcaption>Go to GitHub’s “Actions” tab</figcaption></figure><p>After that, we can see a lot of different actions provided by GitHub. For now, we will use the suggested “Swift” action to use build and test automation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i23QTCVsGq04z40ecAEBgA.png" /><figcaption>We will choose the Swift action</figcaption></figure><p>Now we can see the .yml file GitHub created for us. Above the file, we can see the path of the new file in our repository. Also, we can see and edit the name of the file.</p><p>By default, actions are created on the main branch. On the right-side panel, we can see some coding suggestions for beginners in workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zy5R9EtHVDL7KVA-8fec2g.png" /></figure><p>After we see the default settings for the Swift project, we can apply our settings to the project such as an Xcode version or a project path. After we’ve added the custom settings, our swift.yml file will now look like this:</p><pre>name: Swift<br><br>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br>  pull_request:<br>    branches: [ &quot;main&quot; ]<br><br>jobs:<br>  build:<br><br>    runs-on: macos-12<br><br>    steps:<br>    - uses: actions/checkout@v3<br><br>    - name: Xcode Setup<br>      uses: maxim-lobanov/setup-xcode@v1<br>      with:<br>        xcode-version: &#39;14.1&#39;<br><br>    - name: Build<br>      run: |<br>        cd GitHubActions<br>        xcodebuild build -project GitHubActions.xcodeproj -scheme GitHubActions clean build -sdk iphoneos CODE_SIGNING_ALLOWED=No<br><br>    - name: Run tests<br>      run: |<br>        cd GitHubActions<br>        xcodebuild test -project GitHubActions.xcodeproj -scheme GitHubActions clean build -sdk iphoneos -destination &quot;platform=iOS Simulator,OS=16.1,name=iPhone 14 Pro Max&quot; CODE_SIGNING_ALLOWED=No</pre><p>The sections in the file have the following meanings:</p><h4>name</h4><p>It is the name of our workflow. You will see this name under the “Actions” tab while checking actions.</p><h4>on</h4><p>Basically, under the “on” area, we can define where and when this workflow will run. For example, the below code means our workflow runs every time somebody creates a pull request with the target branch as “main”.</p><pre>pull_request:<br>    branches: [ &quot;main&quot; ]</pre><h4>jobs</h4><p>Every workflow has one or more jobs. It is the place where we define what our workflow does.</p><h4>runs-on</h4><p>We can define which machine will be used to run our workflow. We can run our workflows on different machines. For example, we may need to build our app on an older macOS version.</p><h4>steps</h4><p>Under the steps area, we need to write every step to complete our job. In this example, our first step will be to check out the repository, so then we can do our next steps. To check out;</p><pre>- uses: actions/checkout@v3</pre><p>Then we can define our Xcode version. I needed to use this because the demo app was created on Xcode 14.1 and was working on iOS 16.1. To define the Xcode version, we use the code below.</p><pre>- name: Xcode Setup<br>  uses: maxim-lobanov/setup-xcode@v1<br>  with:<br>    xcode-version: &#39;14.1&#39;</pre><p>After we’ve successfully completed our check out step and Xcode set up, we can build our project with the code below.</p><p>Note: If you have CocoaPods in your project, you must install pods before building the project.</p><pre>- name: Build<br>  run: xcodebuild build -project GitHubActions.xcodeproj -scheme GitHubActions clean build -sdk iphoneos CODE_SIGNING_ALLOWED=No</pre><p>After we’ve finished building, now we can run our tests. To run our tests, we will use the following code.</p><pre>- name: Run tests<br>  run: xcodebuild test -project GitHubActions.xcodeproj -scheme GitHubActions clean build -sdk iphoneos -destination &quot;platform=iOS Simulator,OS=16.1,name=iPhone 14 Pro Max&quot; CODE_SIGNING_ALLOWED=No</pre><p>After all of these steps, if there were no errors, we should get a screen similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lB47hLN4Gbe7h7Mkzmfd4w.png" /></figure><h4><strong>Action for SwiftLint Checks in an iOS App</strong></h4><p>Sometimes checking SwiftLint rules can be really difficult, and we may miss some of the mistakes. To avoid this problem, we can add a GitHub Action to our repository. In this way, we will not need to check swiftlint in the codes in the pull request. We can start adding SwiftLint to our project via CocoaPods. We can use following terminal codes to setup our pod.</p><pre>pod init</pre><p>After this step, we need to open our podfile, and add SwiftLint to it.</p><pre>target &#39;GitHubActions&#39; do<br>  # Comment the next line if you don&#39;t want to use dynamic frameworks<br>  use_frameworks!<br><br>  # Pods for GitHubActions<br>  pod &#39;SwiftLint&#39;<br><br>  target &#39;GitHubActionsTests&#39; do<br>    inherit! :search_paths<br>    # Pods for testing<br>  end<br><br>  target &#39;GitHubActionsUITests&#39; do<br>    # Pods for testing<br>  end<br><br>end</pre><p>Then we will install our pod.</p><pre>pod install</pre><p>After this, we also need to update our .yml file for the GitHub Action. Since we now have pods, we need to install the pods before we build or test the project. We will add the following lines before we start the building and testing process.</p><pre>- name: Install Dependencies<br>  run: |<br>    pod install --repo-update<br>  shell: bash</pre><p>Then we can add our SwiftLint controller job. By adding this we will be checking SwiftLint rules automatically and also if there are any codes against our rules, they will be commented on the pull request.</p><pre>SwiftLint:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: GitHub Action for SwiftLint<br>        uses: norio-nomura/action-swiftlint@3.2.1</pre><p>Final form of our Swift.yml file will be looking like below.</p><pre>name: pull_request<br><br>on:<br>  pull_request:<br>    branches: [&quot;main&quot;]<br><br>jobs:<br>  SwiftLint:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: GitHub Action for SwiftLint<br>        uses: norio-nomura/action-swiftlint@3.2.1<br><br>  Build:<br>    runs-on: macos-12<br><br>    steps:<br>    - uses: actions/checkout@v3<br>    - name: Install Dependencies<br>      run: |<br>        cd GitHubActions<br>        pod install --repo-update<br>      shell: bash<br><br>    - name: Xcode Setup<br>      uses: maxim-lobanov/setup-xcode@v1<br>      with:<br>        xcode-version: &#39;14.1&#39;<br><br>    - name: Build<br>      run: |<br>        cd GitHubActions<br>        xcodebuild build -workspace GitHubActions.xcworkspace -scheme GitHubActions clean build -sdk iphoneos CODE_SIGNING_ALLOWED=No<br><br>    - name: Run tests<br>      run: |<br>        cd GitHubActions<br>        xcodebuild test -workspace GitHubActions.xcworkspace -scheme GitHubActions clean build -sdk iphoneos -destination &quot;platform=iOS Simulator,OS=16.1,name=iPhone 14 Pro Max&quot; CODE_SIGNING_ALLOWED=No</pre><p>That’s all. We now have a project that can check SwiftLint rules, check build status, and run tests on its own. You can view the latest version of the project on GitHub.</p><p><a href="https://github.com/cagrigider/GitHubActions">https://github.com/cagrigider/GitHubActions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b3da0dbad00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/github-actions-with-swift-5b3da0dbad00">GitHub Actions with Swift</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>