<?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 Mattia Cardone on Medium]]></title>
        <description><![CDATA[Stories by Mattia Cardone on Medium]]></description>
        <link>https://medium.com/@lcardone65?source=rss-8fea83349216------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OTBxmFcaL0QnzVvco7f0UA.png</url>
            <title>Stories by Mattia Cardone on Medium</title>
            <link>https://medium.com/@lcardone65?source=rss-8fea83349216------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:41:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lcardone65/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[Login app with FireBase]]></title>
            <link>https://medium.com/@lcardone65/login-app-with-firebase-11c6cbae56b6?source=rss-8fea83349216------2</link>
            <guid isPermaLink="false">https://medium.com/p/11c6cbae56b6</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mattia Cardone]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 15:05:58 GMT</pubDate>
            <atom:updated>2023-10-04T15:06:20.588Z</atom:updated>
            <content:encoded><![CDATA[<p>Firebase is a serverless platform for developing mobile and web applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*kk0P2do_ev4kaAr-2pHMgA.png" /></figure><p>Open source but supported by Google, Firebase leverages Google’s infrastructure and its cloud to provide a suite of tools for writing, analyzing and maintaining cross-platform applications. In fact, Firebase offers features such as analysis, database (using noSQL structures), messaging and crash reporting for managing web applications, iOS and Android.</p><p>In this article we will see how to create a Login app(email/password) with Firebase using Swift.</p><p>First step : Create a Firebase project. Let’s go to <a href="https://firebase.google.com/">Firebase</a> and create an account. After this, you will redirected in the Firebase console, where you can create a new project. Give the name to it and you have done(the next step allows you to set up Google Analytics for your project)! Firebase automatically provisions resources for your Firebase project. When the process completes, you’ll be taken to the overview page for your Firebase project in the FB console.</p><p>Now we are ready for the second step: Register your app to the firebase project. So you need to add your app trough the app’s ID bundle identifier. Go to the Firebase project console,in the middle of the page click the IOS+ icon to launch the setup workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*CDTCq_4NWmKpNV-dZ2wVog.png" /><figcaption>Ios+ icon</figcaption></figure><p>Insert your bundle and click on “Register”. Basically, now, we have to follow the nexts 4 step of firebase app configuration. The first thing download the GoogleService-info.plist and move it into the root of your Swift app.</p><p><strong>NB.</strong> Firebase generates a unique ID for your Firebase project based upon the name you give it. If you want edit this project ID, you must do it now as it cannot be altered after Firebase Provisions resources for your project.</p><p>The next step id add the Firebase SDK to your project. In Xcode, with your app project open, open FILE -&gt; Add Packages. In the top right, in the search bar, past this url : <br><a href="https://github.com/firebase/firebase-ios-sdk">https://github.com/firebase/firebase-ios-sdk</a><br>Select the version (the latest version is recommended) and then select the packages that you need( In our case almost <a href="https://github.com/firebase/firebase-ios-sdk/tree/master/FirebaseAuth">FirebaseAuth</a> and <a href="https://github.com/firebase/firebase-ios-sdk/tree/master/FirebaseCombineSwift">FirebaseAuthCombine</a>).</p><p><strong>NB.</strong> You can install the packages without Swift Package Manager. In fact you can use CocoaPods. For more info, see this tutorial : <a href="https://firebase.google.com/docs/ios/setup#integrate-without-swift-pm">Cocoa</a>.</p><p>The last step to configure our Firebase app is to add this code in the appDelegate :</p><pre>import Firebase </pre><pre>@UIApplicationMainclass AppDelegate: UIResponder, <br>UIApplicationDelegate <br>{  <br>    <br>  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool <br>      {<br>          // Firebase set up<br>          FirebaseApp.configure()<br>          return true<br>      }<br>}</pre><p>Now we have to allow the email/password login on Firebase console. Go to console of your Firebase app : Click on Authentication -&gt; select email/password. After done that, you have a situation like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hj_9N0LYNmvgFZnjvz8nkQ.png" /></figure><p><strong>NB.</strong> You can add a new provider further on.</p><p>Now we can go ahead with Xcode because we have to create the functions that allow us to :</p><ol><li>Create a new user</li><li>Log in trough email and password</li><li>Log out</li></ol><p>Let’s go to configure in swift those three steps!</p><pre>import UIKit<br>import Firebase</pre><pre>class ViewController: UIViewController {<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Configure Firebase<br>        FirebaseApp.configure()<br>    }<br>    <br>    // Perform login with email and password<br>    func loginUser(email: String, password: String) {<br>        Auth.auth().signIn(withEmail: email, password: password) { (authResult, error) in<br>            if let error = error {<br>                print(&quot;Login error: \(error.localizedDescription)&quot;)<br>            } else {<br>                // Login successful<br>                print(&quot;Login successful&quot;)<br>                // Proceed to the next screen or perform additional tasks<br>            }<br>        }<br>    }<br>    <br>    // Perform user registration with email and password<br>    func registerUser(email: String, password: String) {<br>        Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in<br>            if let error = error {<br>                print(&quot;Registration error: \(error.localizedDescription)&quot;)<br>            } else {<br>                // Registration successful<br>                print(&quot;Registration successful&quot;)<br>                // Proceed to the next screen or perform additional tasks<br>            }<br>        }<br>    }<br>    <br>    // Perform user sign out<br>    func signOutUser() {<br>        do {<br>            try Auth.auth().signOut()<br>            // Sign out successful<br>            print(&quot;Sign out successful&quot;)<br>            // Proceed to the login screen or perform additional tasks<br>        } catch let signOutError as NSError {<br>            print(&quot;Sign out error: \(signOutError.localizedDescription)&quot;)<br>        }<br>    }<br>    <br>    // Example usage<br>    func exampleUsage() {<br>        // Login<br>        loginUser(email: &quot;example@example.com&quot;, password: &quot;password&quot;)<br>        <br>        // Register<br>        registerUser(email: &quot;newuser@example.com&quot;, password: &quot;password123&quot;)<br>        <br>        // Sign out<br>        signOutUser()<br>    }<br>}</pre><p>This code snippet includes the configuration of Firebase using `FirebaseApp.configure()`. It also demonstrates functions to perform login, user registration, and sign-out operations using Firebase Authentication APIs (`Auth.auth()`). You can call these functions with appropriate email and password parameters to handle the respective operations.</p><p>Customize the code according to your app’s specific requirements and add UI elements and navigation as needed.</p><p>Well Done, it is finished! Enjoy !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11c6cbae56b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Step-by-Step Tutorial on Using Entity Framework]]></title>
            <link>https://medium.com/@lcardone65/a-step-by-step-tutorial-on-using-entity-framework-fe432c83e0e0?source=rss-8fea83349216------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe432c83e0e0</guid>
            <category><![CDATA[context]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[entity-framework]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[visual-studio]]></category>
            <dc:creator><![CDATA[Mattia Cardone]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 14:36:02 GMT</pubDate>
            <atom:updated>2023-10-04T14:36:17.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*D0Pzz_D0TXd9wNRYtK1hcg.png" /></figure><p><strong><em>Introduction</em></strong>:</p><p>Entity Framework (EF) is a popular object-relational mapping framework that simplifies database interactions for .NET developers. By providing an abstraction layer over the database, EF allows developers to work with their data using object-oriented principles. In this tutorial, we will walk you through the process of using Entity Framework to perform basic CRUD (Create, Read, Update, Delete) operations in a .NET application.</p><p><strong><em>Prerequisites</em></strong>:</p><p>To follow along with this tutorial, you should have a basic understanding of C# programming and have the following installed:</p><p>- Visual Studio or Visual Studio Code</p><p>- .NET Framework or .NET Core</p><p>- Entity Framework (installable via NuGet packages)</p><p><strong>Step 1: Set up a New Project</strong></p><p>Start by creating a new project in Visual Studio or Visual Studio Code. Choose the appropriate project template based on your .NET version preference and desired application type (e.g., console application, web application, etc.).</p><p><strong>Step 2: Install Entity Framework</strong></p><p>If you’re using Visual Studio, right-click on your project in the Solution Explorer, select “Manage NuGet Packages,” and search for “EntityFramework.” Install the latest stable version of Entity Framework. Alternatively, you can use the .NET CLI or Package Manager Console to install the EF package.</p><p><strong>Step 3: Define Your Database Model</strong></p><p>In Entity Framework, the database schema is represented by a set of classes called “entities.” These entities will map to tables in the database. Start by defining your entities as C# classes. Each class will represent a table, and properties within the class will correspond to columns in the table. Decorate the classes and properties with appropriate attributes to define relationships, primary keys, and other constraints.</p><p><strong>Step 4: Create a DbContext Class</strong></p><p>The DbContext class acts as a bridge between your application and the database. It enables you to query and manipulate data using LINQ (Language Integrated Query). Create a new class that derives from the DbContext class and add a constructor to pass the database connection string.</p><p><strong>Step 5: Configure the DbContext</strong></p><p>Within the DbContext class, override the OnConfiguring method and provide the connection string for your database. You can use various providers such as SQL Server, MySQL, or SQLite, depending on your database choice.</p><p><strong>Step 6: Perform CRUD Operations</strong></p><p>With the setup complete, you can now perform CRUD operations on your entities. Use the DbSet properties within your DbContext class to access the corresponding tables. Use LINQ queries to retrieve, insert, update, or delete data.</p><p><strong>Step 7: Test Your Application</strong></p><p>Build and run your application to test the functionality. Create sample data, retrieve records, update them, and delete them. Inspect the changes in your database to ensure that the operations are working as expected.</p><p><strong><em>Conclusion:</em></strong></p><p>Entity Framework simplifies database interactions in .NET applications by providing a powerful and flexible object-relational mapping framework. In this tutorial, we covered the basic steps to get started with Entity Framework, including setting up a project, installing EF, defining a database model, creating a DbContext class, and performing CRUD operations. By mastering Entity Framework, you can streamline your data access layer and focus more on building robust applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe432c83e0e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read, update and delete data with CoreData]]></title>
            <link>https://medium.com/thpintgroup/read-update-and-delete-data-with-coredata-d1b17e62addf?source=rss-8fea83349216------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1b17e62addf</guid>
            <category><![CDATA[nsobject]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[core-data]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mattia Cardone]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 07:10:31 GMT</pubDate>
            <atom:updated>2022-10-17T07:13:14.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*H50H7p8PHQUvf-79EG7B2g.jpeg" /></figure><p>Core Data is used to save your application’s permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container. This article will explain how to save, update and delete with CoreData.</p><p>To use CoreData when you create a project, you have to select “Use Core Data”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*wPl_YAEwOVi_PDFpdxbpLA.png" /></figure><p>When the project is created, see in your project navigator. There will be the Core data database with the same name of the project like in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*sG-uiPmz6XgevsGQ3p1JfQ.png" /></figure><p>Click on it. It is time to add a new entity or add the attributes to your entity. In this project i will save three strings and one Image. The type of image in core data is “Binary Data”. So after added the attributes, we will have a situation like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*28LoG6X_lEiCV4Q0WISiZA.png" /></figure><p>Now we are ready to create the right functions to save, update and delete from core data.</p><p>To have a clean code, create a new swift file “CoreDataManager” that contain all the functions we need. First create a struct that rapresents our Entity(in this case, “EventiEntity”).</p><pre><strong>struct</strong> EventsItem {</pre><pre><strong>       var</strong> title:String?</pre><pre><strong>       var</strong> description:String?</pre><pre><strong>       var</strong> imagine: Data?</pre><pre><strong>       var</strong> url: String?<br>}</pre><p>Now, add a class “CoreDataManager” which implements NSObject. NSObject is the base class for most Objective-C objects. In Swift you would inherit from it if you want your Swift object to be an Objective-C object (with all the advantages and drawbacks that implies), but don’t have a more specific Objective-C object in mind.</p><p>Then we add a function to get the context. The class will return a type “NSManagedObjectContext”(A context consists of a group of related model objects that represent an internally consistent view of one or more persistent stores. In fact, NSManagedObjectContext is an object space to manipulate and track changes to managed objects) that rapresents our context. So the class looks like this :</p><pre><strong>class</strong> CoreDataManager: NSObject {</pre><pre><strong>   private</strong> <strong>class</strong> <strong>func</strong> getContext() -&gt; NSManagedObjectContext {</pre><pre><strong>     let</strong> appDelegate = UIApplication.shared.delegate <strong>as</strong>! AppDelegate</pre><pre><strong>     return</strong> appDelegate.persistentContainer.viewContext</pre><pre>   }</pre><pre>}</pre><p>Now, we can create the save function. So, create a class function with 4 parameters : 3 types will be Strings and one Data(It is possible cast an UIImage to Data, so we can use both of them as parameter).</p><pre><strong>class</strong> <strong>func</strong> storeObj(title:String,description:String, img: Data, url: String) {</pre><pre><strong>let</strong> context = getContext()</pre><pre><strong>let</strong> entity = NSEntityDescription.entity(forEntityName: &quot;EventiEntity&quot;, in: context)</pre><pre><strong>let</strong> managedObj = NSManagedObject(entity: entity!, insertInto: context)</pre><pre>managedObj.setValue(title, forKey: &quot;nomeEvento&quot;)</pre><pre>managedObj.setValue(description, forKey: &quot;descrizioneEvento&quot;)</pre><pre>managedObj.setValue(img, forKey: &quot;imagineEvento&quot;)</pre><pre>managedObj.setValue(url, forKey: &quot;urlEvento&quot;)</pre><pre><strong>do</strong> {</pre><pre><strong>try</strong> context.save()</pre><pre>print(&quot;saved!&quot;)</pre><pre>} <strong>catch</strong> {</pre><pre>print(error.localizedDescription)</pre><pre>}</pre><pre>}</pre><p><strong>NB</strong>. A “class func” is called on the type itself, while just “func” is called on the instance of that type.</p><p>We have done ! The save function is ready to use. Now fetch our objects.</p><p>Pay attention : create the right function for you. If you have to fetch all objects of the database you will need no parameters. Even if you have to fetch an object through the name or something else, you have to add a parameter. In this tutorial i will create a function with two optional parameters. The first one is an Int to decide which attribute to search for, the second one is a string that represents the string to find. Clearly, the function must return an Array of our struct. The parameters are optional, so if you don’t use them, you will fetch all the objects.</p><pre><strong>class</strong> <strong>func</strong> fetchObj(selectedScopeIdx:Int?=<strong>nil</strong>,targetText:String?=<strong>nil</strong>) -&gt; [EventsItem]{</pre><pre><strong>var</strong> aray = [EventsItem]()</pre><pre><strong>let</strong> fetchRequest:NSFetchRequest&lt;EventiEntity&gt; = EventiEntity.fetchRequest()</pre><pre><strong>if</strong> selectedScopeIdx != <strong>nil</strong> &amp;&amp; targetText != <strong>nil</strong>{</pre><pre><strong>var</strong> filterKeyword = &quot;&quot;</pre><pre><strong>switch</strong> selectedScopeIdx! {</pre><pre><strong>case</strong> 0:</pre><pre>filterKeyword = &quot;urlEvento&quot;</pre><pre><strong>case</strong> 1:</pre><pre>filterKeyword = &quot;descrizioneEvento&quot;</pre><pre><strong>default</strong>:</pre><pre>filterKeyword = &quot;titoloEvento&quot;</pre><pre>}</pre><pre><strong>var</strong> predicate = NSPredicate(format: &quot;\(filterKeyword) contains[c] %@&quot;, targetText!)</pre><pre>fetchRequest.predicate = predicate</pre><pre>}</pre><pre><strong>do</strong> {</pre><pre><strong>let</strong> fetchResult = <strong>try</strong> getContext().fetch(fetchRequest)</pre><pre><strong>for</strong> item <strong>in</strong> fetchResult {</pre><pre><strong>let</strong> rem = EventsItem(title: item.nomeEvento!, description: item.descrizioneEvento!, imagine: item.value(forKey: &quot;imagineEvento&quot;)! <strong>as</strong>! Data, url: item.urlEvento ?? &quot;&quot;)</pre><pre>aray.append(rem)</pre><pre>print(&quot;titolo:&quot;+rem.title!+&quot;\n descrizione:&quot;+rem.description!+&quot;\n url:&quot; + rem.url!)</pre><pre>}</pre><pre>}<strong>catch</strong> {</pre><pre>print(error.localizedDescription)</pre><pre>}</pre><pre><strong>return</strong> aray</pre><pre>}</pre><p>To fetch the right object in this function we’ve to set the NSFetchRequest’s predicate :</p><pre><strong>let</strong> fetchRequest =</pre><pre>NSFetchRequest&lt;NSManagedObject&gt;(entityName: &quot;EventiEntity&quot;)</pre><pre>fetchRequest.returnsObjectsAsFaults = <strong>false</strong></pre><pre>fetchRequest.predicate = NSPredicate(format: &quot;\(filterKeyword) contains[c] %@&quot;, targetText!)</pre><pre><strong>let</strong> result = <strong>try</strong>? context.fetch(fetchRequest)</pre><p>A definition of logical conditions for constraining a search for a fetch or for in-memory filtering. This is the definition of “NSPredicate”. The format is literally how it has to search; in this case, we are searching through a String, so we use “%@”. (For example, if we searched through an id, an integer, we should use “%d”).</p><p>Go to Update Function. To do this we have to find an object(in this case through the name of the event) and then update the data. In this case we have five parameters, because we have also a string that rapresents the name of the event with whom we find the row to modify(we will use the NSPredicate like before).</p><pre><strong>class</strong> <strong>func</strong> UpdateObj(nomeVecchio:String,nomeNuovo: String, descrizione:String, img: Data, url: String) {</pre><pre><strong>let</strong> context = CoreDataManager.getContext()</pre><pre><strong>let</strong> fetchRequest =</pre><pre>NSFetchRequest&lt;NSManagedObject&gt;(entityName: &quot;EventiEntity&quot;)</pre><pre>fetchRequest.returnsObjectsAsFaults = <strong>false</strong></pre><pre>fetchRequest.predicate = NSPredicate(format:&quot;nomeEvento == %@&quot;,nomeVecchio)</pre><pre><strong>let</strong> result = <strong>try</strong>? context.fetch(fetchRequest)</pre><pre><strong>if</strong> result?.count == 1 {</pre><pre><strong>          let</strong> dic = result![0]</pre><pre>          dic.setValue(nomeNuovo, forKey: &quot;nomeEvento&quot;)</pre><pre>          dic.setValue(descrizione, forKey: &quot;descrizioneEvento&quot;)</pre><pre>          dic.setValue(img, forKey: &quot;imagineEvento&quot;)</pre><pre>          dic.setValue(url, forKey: &quot;urlEvento&quot;)</pre><pre><strong>          do</strong> {</pre><pre><strong>             try</strong> context.save()</pre><pre>             print(&quot;saved!&quot;)</pre><pre>            } <strong>catch</strong> {</pre><pre>          print(error.localizedDescription)</pre><pre>      }</pre><pre>   }</pre><pre>}</pre><p>Finally, we arrived at delete function. Let’s see how to create it.</p><pre><strong>class</strong> <strong>func</strong> deleteItemWithIndex(titolo: String) {</pre><pre><strong>let</strong> context = getContext()</pre><pre><strong>let</strong> coord   = context.persistentStoreCoordinator</pre><pre><strong>let</strong> fetchRequest = NSFetchRequest&lt;NSFetchRequestResult&gt;(entityName: &quot;EventiEntity&quot;)</pre><pre>//Here is the field on which u need to chk which record u want to delete just pass here in value ( acutal value) unique key = field in coredata</pre><pre><strong>let</strong> predicate = NSPredicate(format: &quot;nomeEvento == %@&quot;, titolo)</pre><pre>fetchRequest.predicate = predicate</pre><pre><strong>let</strong> deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)</pre><pre><strong>do</strong> {</pre><pre><strong>try</strong> coord!.execute(deleteRequest, with: context)</pre><pre>}</pre><pre><strong>catch</strong> {</pre><pre>print(error.localizedDescription)</pre><pre>}</pre><pre>}</pre><p>In this case, we use the NSPredicate to find the object to delete. Then we use a NSBatchDeleteRequest(A request that deletes objects in the SQLite persistent store without loading them into memory.) with our fetchRequest to delete it.</p><p><strong>NB</strong>. If you want clean all the database, you can use :</p><pre><strong>class</strong> <strong>func</strong> cleanCoreData() {</pre><pre><strong>let</strong> fetchRequest:NSFetchRequest&lt;EventiEntity&gt; = EventiEntity.fetchRequest()</pre><pre><strong>let</strong> deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest <strong>as</strong>! NSFetchRequest&lt;NSFetchRequestResult&gt;)</pre><pre><strong>do</strong> {</pre><pre>print(&quot;deleting all contents&quot;)</pre><pre><strong>try</strong> getContext().execute(deleteRequest)</pre><pre>}<strong>catch</strong> {</pre><pre>print(error.localizedDescription)</pre><pre>}</pre><pre>}</pre><p>That’s it. Now you can manage your data.</p><p>References :</p><p><a href="https://developer.apple.com/documentation/coredata">Core Data | Apple Developer Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1b17e62addf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thpintgroup/read-update-and-delete-data-with-coredata-d1b17e62addf">Read, update and delete data with CoreData</a> was originally published in <a href="https://medium.com/thpintgroup">ThPint</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Take data from a local file.json and display it in a Collection view]]></title>
            <link>https://medium.com/thpintgroup/take-data-from-a-local-file-json-and-display-it-in-a-collection-view-ca6760f2ea9b?source=rss-8fea83349216------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca6760f2ea9b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[collectionview]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Mattia Cardone]]></dc:creator>
            <pubDate>Fri, 26 Feb 2021 01:28:04 GMT</pubDate>
            <atom:updated>2021-02-26T01:28:04.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxjbysaQHi7-vJ5eQFbiJA.jpeg" /></figure><p>This is a tutorial to take data from a local file.json and fill a collection view with it.</p><p>JSON, an acronym for JavaScript Object Notation, is an open standard file format. It is used for the exchange of data between client/server applications, using human-readable text to store and transmit data objects consisting of attribute-value pairs and array data types. The JSON is the file format most used in data transmission.</p><p>If your app communicates with a web application, information returned from the server is often formatted as <a href="http://www.json.org/">JSON</a>. You can use the Foundation framework’s <a href="https://developer.apple.com/reference/foundation/nsjsonserialization">JSONSerialization</a> class to convert JSON into Swift data types like Dictionary, Array, String, Number, and Bool. However, because you can’t be sure of the structure or values of JSON your app receives, it can be challenging to deserialize model objects correctly.</p><p>Well, let’s start the tutorial!</p><p>First create an app project with storyboard. Drag and drop in the project your json file and look the structure of it(it is very important, because we will create a struct with the same structure).</p><pre><em>[<br>{<br>“Strain”: “100-Og”,</em></pre><pre><em>“Type”: “hybrid”,</em></pre><pre><em>“Rating”: 4,</em></pre><pre><em>“Effects”: “Creative,Energetic,Tingly,Euphoric,Relaxed”,</em></pre><pre><em>“Flavor”: “Earthy,Sweet,Citrus”,</em></pre><pre><em>“Description”: “$100 OG is a 50/50 hybrid strain that packs a strong punch. The name supposedly refers to both its strength and high price when it first started showing up in Hollywood. As a plant, $100 OG tends to produce large dark green buds with few stems. Users report a strong body effect of an indica for pain relief with the more alert, cerebral feeling thanks to its sativa side.”</em></pre><pre><em>},</em></pre><pre><em>...]</em></pre><p>As you can see, you have 6 attributes( five Strings, one decimal), so your struct will be like this :</p><pre><strong>struct</strong> Cannabis : Codable {</pre><pre><strong>let</strong> Strain : String</pre><pre><strong>let</strong> `Type` : String</pre><pre><strong>let</strong> Rating : Decimal</pre><pre><strong>let</strong> Effects : String</pre><pre><strong>let</strong> Flavor : String</pre><pre><strong>let</strong> Description : String</pre><pre>}</pre><p><strong>NB : Pay attention! You have an array of this struct.</strong></p><p>The struct has to be Codable. What is the word “Codable” ? It is a type that can convert itself into and out of an external representation(in our case, the representation is the json). So, defining this struct “Codable” allow us to automatically synthesize the code required to encode or decode an instance of that type.</p><p>Then open the storyboard and create a CollectionViewController. Customize your collectionView like you want, and add the object that you want to display in it. In this case, I created an collectionView with a static image and two labels, one for the string “Strain”, one for the “Type”. The Cell will look like the follow picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*zoFCq8c8JaM-OWVAPW289Q.png" /></figure><p>Remember of connect the SourceData and the Delegate of the collectionView to the view. Create one swift file for the cell, set the StrainCell.swift as the class of the cell in the “Identity Inspector” and connect the labels to the StrainCell.swift.</p><pre><strong>import</strong> UIKit</pre><pre><strong>class</strong> StrainCell: UICollectionViewCell {</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> strainLabel: UILabel!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> typeLabel: UILabel!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> weedImage: UIImageView!</pre><pre>}</pre><p>Now we have to create the DataLoaderClass in which we will decode our file.json and fill an array of the struct created before. So create an array of “Cannabis”.</p><pre><strong>public</strong> <strong>class</strong> DataLoader {</pre><pre>@Published <strong>var</strong> userData = [Cannabis]()</pre><pre>}</pre><p>In this class we will add a function that take the data from the JSON.</p><pre><strong>public</strong> <strong>class</strong> DataLoader {</pre><pre><strong>var</strong> userData = [Cannabis]()</pre><pre><strong>init</strong>() {</pre><pre>load()</pre><pre>}</pre><pre><strong>func</strong> load() {</pre><pre><strong>if</strong> <strong>let</strong> fileLocation = Bundle.main.url(/service/forresource: &quot;cannabis&quot;, withExtension: &quot;json&quot;) {</pre><pre>// do catch in case of an error</pre><pre><strong>do</strong> {</pre><pre><strong>let</strong> data = <strong>try</strong> Data(contentsOf: fileLocation)</pre><pre><strong>let</strong> jsonDecoder = JSONDecoder()</pre><pre><strong>let</strong> dataFromJson = <strong>try</strong> jsonDecoder.decode([Cannabis].<strong>self</strong>, from: data)</pre><pre><strong>self</strong>.userData = dataFromJson</pre><pre>   } <strong>catch</strong> {</pre><pre>print(error)</pre><pre>        }</pre><pre>     }</pre><pre>  }</pre><pre>}</pre><p><strong>NB. <em>cannabis.json</em> is the name of the local file JSON.</strong></p><p>With this code we take the data and with it we fill the array userData. So we are ready to set up our collection view with this array.</p><pre><strong>class</strong> ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate {<br></pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> collectionView: UICollectionView!</pre><pre><strong>let</strong> strains = DataLoader().userData<br></pre><pre><strong>func</strong> collectionView(<strong>_</strong> collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {</pre><pre><strong>return</strong> strains.count-1</pre><pre>}<br></pre><pre><strong>func</strong> collectionView(<strong>_</strong> collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {</pre><pre><strong>let</strong> cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;Cell&quot;, for: indexPath) <strong>as</strong>! StrainCell</pre><pre><br>//customizing the cell</pre><pre>cell.layer.borderWidth = 1</pre><pre>cell.layer.borderColor = UIColor.lightGray.cgColor</pre><pre>cell.layer.backgroundColor = UIColor.clear.cgColor</pre><pre>cell.layer.cornerRadius = 10</pre><pre>cell.layer.masksToBounds = <strong>false</strong></pre><pre>cell.layer.shadowColor = UIColor.black</pre><pre>.cgColor</pre><pre>cell.layer.shadowOpacity = 0.5</pre><pre>cell.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)</pre><pre>cell.layer.shadowRadius = 4.0</pre><pre>cell.strainLabel.text = strains[indexPath.row].Strain</pre><pre>cell.typeLabel.font = UIFont.italicSystemFont(ofSize: 20.0)</pre><pre>cell.typeLabel.text = strains[indexPath.row].Type.uppercased()<br></pre><pre><strong>return</strong> cell</pre><pre>}<br></pre><pre><strong>override</strong> <strong>func</strong> viewDidLoad() {</pre><pre><strong>super</strong>.viewDidLoad()</pre><pre>collectionView.reloadData()</pre><pre>}<br></pre><pre>}</pre><p>Now we have a working Collection View with the right Data in the labels. To finish I added the cellDetails in another view in which I take also the other attributes of our struct for the selected row of the collection. So the important is pass in the correct way the indexPath of the selected row.</p><p>At this point, we have to create a new viewController in the storyboard and put in it six labels to retrieve the data. Connect the cell with the new controller. Return to the CollectionView.swift and add this override of the prepare function and a integer(where we save our indexPath).</p><pre><strong>var</strong> id: Int = 0</pre><pre><strong>override</strong> <strong>func</strong> prepare(for segue: UIStoryboardSegue, sender: <strong>Any</strong>?)</pre><pre>{</pre><pre>// Determine what the segue destination is</pre><pre><strong>if</strong> segue.destination <strong>is</strong> DetailsView</pre><pre>{</pre><pre><strong>let</strong> paths = collectionView?.indexPathsForSelectedItems</pre><pre><strong>let</strong> row = paths![0].row</pre><pre><strong>let</strong> vc = segue.destination <strong>as</strong>? DetailsView</pre><pre>vc!.id = 0</pre><pre>vc!.id = row</pre><pre>}</pre><p>Now create new swiftFile and call it DetailsView.swift. Assign this file to the new controller in the storyboard and connect the labels created before. Then modify the swift file like this :</p><pre><strong>import</strong> UIKit</pre><pre><strong>class</strong> DetailsView: UIViewController {</pre><pre><strong>var</strong> id: Int!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> flavorDetailLabel: UILabel!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> strainDetailLabel: UILabel!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> descriptionDetailLabel: UILabel!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> effectsDetailLabel: UILabel!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> typeDetailLabel: UILabel!</pre><pre><strong>override</strong> <strong>func</strong> viewDidLoad() {</pre><pre><strong>super</strong>.viewDidLoad()</pre><pre><strong>let</strong> storyboard = UIStoryboard(name: &quot;Main&quot;, bundle: <strong>nil</strong>)</pre><pre><strong>let</strong> secondVC = storyboard.instantiateViewController(withIdentifier: &quot;Collection&quot;)  <strong>as</strong>! ViewController</pre><pre>strainDetailLabel.text = secondVC.strains[id].Strain</pre><pre>descriptionDetailLabel.text = secondVC.strains[id].Description</pre><pre>typeDetailLabel.text = secondVC.strains[id].Type.uppercased()</pre><pre>effectsDetailLabel.text = secondVC.strains[id].Flavor</pre><pre>}</pre><p>That’s it ! We have finish !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca6760f2ea9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thpintgroup/take-data-from-a-local-file-json-and-display-it-in-a-collection-view-ca6760f2ea9b">Take data from a local file.json and display it in a Collection view</a> was originally published in <a href="https://medium.com/thpintgroup">ThPint</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iCloud : Share private database’s data between Apple users]]></title>
            <link>https://medium.com/apple-developer-academy-federico-ii/icloud-share-data-between-different-users-ec5111bfbd4a?source=rss-8fea83349216------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec5111bfbd4a</guid>
            <category><![CDATA[cloudkit-sharing]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[private-data]]></category>
            <category><![CDATA[icloud]]></category>
            <category><![CDATA[cloudkit]]></category>
            <dc:creator><![CDATA[Mattia Cardone]]></dc:creator>
            <pubDate>Wed, 01 Apr 2020 15:52:53 GMT</pubDate>
            <atom:updated>2020-06-08T13:50:33.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fng6c1gd6WvuoyFCY0du0w.jpeg" /></figure><h3><strong>iCloud : Share private database’s data between Apple users</strong></h3><p>Apple iCloud has come a long way since launching in late 2011.The storage and cloud computing service includes useful features centered on making it easier to access your favorite files across multiple devices. That means all your stuff is safe and available wherever you are. To use those services there is a framework called CloudKit, which provides API for transferring data from devices running on iOS to Apple’s servers or iCloud.</p><p>To store data on iCloud we have to put it in a kind of object called CKRecord. We can put this records in three different structure (database) in a Container on iCloud which have different properties:</p><ul><li><strong>Private database</strong>: this is where the user stores records contain his private data that will not be visible to other users. In this database the user can use the zones to divide different kind of data that he want store: default zone and custom zone. Use custom zones to arrange and encapsulate groups of related records.</li><li><strong>Shared database</strong>: in the shared database you can see the record that exist on other people’s private databases only if those have granted to you permissions to view / edit the information. In shared database there isn’t any zones because that info lives in their private database.</li><li><strong>Public database</strong>: this is where you would store things you want everyone to be able to access. There are no custom zones in Public databases, everything exists in the default zone.</li></ul><p>In 2016, Apple added features for sharing data between different Apple accounts to the CloudKit framework. In this article we will explain step by step how to realise an app to save data on iCloud and share it with other users through an example where the user put name and last name in a public database and email and phone number in a private database.</p><p><strong>Tutorial</strong></p><p><strong>Create a new Project</strong></p><p>Create a new project as a single view app and go in “Signing &amp; Capabilities” section. After that you have to enable iCloud through button “+Capability” and set on Key-value storage and CloudKit like in the picture. The Notifications will able when you able CloudKit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBMtf5NLrZxnBiKSVmG2Mg.jpeg" /></figure><p>Don’t worry if they’re not any objects in the containers section. To add it tap on plus button. Then run the project and if you press on CloudKit Dashboard to check if you created your container. If you don’t see your container on the dashboard wait some time and refresh the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zbq1zPP1OF--DXq9aNK2Cg.jpeg" /></figure><p>When you can see your container in left side on dashboard, click on it and then click on Schema. After that press on “New Type” and set the name with “publicInfo”, then click on “Add Field” and add firstName and lastName. Save and then press on “Edit Indexes” and add all indexes like next picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQZmio9rnV8MBV4GcBkpOw.jpeg" /></figure><p>After saving these changes, proceed in the same way to create new Type “privateInfo” with phoneNumber and email. Save and then press on “Edit Indexes” and add all indexes like next picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CgbtkOhlM8XJebS9IDzFg.jpeg" /></figure><p><strong>Store data</strong></p><p>In this section we will create and save the data on private database and on public database. So let’s create “ProfileEditViewController.swift” and insert the following functions inside.</p><p>Through next function we will create a record with the informations for the fields “firstName” and “lastName” in public database.</p><pre><strong>func</strong> createPublicRecord(firstName: String, lastName: String, completion: ((Bool, Error?) -&gt; Void)?) {<br>  <strong>let</strong> container = CKContainer.default()<br>  <strong>let</strong> publicDatabase = container.publicCloudDatabase<br>  <strong>let</strong> query = CKQuery(recordType: &quot;PublicInfo&quot;, predicate: NSPredicate(format: &quot;TRUEPREDICATE&quot;, argumentArray: <strong>nil</strong>))<br>  <strong>var</strong> ourRecord = CKRecord(recordType: &quot;PublicInfo&quot;)<br>  publicDatabase.perform(query, inZoneWith: <strong>nil</strong>) { (results, error) -&gt; Void <strong>in<br>    if</strong> <strong>let</strong> error = error {<br>      completion?(<strong>false</strong>, error) <br>      <strong>return<br>    </strong>}<strong>else</strong> <strong>if</strong> <strong>let</strong> results = results {<br>      <strong>for</strong> aRecord <strong>in</strong> results {<br>         <strong>if</strong> aRecord.creatorUserRecordID?.recordName == &quot;__defaultOwner__&quot;{            <br>           ourRecord = aRecord <br>           <strong>break <br>        </strong>}<br>      }<br>    }<br>    ourRecord.setObject(firstName <strong>as</strong> CKRecordValue, forKey: &quot;firstName&quot;)<br>    ourRecord.setObject(lastName <strong>as</strong> CKRecordValue, forKey: &quot;lastName&quot;)<br>    publicDatabase.save(ourRecord, completionHandler: { (record, error) -&gt; Void <strong>in<br>      if</strong> <strong>let</strong> error = error {<br>          completion?(<strong>false</strong>, error)<br>      }<strong>else</strong> {<br>          completion?(<strong>true</strong>, <strong>nil</strong>)<br>      }<br>    })<br>  }<br>}</pre><p>With the next function we will create a zone, named “FavZone”, in a private database.</p><pre><strong>func</strong> createFavZone(<strong>_</strong> completionHandler:((Bool, Error?)-&gt;Void)?) {<br>  <strong>let</strong> container = CKContainer.default()<br>  <strong>let</strong> privateDatabase = container.privateCloudDatabase<br>  <strong>let</strong> customZone = CKRecordZone(zoneName: &quot;FavZone&quot;)<br>  privateDatabase.save(customZone,completionHandler:({returnRecord,error <strong>in<br>    if</strong> <strong>let</strong> error = error {<br>         completionHandler?(<strong>false</strong>, error)<br>    }<strong>else</strong> {<br>         completionHandler?(<strong>true</strong>, <strong>nil</strong>)<br>    }<br>  }))<br>}</pre><p>Through next function we will create a record with the informations for the fields “email” and “phoneNumber” in private database. This information will be saved in a particular zone (“FavZone”).</p><pre><strong>func</strong> createPrivateRecord(email: String, phoneNumber: String, completion: ((Bool, Error?) -&gt; Void)?) {<br>  <strong>let</strong> container = CKContainer.default()<br>  <strong>let</strong> privateDatabase = container.privateCloudDatabase<br>  <strong>let</strong> query = CKQuery(recordType: &quot;PrivateInfo&quot;, predicate: NSPredicate(format: &quot;TRUEPREDICATE&quot;, argumentArray: <strong>nil</strong>))<br>  <strong>let</strong> recordZone: CKRecordZone = CKRecordZone(zoneName: &quot;FavZone&quot;)<br>  <strong>var</strong> ourRecord = CKRecord(recordType: &quot;PrivateInfo&quot;, zoneID: recordZone.zoneID)<br>  privateDatabase.perform(query, inZoneWith: recordZone.zoneID){(results, error) -&gt; Void <strong>in<br>    if</strong> <strong>let</strong> error = error {<br>         completion?(<strong>false</strong>, error)<br>    }<strong>else</strong> <strong>if</strong> <strong>let</strong> results = results, <strong>let</strong> firstRecord = results.first     <br>    {<br>       ourRecord = firstRecord<br>    }<br>    ourRecord.setObject(email <strong>as</strong> CKRecordValue, forKey: &quot;email&quot;)<br>    ourRecord.setObject(phoneNumber <strong>as</strong> CKRecordValue, forKey: &quot;phoneNumber&quot;)<br>    privateDatabase.save(ourRecord, completionHandler: { (record, error) -&gt; Void <strong>in<br>      if</strong> <strong>let</strong> error = error {<br>          completion?(<strong>false</strong>, error)<br>      }<strong>else</strong> {<br>          completion?(<strong>true</strong>, <strong>nil</strong>)<br>      }<br>    })<br>  }<br>}</pre><p><strong>Load data</strong></p><p>Now it’s time to fetch our data. With the following function it is possible to load data from public database. Those functions always will be in “ProfileEditViewController.swift”.</p><pre><strong>func</strong> fetchPublicRecord( completion: ((String?, String?, Error?) -&gt; Void)?){<br>  <strong>let</strong> container = CKContainer.default()<br>  <strong>let</strong> publicDatabase = container.publicCloudDatabase<br>  <strong>let</strong> query = CKQuery(recordType: &quot;PublicInfo&quot;, predicate: NSPredicate(format: &quot;TRUEPREDICATE&quot;, argumentArray: <strong>nil</strong>))<br> <strong> var</strong> ourRecord:CKRecord?<br>  publicDatabase.perform(query, inZoneWith: <strong>nil</strong>) { (results, error) -&gt; Void <strong>in<br>    if</strong> <strong>let</strong> error = error {<br>        completion?(<strong>nil</strong>, <strong>nil</strong>, error)<br>    }<strong>else</strong> <strong>if</strong> <strong>let</strong> results = results {<br>        <strong>for</strong> aRecord <strong>in</strong> results {<br>          <strong>if</strong> aRecord.creatorUserRecordID?.recordName == &quot;__defaultOwner__&quot; {<br>           ourRecord = aRecord<br>           <strong>break<br>         </strong>}<br>       }<br>     } <strong>else</strong> {<br>        completion?(<strong>nil</strong>, <strong>nil</strong>, NSError(domain: &quot;No record found&quot;, code: -3, userInfo: <strong>nil</strong>))<br>     }<br>     <strong>if</strong> <strong>let</strong> ourRecord = ourRecord,<br>        <strong>let</strong> firstName = ourRecord.object(forKey: &quot;firstName&quot;) <strong>as</strong>? String,<br>        <strong>let</strong> lastName = ourRecord.object(forKey: &quot;lastName&quot;) <strong>as</strong>? String<br>     {<br>        completion?(firstName, lastName, <strong>nil</strong>)<br>     } <strong>else</strong>{<br>         completion?(<strong>nil</strong>, <strong>nil</strong>, NSError(domain: &quot;Unknown error&quot;, code: -4, userInfo: <strong>nil</strong>))<br>    }<br>  }<br>}</pre><p>For the private database you have to do the same thing, but in this case you can load the data only if you are the owner or if you have permissions through sharing.</p><pre><strong>func</strong> fetchPrivateRecord( completion: ((String?, String?, Error?) -&gt; Void)?) {<br>  <strong>let</strong> container = CKContainer.default()<br>  <strong>let</strong> privateDatabase = container.privateCloudDatabase<br>  <strong>let</strong> query = CKQuery(recordType: &quot;PrivateInfo&quot;, predicate: NSPredicate(format: &quot;TRUEPREDICATE&quot;, argumentArray: <strong>nil</strong>))<br>  <strong>let</strong> recordZone: CKRecordZone = CKRecordZone(zoneName: &quot;FavZone&quot;)<br>  <strong>var</strong> ourRecord:CKRecord?<br>  privateDatabase.perform(query, inZoneWith: recordZone.zoneID) { (results, error) -&gt; Void <strong>in<br>    if</strong> <strong>let</strong> error = error {<br>       completion?(<strong>nil</strong>, <strong>nil</strong>, error)<br>    }<strong>else</strong> <strong>if</strong> <strong>let</strong> results = results, <strong>let</strong> firstRecord = results.first{<br>       ourRecord = firstRecord<br>    } <strong>else</strong> {<br>       completion?(<strong>nil</strong>, <strong>nil</strong>, NSError(domain: &quot;No record found&quot;, code: -3, userInfo: <strong>nil</strong>))<br>    }<br>    <strong>if</strong> <strong>let</strong> ourRecord = ourRecord,<br>       <strong>let</strong> email = ourRecord.object(forKey: &quot;email&quot;) <strong>as</strong>? String,<br>       <strong>let</strong> phoneNumber = ourRecord.object(forKey: &quot;phoneNumber&quot;) <strong>as</strong>? String<br>    {<br>       completion?(email, phoneNumber, <strong>nil</strong>)<br>    } <strong>else</strong> {<br>       completion?(<strong>nil</strong>, <strong>nil</strong>, NSError(domain: &quot;Unknown error&quot;, code: -4, userInfo: <strong>nil</strong>))<br>    }<br>  }<br>}</pre><p><strong>Share data</strong></p><p>In this section we will provide all the necessary function to share private data between different users. To share data with another user you have to press a button that call the following function to give him the permissions for read and/or write. This action will go in “UsersDetailsViewController.swift”.</p><pre><strong>@IBAction</strong> <strong>func</strong> addToFavoritesDidPressed() {<br>  <strong>guard</strong> <strong>let</strong> dataSource = dataSource, <strong>let</strong> creatorID = dataSource.creatorUserRecordID <strong>else</strong> { <strong>return</strong> }<br><strong>  let</strong> container = CKContainer.default()<br>  <strong>let</strong> privateDatabase = container.privateCloudDatabase<br>  container.discoverUserIdentity(withUserRecordID: creatorID) { [<strong>weak</strong> <strong>self</strong>] (userIdentity, error) <strong>in<br>     if</strong> <strong>let</strong> error = error {<br>          print(error)<br>     } <strong>else</strong> <strong>if</strong> <strong>let</strong> userIdentity = userIdentity {<br>          <strong>self</strong>?.fetchPrivateRecord(completion: { (privateRecord, error) <strong>in<br>            if</strong> <strong>let</strong> error = error {<br>                 print(&quot;error: &quot;, error)<br>            } <strong>else</strong> <strong>if</strong> <strong>let</strong> privateRecord = privateRecord {<br>                 <strong>let</strong> share = CKShare(rootRecord: privateRecord)<br>                 <strong>if</strong> <strong>let</strong> lookupInfo = userIdentity.lookupInfo {<br>                      <strong>let</strong> op: CKFetchShareParticipantsOperation =      CKFetchShareParticipantsOperation(userIdentityLookupInfos: [lookupInfo])<br>                      op.fetchShareParticipantsCompletionBlock = { error <strong>in<br>                        if</strong> <strong>let</strong> error = error {<br>                             print(&quot;error: &quot;, error)<br>                        }<br>                      }<br>                      op.shareParticipantFetchedBlock = { participant <strong>in<br>                        </strong>participant.permission = .readOnly<br>                        share.addParticipant(participant)<br><strong>                        let</strong> modOp: CKModifyRecordsOperation = CKModifyRecordsOperation(recordsToSave: [privateRecord, share], recordIDsToDelete: <strong>nil</strong>)<br>                        modOp.savePolicy = .ifServerRecordUnchanged<br>                        modOp.perRecordCompletionBlock = {record, error <strong>in<br>                          </strong>print(&quot;record completion \(record) and \(String(describing: error))&quot;)<br>                        }<br>                        modOp.modifyRecordsCompletionBlock = {records, recordIDs, error <strong>in<br>                          if</strong> <strong>let</strong> error = error  {  <br>                              print(&quot;error in modifying the records: &quot;, error)<br>                          } <strong>else</strong> <strong>if</strong> <strong>let</strong> anURL = share.url {<br>                               <strong>self</strong>?.updatePublicRecord(shareURL: anURL.absoluteString, completion: { (status, error) <strong>in<br>                               if</strong> <strong>let</strong> error = error {<br>                                    print(&quot;error: &quot;, error)<br>                               }<br>                           })<br>                           <strong>let</strong> url : String = (String(String(describing: share.url).dropFirst(9).dropLast(1)))<br>                          UIPasteboard.general.string = url<br>                        }<br>                     }<br>                 privateDatabase.add(modOp)<br>                     }<br>                 container.add(op)<br>                  }<br>                }<br>             })<br>           }<br>         }<br>     <strong>if</strong>(isOpenAccessGranted()){<br>         <strong>self</strong>.alert()<br>    }<br> }</pre><p>To share data successfully, we need to update the public database with a url through the function named “updatePublicRecord”, we will write this function in “UsersDetailsViewController.swift”.</p><pre><strong>func</strong> updatePublicRecord(shareURL: String, completion: ((Bool, Error?) -&gt; Void)?) {<br>  <strong>let</strong> container = CKContainer.default()<br>  <strong>let</strong> publicDatabase = container.publicCloudDatabase<br>  <strong>let</strong> query = CKQuery(recordType: &quot;PublicInfo&quot;, predicate: NSPredicate(format: &quot;TRUEPREDICATE&quot;, argumentArray: <strong>nil</strong>))<br>  <strong>var</strong> ourRecord:CKRecord?<br>  publicDatabase.perform(query, inZoneWith: <strong>nil</strong>) { (results, error) -&gt; Void <strong>in<br>    if</strong> <strong>let</strong> error = error {<br>        completion?(<strong>false</strong>, error)<br>        <strong>return<br>    </strong>} <strong>else</strong> <strong>if</strong> <strong>let</strong> results = results {<br>        <strong>for</strong> aRecord <strong>in</strong> results {<br>           <strong>if</strong> aRecord.creatorUserRecordID?.recordName == &quot;__defaultOwner__&quot; {<br>               ourRecord = aRecord<br>               <strong>break<br>            </strong>}<br>          }<br>        }<br><strong>        if</strong> <strong>let</strong> ourRecord = ourRecord {<br>            ourRecord.setObject(shareURL <strong>as</strong> CKRecordValue, forKey: &quot;privateShareUrl&quot;)<br>             publicDatabase.save(ourRecord, completionHandler: { (record, error) -&gt; Void <strong>in<br>             if</strong> <strong>let</strong> error = error {<br>                  completion?(<strong>false</strong>, error)<br>             } <strong>else</strong> {<br>                  completion?(<strong>true</strong>, <strong>nil</strong>)<br>             }<br>          })<br>        } <strong>else</strong> {<br>             completion?(<strong>false</strong>, NSError(domain: &quot;Unknown error&quot;, code: -5, userInfo: <strong>nil</strong>))<br>        }<br>      }<br>    }</pre><p>After sent the link to user with who we want share data, we have to wait his acceptance. To accept the sharing, we need the following function in “UsersDetailsViewController.swift” :</p><pre><strong>func</strong> acceptShare(<strong>_</strong> anURL: String, completionHandler: ((CKRecord?, Error?) -&gt; Void)?) {<br>  <strong>let</strong> container = CKContainer.default()<br>  <strong>let</strong> sharedDatabase = container.sharedCloudDatabase<br>  <strong>let</strong> anURL = URL(string: anURL)!<br>  <strong>let</strong> op = CKFetchShareMetadataOperation(shareURLs: [anURL])<br>  op.perShareMetadataBlock = { shareURL, shareMetadata, error <strong>in<br>  if</strong> <strong>let</strong> error = error {<br>       completionHandler?(<strong>nil</strong>, error)<br>  } <strong>else</strong> <strong>if</strong> <strong>let</strong> shareMetadata = shareMetadata {<br>            <strong>if</strong> shareMetadata.participantStatus == .accepted {<br>                 <strong>let</strong> query = CKQuery(recordType: &quot;PrivateInfo&quot;, predicate: NSPredicate(format: &quot;TRUEPREDICATE&quot;, argumentArray: <strong>nil</strong>))<br>                 <strong>let</strong> zone = CKRecordZoneID(zoneName: &quot;FavZone&quot;, ownerName: (shareMetadata.ownerIdentity.userRecordID?.recordName)!)<br>                 sharedDatabase.perform(query, inZoneWith: zone, completionHandler:{ (records, error) <strong>in<br>                      if</strong> <strong>let</strong> error = error {<br>                          completionHandler?(<strong>nil</strong>, error)<br>                      } <strong>else</strong> <strong>if</strong> <strong>let</strong> records = records, <strong>let</strong> firstRecord = records.first {<br>                        completionHandler?(firstRecord, <strong>nil</strong>)<br>                            }<br>                      })<br>                   } <strong>else</strong> <strong>if</strong> shareMetadata.participantStatus == .pending {<br>                          <strong>let</strong> acceptOp = CKAcceptSharesOperation(shareMetadatas: [shareMetadata])<br>                          acceptOp.qualityOfService = .userInteractive<br>                          acceptOp.perShareCompletionBlock = {meta, share, error <strong>in<br>                           if</strong> <strong>let</strong> error = error {<br>                               completionHandler?(<strong>nil</strong>, error)<br>                          } <strong>else</strong> <strong>if</strong> <strong>let</strong> share = share {<br>                                <strong>let</strong> query = CKQuery(recordType: &quot;PrivateInfo&quot;, predicate: NSPredicate(format: &quot;TRUEPREDICATE&quot;, argumentArray: <strong>nil</strong>))<br>                                <strong>let</strong> zone = CKRecordZoneID(zoneName: &quot;FavZone&quot;, ownerName: (share.owner.userIdentity.userRecordID?.recordName)!)<br>                                sharedDatabase.perform(query, inZoneWith: zone, completionHandler: { (records, error) <strong>in<br>                                if</strong> <strong>let</strong> error = error {<br>                                    completionHandler?(<strong>nil</strong>, error)<br>                                     }<strong>else</strong> <strong>if</strong> <strong>let</strong> records = records, <strong>let</strong> firstRecord = records.first {<br>                       completionHandler?(firstRecord, <strong>nil</strong>)<br>                               }<br>                            })<br>                          }<br>                        }<br>                container.add(acceptOp)<br>                     }<br>                   }<br>                 }<br>            op.fetchShareMetadataCompletionBlock = { error <strong>in<br>            if</strong> <strong>let</strong> error = error {<br>                completionHandler?(<strong>nil</strong>, error)<br>            }<br>          }<br>           container.add(op)<br>        }</pre><p>You should now have a proper understanding of the basics of the sharing with CloudKit framework.</p><p>People worked on this project : <a href="https://medium.com/u/193aae3dee3b">Antonio Cimino</a> &amp; <a href="https://medium.com/u/559789656c5c">Silvio Cresci</a> .</p><p>If you need the project, there is the github link below :</p><p><a href="https://github.com/mattia-ui/ProvaCloud">mattia-ui/ProvaCloud</a></p><p>References :</p><ul><li><a href="https://code.tutsplus.com/tutorials/building-a-shopping-list-application-with-cloudkit-introduction--cms-24674">Building a Shopping List Application With CloudKit: Introduction</a></li><li><a href="https://developer.apple.com/icloud/">iCloud</a></li><li><a href="https://medium.com/@valv0/custom-cloudkit-sharing-workflow-522d67ec0c00">Custom CloudKit sharing workflow</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2016/231/">CloudKit Best Practices - WWDC 2016 - Videos - Apple Developer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec5111bfbd4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apple-developer-academy-federico-ii/icloud-share-data-between-different-users-ec5111bfbd4a">iCloud : Share private database’s data between Apple users</a> was originally published in <a href="https://medium.com/apple-developer-academy-federico-ii">Apple Developer Academy | Federico II</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>