<?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 Muhammad Nabeel on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Nabeel on Medium]]></description>
        <link>https://medium.com/@mrprogrammer?source=rss-96d43fd81e07------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TACi7Ji05GgzKHWFfB04Lw.jpeg</url>
            <title>Stories by Muhammad Nabeel on Medium</title>
            <link>https://medium.com/@mrprogrammer?source=rss-96d43fd81e07------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:52:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrprogrammer/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 Started with Machine Learning in Swift]]></title>
            <link>https://mrprogrammer.medium.com/getting-started-with-machine-learning-in-swift-7403ef37705e?source=rss-96d43fd81e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/7403ef37705e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[coreml]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Muhammad Nabeel]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 20:33:24 GMT</pubDate>
            <atom:updated>2023-12-05T10:19:57.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*rhf_pw7LzgddxLV1Oext3g.png" /></figure><p>Machine learning is a branch of artificial intelligence that enables computers to learn from data and make predictions or decisions. In this article, I will show you how to create a simple image classifier using Swift. Swift also has a great support for machine learning, thanks to frameworks like Core ML and Create ML, which allow us to integrate and use machine learning models in your apps.</p><p>To begin, make sure you have Xcode installed, as it comes with Swift and all the tools we need for machine learning development.</p><p><strong>Step 1: Importing Core ML and Create ML</strong></p><p>Swift provides two powerful frameworks for machine learning: Core ML for integrating ML models into your app, and Create ML for training custom models. Import these frameworks into your project:</p><pre>import CoreML<br>import CreateML</pre><p><strong>Step 2: Creating a Small Dataset</strong></p><p>For our example, let’s imagine we’re building a classification model to predict whether a fruit is an apple or a banana based on its weight and color. Our dataset might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDVtLxEyKsh7M_i_aNksNA.png" /><figcaption>Dataset.csv</figcaption></figure><p>You can create a CSV file with this data and import it into Xcode.</p><p><strong>Training the Model with Create ML:</strong></p><p>Now, let’s train our machine learning model using Create ML. Create a new playground in Xcode and run the following code:</p><pre>import CreateML<br><br>let data = try MLDataTable(contentsOf: URL(fileURLWithPath: &quot;path/to/your/dataset.csv&quot;))<br>let (trainingData, testingData) = data.randomSplit(by: 0.8)<br><br>let classifier = try MLImageClassifier(trainingData: trainingData, featureColumns: [&quot;Weight&quot;, &quot;Color&quot;], labelColumn: &quot;Label&quot;)<br>let evaluation = classifier.evaluation(on: testingData)<br><br>let accuracy = (1.0 - evaluation.classificationError) * 100<br>print(&quot;Model Accuracy: \(accuracy)%&quot;)<br><br>try classifier.write(to: URL(fileURLWithPath: &quot;path/to/save/your/model.mlmodel&quot;))</pre><p>This code will load your dataset, split it into training and testing data, create an image classifier, evaluate its accuracy, and save the trained model.</p><p>We can also use Create ML tool to load our CSV or JSON file. We can launch Create ML from Xcode by choosing Xcode &gt; Open Developer Tool &gt; Create ML. As we are using CSV file, we can then drag and drop our dataset file into the CreateML window. Create ML will automatically detect the columns and the data types in our dataset, and show us a preview of the data. Create ML will then suggest the best model type for our task, such as a classifier, a regressor, or a recommender. After that, we can click on the Train button to start the training process. Create ML will show us the progress and the results of the training, such as the accuracy, the confusion matrix, and the feature importance. Once we are satisfied with our model, we can export it as a Core ML model file, which we can then use in our app.</p><p><strong>Using the Model in iOS App with Core ML:</strong></p><p>Now that we have our trained model, let’s integrate it into a simple iOS app using Core ML. Create a new Xcode project, drag-and-drop your model.mlmodel file, and use the following Swift code:</p><pre>import UIKit<br>import CoreML<br>import Vision<br><br>class ViewController: UIViewController {<br><br>    @IBOutlet weak var imageView: UIImageView!<br><br>    lazy var model: FruitClassifier = {<br>        do {<br>            return try FruitClassifier(configuration: MLModelConfiguration())<br>        } catch {<br>            fatalError(&quot;Failed to load ML model: \(error)&quot;)<br>        }<br>    }()<br><br>    func classifyImage(_ image: UIImage) {<br>        guard let ciImage = CIImage(image: image) else { return }<br><br>        do {<br>            let handler = try VNImageRequestHandler(ciImage: ciImage)<br>            let request = try VNCoreMLRequest(model: model)<br><br>            try handler.perform([request])<br><br>            if let results = request.results as? [VNClassificationObservation], let firstResult = results.first {<br>                print(&quot;Predicted: \(firstResult.identifier) with confidence \(firstResult.confidence)&quot;)<br>            }<br>        } catch {<br>            print(&quot;Error classifying image: \(error)&quot;)<br>        }<br>    }<br><br>    @IBAction func selectImageTapped(_ sender: UIButton) {<br>        // Code to pick an image from the photo library<br>    }<br><br>    // Implement UIImagePickerControllerDelegate methods for image selection<br><br>    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {<br>        if let selectedImage = info[.originalImage] as? UIImage {<br>            imageView.image = selectedImage<br>            classifyImage(selectedImage)<br>        }<br>        picker.dismiss(animated: true, completion: nil)<br>    }<br>}</pre><p>This Swift code sets up a simple iOS app with an image picker and uses Core ML to classify the selected image as either an apple or a banana.</p><p><strong>Conclusion</strong>:<br>So we have used a machine learning model in a Swift app. Machine learning is a way to make computers learn from data and do smart things. We used CreateML and CoreML to do this. These are tools that help to make and use machine learning models in Swift. This example is simple, but it shows the basic steps to add machine learning in iOS apps. When you learn more about machine learning, you will find many ways to make your apps clever and helpful. Have fun with coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7403ef37705e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating OpenAI API into iOS Application Using Swift]]></title>
            <link>https://mrprogrammer.medium.com/integrating-openai-api-into-ios-application-using-swift-42b96614458b?source=rss-96d43fd81e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/42b96614458b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Muhammad Nabeel]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 20:22:51 GMT</pubDate>
            <atom:updated>2023-11-20T20:22:51.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qVgLkDsGmLV2PnZns1bRw.jpeg" /></figure><p>OpenAI provides powerful natural language processing capabilities through its API, allowing developers to incorporate advanced language models into their applications. In this guide, we’ll explore how to integrate the OpenAI API into an iOS application using Swift.</p><h4>Prerequisites</h4><p>Before diving in, ensure you have the following:</p><ul><li>OpenAI API Key: Obtain your key by signing up on the OpenAI platform, crucial for authenticating API requests.</li><li>Xcode: Install Xcode on your development machine.</li><li>A device or simulator running iOS 14 or later.</li></ul><h3>Project Setup</h3><p>Create a new Swift project in Xcode:</p><ul><li>Open Xcode and select “Create a new Xcode project.”</li><li>Choose the “App” template and select “Swift” as the programming language.</li></ul><p>Setting Up the User Interface:</p><ul><li>Design your app’s UI based on your requirements. For simplicity, let’s use a text input and a button.</li></ul><p>Configuring App Transport Security:</p><ul><li>Open Info.plist and add a new key called App Transport Security Settings.</li><li>Under this key, add another key called Allow Arbitrary Loads and set its value to YES</li></ul><p>In the project navigator, open the ViewController.swift file and import the Foundation and UIKit frameworks at the top of the file. These frameworks provide the basic functionality and user interface components for your app.</p><p>In the same file, create a property called apiKey and assign it your OpenAI API key as a string. You can find your API key in your OpenAI dashboard. Make sure to keep your API key secret and do not share it with anyone.</p><pre>let apiKey = &quot;sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;</pre><p>In the same file, create another property called prompt and assign it an empty string. This will store the user input that will be sent to OpenAI API as a prompt.</p><pre>var prompt = &quot;&quot;</pre><p>In the same file, create a method called generateText that takes no parameters and returns nothing. This method will use the URLSession class to create a network request to OpenAI API and handle the response. Inside the method, do the following:</p><p><em>Create a URL object with the endpoint of OpenAI API for text generation. You can use the following URL:</em></p><pre>let url = URL(string: &quot;https://api.openai.com/v1/engines/davinci/completions&quot;)!</pre><p><em>Create a URLRequest object with the URL object and set the HTTP method to POST. You can use the following code:</em></p><pre>var request = URLRequest(url: url)<br>request.httpMethod = &quot;POST&quot;</pre><p><em>Set the HTTP header fields of the request to include your API key and the content type. You can use the following code:</em></p><pre>request.setValue(&quot;Bearer \(apiKey)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)</pre><p><em>Create a JSON object with the parameters for the text generation. You can use the following parameters:</em></p><pre>let parameters: [String: Any] = [<br>    &quot;prompt&quot;: prompt, // the user input<br>    &quot;max_tokens&quot;: 100, // the maximum number of tokens to generate<br>    &quot;temperature&quot;: 0.5, // the randomness of the generation<br>    &quot;frequency_penalty&quot;: 0.5, // the penalty for repeating words or phrases<br>    &quot;presence_penalty&quot;: 0.5, // the penalty for mentioning new entities<br>    &quot;stop&quot;: [&quot;\n&quot;] // the token that indicates the end of the text<br>]</pre><p><em>Convert the JSON object to Data and set it as the HTTP body of the request. You can use the following code:</em></p><pre>request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)</pre><p>Create a URLSessionDataTask object with the request and a completion handler. The completion handler will be called when the network request is completed or failed. Inside the completion handler, do the following:</p><p><em>- Check if there is an error. If there is, print the error and return.</em></p><pre>if let error = error {<br>    print(error)<br>    return<br>}</pre><p><em>- Check if there is a response and a data. If there is, cast the response as HTTPURLResponse and check the status code. If the status code is 200, which means the request was successful, parse the data as JSON and extract the generated text.</em></p><pre>if let response = response as? HTTPURLResponse, let data = data {<br>    if response.statusCode == 200 {<br>        if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {<br>            if let choices = json[&quot;choices&quot;] as? [[String: Any]], let choice = choices.first {<br>                if let text = choice[&quot;text&quot;] as? String {<br>                    // do something with the generated text<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><em>Call the resume method on the URLSessionDataTask object to start the network request. You can use the following code:</em></p><pre>task.resume()</pre><p>The generateText method is now complete. You can call this method whenever you want to generate text from OpenAI API.</p><p>To create a simple user interface for your app, open the Main.storyboard file and drag and drop a text field, a button, and a label from the object library to the view controller. Resize and position them as you like. You can also change their properties, such as text, color, font, etc., in the attributes inspector.</p><p>Connect the text field, the button, and the label to the ViewController.swift file as outlets and actions. You can name them as inputTextField, generateButton, and outputLabel, respectively.</p><pre>@IBOutlet weak var inputTextField: UITextField!<br>@IBOutlet weak var outputLabel: UILabel!<br><br>@IBAction func generateButtonTapped(_ sender: UIButton) {<br>    // do something when the button is tapped<br>}</pre><p>In the generateButtonTapped method, get the text from the inputTextField and assign it to the prompt property. Then, call the generateText method to generate text from OpenAI API.</p><pre>prompt = inputTextField.text ?? &quot;&quot;<br>generateText()</pre><p>In the completion handler of the generateText method, where you have the generated text, set the text of the outputLabel to the generated text.</p><pre>outputLabel.text = text</pre><p>Run your app on a device or simulator and test it. You can enter any text in the inputTextField and tap the generateButton to see the generated text in the outputLabel. For example, you can enter “Write a poem about love” and see what OpenAI API generates.</p><p><strong>Final Code</strong></p><pre>import UIKit<br><br>class YourViewController: UIViewController {<br><br>    let apiKey = &quot;sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;<br>    var prompt = &quot;&quot;<br><br>    @IBOutlet weak var inputTextField: UITextField!<br>    @IBOutlet weak var outputLabel: UILabel!<br><br>    @IBAction func generateButtonTapped(_ sender: UIButton) {<br>        prompt = inputTextField.text ?? &quot;&quot;<br>        generateText()<br>    }<br><br>    func generateText() {<br>        let url = URL(string: &quot;https://api.openai.com/v1/engines/davinci/completions&quot;)!<br>        var request = URLRequest(url: url)<br>        request.httpMethod = &quot;POST&quot;<br>        request.setValue(&quot;Bearer \(apiKey)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br><br>        let parameters: [String: Any] = [<br>            &quot;prompt&quot;: prompt,<br>            &quot;max_tokens&quot;: 100,<br>            &quot;temperature&quot;: 0.5,<br>            &quot;frequency_penalty&quot;: 0.5,<br>            &quot;presence_penalty&quot;: 0.5,<br>            &quot;stop&quot;: [&quot;\n&quot;]<br>        ]<br><br>        request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)<br><br>        let task = URLSession.shared.dataTask(with: request) { data, response, error in<br>            guard let data = data, error == nil else {<br>                print(error ?? &quot;Unknown error&quot;)<br>                return<br>            }<br><br>            if let response = response as? HTTPURLResponse, response.statusCode == 200 {<br>                if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],<br>                   let choices = json[&quot;choices&quot;] as? [[String: Any]],<br>                   let choice = choices.first,<br>                   let text = choice[&quot;text&quot;] as? String {<br>                    DispatchQueue.main.async {<br>                        self.outputLabel.text = text<br>                    }<br>                }<br>            }<br>        }<br><br>        task.resume()<br>    }<br>}</pre><p><strong>Conclusion</strong></p><p>In this article, we learned how to integrate OpenAI API into your iOS application using Swift. We created a simple app that uses OpenAI API to generate text based on user input. This opens up possibilities for creating more complex and interesting features for your users. Explore other models and parameters offered by OpenAI API on their website and GitHub repository. Happy coding!</p><p>Feel free to customize the conclusion based on your preferences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42b96614458b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftData Unveiled: Building a Declarative Todo List App with Apple’s Latest Framework]]></title>
            <link>https://mrprogrammer.medium.com/swiftdata-unveiled-building-a-declarative-todo-list-app-with-apples-latest-framework-1a906543aa1a?source=rss-96d43fd81e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a906543aa1a</guid>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[coredataevolution]]></category>
            <category><![CDATA[apple-wwdc-2023]]></category>
            <dc:creator><![CDATA[Muhammad Nabeel]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 17:25:04 GMT</pubDate>
            <atom:updated>2023-10-01T17:25:04.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pL2j288BhvJfxemM-gks9A.jpeg" /></figure><p>During the WWDC 2023 event, Apple unveiled a cutting-edge framework for handling app data — the SwiftData framework. This framework harnesses Core Data’s robust storage architecture but introduces a more streamlined and expressive syntax, making the most of Swift’s modern features and enabling the declarative writing of model code.</p><p>SwiftData operates by leveraging Swift macros to convert existing classes into stored models managed by Core Data. It also offers a model context and container, responsible for the storage and synchronization of our data. Seamlessly integrating with SwiftUI, SwiftData allows the use of the @Query property wrapper to exhibit data in views. Predicates can be employed to filter and sort data using regular Swift code.</p><p>This article will guide you through utilizing the SwiftData framework by creating a straightforward Todo list app.</p><h3>Creating a Todo Item Model</h3><p>Let’s initiate a new iOS app using Xcode 15 beta and create a model class named <strong>TodoItem</strong>:</p><pre>import Foundation<br>import SwiftData<br><br>@Model<br>class TodoItem: Identifiable {<br>    var id: UUID<br>    var title: String<br>    var isDone: Bool<br>    <br>    init(title: String, isDone: Bool = false) {<br>        self.id = UUID()<br>        self.title = title<br>        self.isDone = isDone<br>    }<br>}</pre><p>This is a conventional model class with two modifications — importing the SwiftData framework and annotating the class with the @Model macro.</p><h3>Configuring Model Container</h3><p>Informing SwiftData about the models to store is facilitated by the Model Container. Apply the modelContainer view modifier to the ContentView:</p><pre>import SwiftUI<br>import SwiftData<br><br>@main<br>struct TodoListApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .modelContainer(for: TodoItem.self)<br>        }<br>    }<br>}</pre><h3>Implementing ContentView</h3><p>Now, update ContentView to leverage SwiftData:</p><pre><br>import SwiftUI<br>import SwiftData<br><br>struct ContentView: View {<br>    @State private var newItemTitle = &quot;&quot;<br>    @Environment(\.modelContext) private var context<br>    @Query(sort: \.title, order: .forward) var todos: [TodoItem]<br>    <br>    var body: some View {<br>        // ... (rest of the ContentView code)<br>    }<br>    <br>    private func addNewItem() {<br>        context.insert(TodoItem(title: newItemTitle))<br>        newItemTitle = &quot;&quot;<br>    }<br>}</pre><h3>Crafting TodoItemView</h3><p>Lastly, create a view for individual Todo items:</p><pre>import SwiftUI<br><br>struct TodoItemView: View {<br>    @Environment(\.modelContext) private var context<br>    var item: TodoItem<br>    <br>    var body: some View {<br>        // ... (TodoItemView code)<br>    }<br>}</pre><p>Now, you have a complete Todo list app utilizing SwiftData — a powerful framework for declarative model code and managed persistence. The article demonstrates creating model classes, configuring the model container, and integrating SwiftData with SwiftUI for effective data management.</p><p><strong>Complete Code</strong></p><pre>import SwiftUI<br>import SwiftData<br><br>@Model<br>class TodoItem: Identifiable {<br>    var id: UUID<br>    var title: String<br>    var isDone: Bool<br>    <br>    init(title: String, isDone: Bool = false) {<br>        self.id = UUID()<br>        self.title = title<br>        self.isDone = isDone<br>    }<br>}<br><br>struct ContentView: View {<br>    @State private var newItemTitle = &quot;&quot;<br>    @Environment(\.modelContext) private var context<br>    @Query(sort: \.title, order: .forward) var todos: [TodoItem]<br>    <br>    var body: some View {<br>        NavigationView {<br>            VStack {<br>                TextField(&quot;Enter new item&quot;, text: $newItemTitle)<br>                    .textFieldStyle(.roundedBorder)<br>                    .padding()<br>                Button(&quot;Add Item&quot;, action: addNewItem)<br>                <br>                List(todos) { item in<br>                    TodoItemView(item: item)<br>                }<br>            }<br>            .navigationTitle(&quot;Todo List&quot;)<br>        }<br>    }<br>    <br>    private func addNewItem() {<br>        context.insert(TodoItem(title: newItemTitle))<br>        newItemTitle = &quot;&quot;<br>    }<br>}<br><br>struct TodoItemView: View {<br>    @Environment(\.modelContext) private var context<br>    var item: TodoItem<br>    <br>    var body: some View {<br>        HStack {<br>            Image(systemName: item.isDone ? &quot;checkmark.circle.fill&quot; : &quot;circle&quot;)<br>                .foregroundColor(item.isDone ? .green : .gray)<br>                .onTapGesture {<br>                    item.isDone.toggle()<br>                }<br>            Text(item.title)<br>                .strikethrough(item.isDone)<br>            Spacer()<br>            Image(systemName: &quot;trash&quot;)<br>                .foregroundColor(.red)<br>                .onTapGesture {<br>                    context.delete(item)<br>                }<br>        }<br>        .padding()<br>    }<br>}<br><br>@main<br>struct TodoListApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .modelContainer(for: TodoItem.self)<br>        }<br>    }<br>}</pre><p><strong>Conclusion:</strong></p><p>In conclusion, SwiftData emerges as a game-changer in the realm of app development, offering a seamless and expressive approach to managing data. Leveraging the proven storage architecture of Core Data, SwiftData empowers developers to write model code declaratively, ushering in a new era of efficiency and clarity.</p><p>Through the step-by-step guide to building a Todo list app, we’ve explored SwiftData’s features, from creating model classes to configuring the model container and seamlessly integrating with SwiftUI. This journey highlights the simplicity and power of SwiftData in persisting app data.</p><p>As we wrap up, the Todo list app serves as a testament to SwiftData’s capabilities, providing a foundation for developers to build upon and customize for their unique projects. The framework’s synergy with SwiftUI and its ability to simplify complex tasks reaffirm its position as a valuable addition to the developer’s toolkit.</p><p>With SwiftData, the horizon of possibilities expands, and as developers, we can look forward to more efficient and expressive ways of handling data in our applications. As we embrace the future of Swift development, SwiftData stands as a beacon, guiding us towards a more streamlined and enjoyable coding experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a906543aa1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Observation Framework in Swift 5.9]]></title>
            <link>https://mrprogrammer.medium.com/exploring-the-observation-framework-in-swift-5-9-2a1073bb93a6?source=rss-96d43fd81e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a1073bb93a6</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[observation-framework]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Muhammad Nabeel]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 16:04:37 GMT</pubDate>
            <atom:updated>2023-09-10T19:42:43.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Fxngj_uy92Hk0SErkYtOw.png" /></figure><p><em>Enhancing SwiftUI View Updates</em></p><p><strong>Introduction</strong></p><p>At WWDC 2023, Apple introduced the Observation framework as a new addition to the Swift standard library. This framework addresses a longstanding issue for developers — unnecessary updates to SwiftUI views. In this article, we’ll take a comprehensive look at the Observation framework in a Q&amp;A format. We’ll cover why it was created, how to use it, how it works, and important precautions.</p><p><strong>The Need for Observation Framework</strong></p><p>Before Swift 5.9, developers lacked a unified and efficient way to observe changes to reference type properties. KVO was limited to NSObject subclasses, Combine couldn’t precisely observe at the property level, and both lacked cross-platform support. SwiftUI faced performance issues due to its reliance on the ObservableObject protocol from Combine.</p><p>Swift 5.9 introduced the Observation framework, offering these advantages:</p><ul><li>Applicable to all Swift reference types, not just NSObject subclasses.</li><li>Provides precise property-level observation without special annotations.</li><li>Reduces unnecessary view updates in SwiftUI, improving performance.</li></ul><p><strong>Declaring an Observable Object</strong></p><p>With Combine, you declare an observable reference type like this:</p><pre>class Store: ObservableObject {<br>    @Published var firstName: String<br>    @Published var lastName: String<br>    // ...<br>}</pre><p>In Observation, it’s simpler:</p><pre>@Observable<br>class Store {<br>    var firstName: String = &quot;John&quot;<br>    var lastName: String = &quot;Doe&quot;<br>    // ...<br>}</pre><p>Notable differences:</p><ul><li>Add @Observable before the class declaration.</li><li>No need for @Published on properties; any stored property can be observed.</li><li>Computed properties can also be observed.</li><li>Use @ObservationIgnored for properties you don&#39;t want to observe.</li></ul><p><strong>What </strong><strong>@Observable Does</strong></p><p>Unlike common keywords like @Published, @Observable is a macro introduced in Swift 5.9. It manipulates code at compile time. The macro expands the original declaration to handle property observation.</p><p><strong>How to Use Observable Objects in Views</strong></p><p>Observable objects are declared using @State in views. Injection into views is flexible:</p><pre>@Observable<br>class Store {<br>   // ...<br>}<br><br>struct ContentView: View {<br>    @State var store = Store()<br>    // ...<br>}</pre><p>Injection through environment:</p><pre>struct ContentView: View {<br>    @Environment(Store.self) var store // Inject through environment in view<br>    // ...<br>}</pre><p>Customize EnvironmentKey:</p><pre>struct StoreKey: EnvironmentKey {<br>    static var defaultValue = Store()<br>}<br><br>extension EnvironmentValues {<br>    var store: Store {<br>        get { self[StoreKey.self] }<br>        set { self[StoreKey.self] = newValue }<br>    }<br>}<br><br>struct ContentView: View {<br>    @Environment(\.store) var store // Inject through environment in view<br>    // ...<br>}</pre><p><strong>Passing Observable Objects in Views</strong></p><p>Passing an observable object to a subview:</p><pre>struct ContentView: View {<br>    @State var store = Store()<br>    var body: some View {<br>        SubView(store: store)<br>    }<br>}<br><br>struct SubView: View {<br>    let store: Store<br>    // ...<br>}</pre><p><strong>Creating a Binding Type</strong></p><p>The @Bindable type allows two-way data binding:</p><pre>struct ContentView: View {<br>    @State var store = Store()<br>    var body: some View {<br>        SubView(store: store)<br>    }<br>}<br><br>struct SubView: View {<br>    @Bindable var store: Store<br>    var body: some View {<br>       TextField(&quot;&quot;, text: $store.name)<br>    }<br>}</pre><p><strong>Compatibility</strong></p><p>The Observation framework is only available in Swift 5.9 and later, not in older versions of SwiftUI.</p><p><strong>Conclusion</strong></p><p>The Observation framework in Swift 5.9 revolutionizes how developers observe changes in reference type properties. With its simplicity and efficiency, it offers a better alternative to existing mechanisms like KVO and Combine. Incorporating it into SwiftUI applications can lead to smoother and more responsive user interfaces.</p><p><em>Note: This article assumes familiarity with Swift and SwiftUI concepts.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a1073bb93a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple coding tutorial of MVVM in IOS(swift)]]></title>
            <link>https://mrprogrammer.medium.com/a-simple-coding-tutorial-of-mvvm-in-ios-swift-17c719b4db93?source=rss-96d43fd81e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/17c719b4db93</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[mvvm-ios]]></category>
            <dc:creator><![CDATA[Muhammad Nabeel]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 20:30:31 GMT</pubDate>
            <atom:updated>2021-08-18T20:30:31.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*ZkoDGds8xDVih88e-m1d_A.png" /><figcaption>Representation of the MVVM</figcaption></figure><p>In 2005, John Gossman proposed MVVM. Surprisingly, the view should only contain visual elements and not make network calls or other similar activities.</p><p>Although all architectures have benefits and drawbacks, MVVM is becoming increasingly popular in implementations.</p><p>There are numerous articles on the internet that explain the definition, as well as the pros and cons of the MVVM pattern. So that, rather than just reading the definition, we’ll concentrate on the pattern’s simple coding implementation.</p><h3>Let’s get started</h3><p>We’ll create a simple application using the MVVM design pattern in this project. We have a view controller (UI) in most of our applications that needs to fetch data from the server (API) and display it in a TableView. We will implement the same behavior using the MVVM Pattern.</p><h3>Components of MVVM</h3><p><strong>ViewController</strong>: Present the UI components and Bind UI components with the ViewModel.</p><p><strong>ViewModel</strong>: Deal with error handling and pagination and APIs and It receives information from viewController, handles all this information, and sends it back to viewController.</p><p><strong>Model</strong>: Simple Data model of any JSON response.</p><h3>The most basic implementation</h3><p>We can create a very basic implementation of MVVM using a static array of items (without any network call).</p><p>This is our expected output at the end of this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*vl_zif8XVh9wbgPZHe4ttw.jpeg" /></figure><p><strong>ViewController</strong> creates the viewModel (possibly with initial model data), and set up bindings (i.e. closures) so the view controller is informed of changes that take place in the viewModel from APIs or static data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/043df28701df3f1465130fa42dd625ab/href">https://medium.com/media/043df28701df3f1465130fa42dd625ab/href</a></iframe><p><strong>ViewModel</strong> performs the APIs requests, and informs the view controller of changes when get the response from server. In our case, we are using the static data so items array will be passed to ViewController through closure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/774c92458e6df51de74387b79fe8912f/href">https://medium.com/media/774c92458e6df51de74387b79fe8912f/href</a></iframe><p>That’s it, our code is ready in MVVM pattern with simple steps of implementation.</p><p><strong>The whole code sample is here:</strong><br><a href="https://github.com/mr-nabeel/MVVMWithSwift">https://github.com/mr-nabeel/MVVMWithSwift</a></p><p><strong>Want to get in contact? Try the link here:</strong></p><p><a href="https://www.linkedin.com/in/mr-programmer/">Muhammad Nabeel  - Team Lead | Mobile Application Developer - AT Tech | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17c719b4db93" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>