<?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 Kevin Leong on Medium]]></title>
        <description><![CDATA[Stories by Kevin Leong on Medium]]></description>
        <link>https://medium.com/@kgleong?source=rss-1d52d86beed4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JnzShySkTfQZAMpRgOjdsA.png</url>
            <title>Stories by Kevin Leong on Medium</title>
            <link>https://medium.com/@kgleong?source=rss-1d52d86beed4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:18:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kgleong/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[Uploading Files to Google Drive using the Google iOS SDK]]></title>
            <link>https://medium.com/@kgleong/uploading-files-to-google-drive-using-the-google-ios-sdk-fcad3e9d6c07?source=rss-1d52d86beed4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcad3e9d6c07</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[google-drive]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[google-api]]></category>
            <dc:creator><![CDATA[Kevin Leong]]></dc:creator>
            <pubDate>Sat, 19 Jan 2019 19:07:38 GMT</pubDate>
            <atom:updated>2019-01-19T20:02:36.105Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick walkthrough on how to upload a file to an existing Google Drive folder</h4><p>There isn’t a dedicated section for iOS integration in the <a href="https://developers.google.com/drive/api/v3/about-sdk">Google Developer docs for Google Drive</a>.</p><p>It took me a non-trivial amount of time figure out how to <strong>upload a file to an existing or new folder</strong>, and this post summarizes how to perform this basic action.</p><h3>Steps</h3><ol><li><strong>Prerequisite:</strong> Setup native Google Sign In. See <a href="https://link.medium.com/QWG7yj9R6S">this post</a> for step-by-step instructions.</li><li>Import the <a href="https://developers.google.com/drive/api/v3/about-sdk">Google Drive REST API</a> client SDK</li><li>Setup the <a href="https://developers.google.com/drive/api/v3/about-sdk">Google Drive API </a>service in your app</li><li><strong>Retrieve</strong> an existing folder or <strong>create</strong> a folder</li><li>Upload the file</li></ol><h3>Import the Google Drive REST API Client SDK</h3><p><a href="https://cocoapods.org/about">Cocoapods</a> is the recommended delivery method for the SDK. The SDK source files are located on <a href="https://github.com/google/google-api-objectivec-client-for-rest">Github</a>.</p><p>Add the following to your <a href="https://guides.cocoapods.org/using/the-podfile.html">Podfile</a>:</p><pre>use_frameworks!</pre><pre># Pinning to the latest versions at the time<br>pod &#39;GoogleSignIn&#39;, &#39;~&gt; 4.4.0&#39;<br><strong>pod &#39;GoogleAPIClientForREST/Drive&#39;, &#39;~&gt; 1.3.7&#39;</strong></pre><h3>Setup the Google Drive API service in your app</h3><p>For the sake of brevity and simplicity, all methods are implemented in a single view controller.</p><p>Once you’ve <a href="https://link.medium.com/QWG7yj9R6S">successfully setup <strong>Google Sign In</strong> in your app</a>, you’ll also need to specify the access scope on the <strong><em>GIDSignIn</em></strong> singleton object that manages the OAuth authentication and authorization flow:</p><pre>import GoogleSignIn<br><strong>import GoogleAPIClientForREST</strong></pre><pre>class ViewController: UIViewController {<br>    override func viewDidLoad() {<br>        super.viewDidLoad()</pre><pre>        GIDSignIn.sharedInstance()?.delegate = self<br>        GIDSignIn.sharedInstance()?.uiDelegate = self</pre><pre><strong>        GIDSignIn.sharedInstance()?.scopes = <br>            [kGTLRAuthScopeDrive]<br></strong>        <br>        GIDSignIn.sharedInstance()?.signInSilently()</pre><pre>        // ...<br>    }<br>}</pre><p>Adding the <strong><em>kGTLRAuthScopeDriveFile</em> </strong>scope will ask the user to allow full Google Drive access (read and write) to your app during the OAuth flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*NwP42zn_Z_PWH-B0hyir8w.png" /></figure><p>Add a <strong><em>GTLRDriveService</em></strong> instance variable that will be responsible for making Google Drive API requests (e.g., uploading files and listing folders).</p><p>Also add a <strong><em>GIDGoogleUser</em></strong> variable. This will allow you to list only files and folders owned by the user, and will exclude shared items.</p><pre><strong>import GoogleAPIClientForREST</strong></pre><pre>class ViewController: UIViewController {<br>    <strong>let googleDriveService = GTLRDriveService()<br>    var googleUser: GIDGoogleUser?</strong></pre><pre><strong> </strong>   // ...<br>}</pre><p>Once a user successfully signs in, you can set the <strong><em>authorizer</em></strong> property on the <strong><em>GTLRDriveService.</em></strong> This ensures that all requests made by the service to the Google Drive API include any required authentication headers and values (e.g., access token, refresh token).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7095c1c77a56a87cdc7dcc93f04d1312/href">https://medium.com/media/7095c1c77a56a87cdc7dcc93f04d1312/href</a></iframe><h3>Retrieve an Existing Folder</h3><p>A folder’s unique identifier is required to upload a file to the folder. Without it, the file will be uploaded to the user’s root directory.</p><p>Add an instance variable to your ViewController to store the folder identifier. You’ll use it later to upload a file.</p><pre>class ViewController: UIViewController {<br>    let googleDriveService = GTLRDriveService()<br>    var googleUser: GIDGoogleUser?<br><strong>    var uploadFolderID: String?</strong></pre><pre>    // ...<br>}</pre><p>The method below performs a case-insensitive search for a specified folder by name. If a folder is found, the folder’s identifier is passed to the completion handler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce69a636a79236f4a193c57c5e9b7958/href">https://medium.com/media/ce69a636a79236f4a193c57c5e9b7958/href</a></iframe><p>The <strong>user</strong> parameter is only required if you want to limit the search to folders owned by the user. Its used in the query here:</p><pre>&quot;&#39;\(user.profile!.email!)&#39; in owners&quot;</pre><p><strong>Omitting</strong> this from the query statement will broaden the search to include any folders <strong>shared</strong> with the user.</p><p>An example of how you would utilize the <strong><em>getFolderID</em></strong> method to set the <strong><em>uploadFolderID</em></strong>:</p><pre>class ViewController: UIViewController {<br>    let googleDriveService = GTLRDriveService()<br>    var googleUser: GIDGoogleUser?<br><strong>    </strong>var uploadFolderID: String?</pre><pre>    // ...</pre><pre><strong>    func populateFolderID() {<br>        getFolderID(<br>            name: &quot;my-folder&quot;, <br>            service: service, <br>            user: user) { self.uploadFolderID = $0 }<br>    </strong>}<br>}</pre><p>For more information, see the Google developer docs for:</p><ul><li>a list of <a href="https://developers.google.com/drive/api/v3/mime-types">Google Suite-specific MIME types</a></li><li><a href="https://developers.google.com/drive/api/v3/search-parameters">Google Drive Query Syntax</a></li></ul><h3>Create a Folder</h3><p>To upload the file to a new folder, you’ll need to create the folder first.</p><p>Here’s a simplified example of how to create a folder. The folder identifier is returned via a completion handler if creation succeeds.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93b7e12f8ba4a708f935cdb96ccbc8dc/href">https://medium.com/media/93b7e12f8ba4a708f935cdb96ccbc8dc/href</a></iframe><p>It’s important to note that if you’re creating a new folder, you should <strong>check to ensure an existing folder with the same name</strong> doesn’t exist already. You can do that using the <strong>getFolderID</strong> method presented earlier:</p><pre>class ViewController: UIViewController {<br>    let googleDriveService = GTLRDriveService()<br>    var googleUser: GIDGoogleUser?<br><strong>    </strong>var uploadFolderID: String?</pre><pre>    // ...</pre><pre>    func populateFolderID() {<br>        let myFolderName = &quot;my-folder&quot;</pre><pre>        getFolderID(<br>            name: myFolderName, <br>            service: service, <br>            user: user) { folderID in</pre><pre><strong>            if folderID == nil { <br>                self.createFolder(<br>                    name: myFolderName, <br>                    service: self.googleDriveService) {</strong></pre><pre><strong>                    self.uploadFolderID = $0 <br>                }<br>            } else { <br>                // Folder already exists<br>                self.uploadFolderID = folderID <br>            }<br></strong>        }<br><strong>    </strong>}<br>}</pre><p>For more information, see the Google Developer Docs on <a href="https://developers.google.com/drive/api/v3/folder">managing folders</a>.</p><h3>Upload the File</h3><p>The method below uploads contents from a file URL to a Google Drive folder, specified by the <strong>folderID</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8ea7c4381e6b260925093cc4fafc59a/href">https://medium.com/media/a8ea7c4381e6b260925093cc4fafc59a/href</a></iframe><p>Notice that the Google SDK gives you an optional <strong><em>uploadProgressBlock</em></strong>, that is called at intervals during upload, and this is where you should update any progress bars or indicators in your UI.</p><p>Example usage of the <strong><em>uploadFile</em></strong> method above:</p><pre>class ViewController: UIViewController {<br>    let googleDriveService = GTLRDriveService()<br>    var googleUser: GIDGoogleUser?<br><strong>    </strong>var uploadFolderID: String?</pre><pre>    // ...</pre><pre><strong>    func uploadMyFile() { <br>        let fileURL = Bundle.main.url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20forResource:%20&quot;my-image&quot;,%20withExtension:%20&quot;.png&quot;)</strong></pre><pre><strong>        uploadFile(<br>            name: &quot;my-image.png&quot;, <br>            folderID: uploadFolderID, <br>            fileURL: fileURL!, <br>            mimeType: &quot;image/png&quot;, <br>            service: googleDriveService)</strong><br><strong>    </strong>}<br>}</pre><p>For a complete list of MIME-types See <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">this list from Mozilla</a>.</p><p>If no errors occur during upload, the file should appear in your specified folder!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*EB0bYamG667LDNISMnyJJg.png" /></figure><h3>References</h3><ul><li><a href="https://developers.google.com/drive/api/v3/about-sdk">About Google Drive SDK</a> — Google Developer Docs</li><li><a href="https://developers.google.com/drive/api/v3/reference/files">Google Drive Rest API: Files </a>— Google Developer Docs</li><li><a href="https://agostini.tech/2018/04/22/using-google-drive-in-your-app/">Using Google Drive in your App</a> — Agostini.tech</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcad3e9d6c07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add Native iOS Google Sign In]]></title>
            <link>https://medium.com/@kgleong/how-to-add-native-ios-google-sign-in-8ef66c09006e?source=rss-1d52d86beed4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ef66c09006e</guid>
            <category><![CDATA[google-api]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Kevin Leong]]></dc:creator>
            <pubDate>Mon, 31 Dec 2018 06:51:10 GMT</pubDate>
            <atom:updated>2019-01-19T19:08:52.661Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enable your app to use Google’s API on your user’s behalf</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*9TyimIlK5dVKLI22Vrco4w.gif" /></figure><p>If you want to add an event to a user’s Calendar or save a file to Drive, Google’s services require user authentication before most actions can be taken.</p><p>This guide is a <strong>quick overview</strong> of how to incorporate <a href="https://developers.google.com/identity/sign-in/ios/">Google Sign In</a> into a native iOS app.</p><p>Integrating a specific service, namely Google Drive, is covered in <a href="https://medium.com/@kgleong/uploading-files-to-google-drive-using-the-google-ios-sdk-fcad3e9d6c07">this post</a>.</p><p><em>Disclaimer: for the sake of simplicity, the view controller in this example conforms to all required protocols, which may not be the best approach for your use case.</em></p><h3>Steps</h3><ol><li>Create OAuth credentials via the <a href="https://console.developers.google.com/"><strong>Google Developer Console</strong></a></li><li>Import the <a href="https://developers.google.com/identity/sign-in/ios/"><strong><em>GoogleSignIn</em></strong></a> SDK into your app</li><li>Setup Google Sign In in your app</li><li>Add a sign in button to your UI</li><li>Conform to <strong>Google Sign In protocols</strong></li><li>Configure the <em>GIDSignIn</em> singleton</li></ol><h3>Create OAuth credentials via the Google Developer Console</h3><p>Google Sign In uses OAuth 2.0 to authenticate users and grant permissions to your app.</p><p>You’ll need Google to generate two things for your iOS application:</p><ol><li><strong>OAuth Client ID</strong></li><li><strong>Unique URL scheme </strong>(just a reversed client ID)</li></ol><p>Sign into the <a href="https://console.developers.google.com/"><strong>Google Developer Console</strong></a><strong> </strong>and follow the steps below:</p><ul><li>Create or select a project</li><li>Go to the project’s <a href="https://console.developers.google.com/apis/credentials">credentials page</a></li><li>Create an OAuth Client ID</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*nORtZpvMxcV_RsVlRS_w8Q.png" /><figcaption>Create OAuth Client ID</figcaption></figure><ul><li>You’ll be asked to fill out the required sections of the <strong>OAuth Consent Screen </strong>form if they’re missing. <em>This information is presented to the user when they’re asked to grant your app permission to make requests on the behalf of their Google Account.</em></li><li>Fill in the following form with your app information:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*XoWSFXrUIv_dIJRDiSHm5w.png" /><figcaption>iOS app information form</figcaption></figure><ul><li>Download the <em>.plist </em>that contains the client ID and URL scheme (reverse client ID) by clicking the <strong>download</strong> button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*6_QKbh07P49H6COmwZQJUQ.png" /><figcaption>Download link for client ID and URL scheme. Note: this is not a real client ID :)</figcaption></figure><ul><li>You’ll need the downloaded <em>.plist</em> file later to setup the SDK in your app. Here’s a sample <em>.plist</em> file when opened in Xcode (contains your client ID and reversed client ID/URL scheme):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*6YeSICWS2m3ridapjmn1vA.png" /><figcaption>Sample .plist containing Google credentials and URL scheme</figcaption></figure><h3>Import the GoogleSignIn SDK</h3><p><a href="https://cocoapods.org/about">Cocoapods</a> is the recommended delivery method for the SDK. For manual installation, direct downloads are available <a href="https://developers.google.com/identity/sign-in/ios/sdk">here</a>.</p><p>Add the following to your <a href="https://guides.cocoapods.org/using/the-podfile.html">Podfile</a>:</p><pre>use_frameworks!</pre><pre># Pinning to the latest version at the time<br>pod &#39;GoogleSignIn&#39;, &#39;~&gt; 4.4.0&#39;</pre><h3>Setup Google Sign In in your app</h3><p>Once the SDK has been included in your app, you’ll need to do the following:</p><ul><li>Add a custom URL scheme to your app target. The value should be set to the <strong><em>REVERSED_CLIENT_ID</em></strong> value in the <em>.plist</em> containing your Google credentials.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*2lW1F_lm6jMv-OVJIO_tEw.png" /><figcaption>Add the REVERSED_CLIENT_ID as a custom URL scheme to your app target</figcaption></figure><ul><li>In your app delegate, set the client ID on the <em>GIDSignIn</em> singleton:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57ba1b8041e895dff5e30456eaf8e102/href">https://medium.com/media/57ba1b8041e895dff5e30456eaf8e102/href</a></iframe><ul><li>Implement <em>application(_:open:options)</em> in your app delegate:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2d3b480a4b737290822867baee183c8/href">https://medium.com/media/b2d3b480a4b737290822867baee183c8/href</a></iframe><p>Google uses OAuth to authenticate users, and will send a redirect to the custom URL scheme that you added.</p><h3>Add a Google Sign In Button to your UI</h3><p>Add a button to your view controller that calls the following method to initiate sign in when tapped:</p><pre>// Start Google&#39;s OAuth authentication flow<br>GIDSignIn.sharedInstance()?.signIn()</pre><p><em>Note: To create a sign out button, use </em><strong><em>GIDSignIn.sharedInstance()?.signOut()</em></strong><em>. For more information on signing out, see this </em><a href="https://stackoverflow.com/a/53984407/603960"><em>Stack Overflow Post</em></a><em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bb4655cb95bb60bf96d7bdd664252d7/href">https://medium.com/media/7bb4655cb95bb60bf96d7bdd664252d7/href</a></iframe><p><em>Note: The SDK provides a ready-made </em><a href="https://developers.google.com/identity/sign-in/ios/api/interface_g_i_d_sign_in_button"><em>GIDSignInButton</em></a><em>, but its styling options are limited.</em></p><p>Tapping on the newly added sign in button will <strong>throw an exception, because of a missing delegate.</strong></p><h3>Conform to Google Sign In <strong>protocols</strong></h3><p>Your view controller must conform to two protocols in order for sign in to work: <strong>GIDSignInDelegate </strong>and<strong> GIDSignInUIDelegate</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b3bdb406d8f1fe9575b019e9f2a4175/href">https://medium.com/media/1b3bdb406d8f1fe9575b019e9f2a4175/href</a></iframe><ul><li><a href="https://developers.google.com/identity/sign-in/ios/api/protocol_g_i_d_sign_in_u_i_delegate-p"><strong>GIDSignInUIDelegate</strong></a> — For custom sign in buttons, contains <strong>optional</strong> methods that allow your app to display a loading indicator while app switching is in progress after the OAuth flow completes.</li><li><a href="https://developers.google.com/identity/sign-in/ios/api/protocol_g_i_d_sign_in_delegate-p"><strong>GIDSignInDelegate</strong></a> — Provides a method that allows your app to respond to authentication results. In this example, if sign in completes successfully, the sign in button is hidden. Also provides a <strong><em>GIDGoogleUser</em></strong> object when sign in is successful that contains basic profile information (email, name, etc.).</li></ul><h3>Configure the GIDSignIn Singleton</h3><p>The final step is to configure Google Sign In. This is done by setting properties on the <em>GIDSignIn</em> singleton:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6613ee0ecfaeb6d574891e34e166723/href">https://medium.com/media/f6613ee0ecfaeb6d574891e34e166723/href</a></iframe><p>Both the delegate and UI delegate properties need to be set.</p><p>Finally, call<em> </em><strong><em>signInSilently() </em></strong>to prevent users from having to enter their credentials if a valid session token exists. Results of a silent sign in will be posted to the same <em>GIDSignInDelegate.sign(_:didSignInFor:withError:)</em> method that receives results from a manual sign in.</p><p>More properties need to be set once you’ve decided which Google APIs you need to request access to, but this is all you need to get Google Sign In up and running!</p><h3>References</h3><p><a href="https://developers.google.com/identity/sign-in/ios/start-integrating">Start Integrating Google Sign In (iOS</a>) — Google Developer Docs<br><a href="https://agostini.tech/2018/04/22/using-google-drive-in-your-app/">Using Google Drive in your App</a> — Agostini.tech</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef66c09006e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom UIViewController Modal Transition Animations]]></title>
            <link>https://medium.com/@kgleong/simplified-custom-ios-modal-view-controller-transitions-56d0bd2ad17b?source=rss-1d52d86beed4------2</link>
            <guid isPermaLink="false">https://medium.com/p/56d0bd2ad17b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Kevin Leong]]></dc:creator>
            <pubDate>Sat, 29 Dec 2018 05:20:43 GMT</pubDate>
            <atom:updated>2018-12-29T15:35:23.525Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick intro to custom transition animations.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*LL0JS4IDP-cz-H5JMbidmA.gif" /></figure><p>Many custom transition tutorials go in depth and cover presentation controllers, the <strong>modal</strong> and <strong>navigation</strong> <strong>controller</strong> cases and require downloading a sample project (ANGTFT).</p><p>This is a simple, bare-bones intro to custom transitions that jumps straight to the code with a minimal amount of prose.</p><p><em>Disclaimer: For the sake of brevity, the main view controller conforms to all necessary transitioning protocols. Also, forced casts and extensions are liberally used, though they may not be appropriate in practice.</em></p><h3>Setup</h3><p>We’ll be creating a simple sliding drawer animation that transitions between two view controllers (see image above).</p><p><em>MyViewController</em> is the app’s root view controller and consists of a single button that presents the drawer’s view controller <strong>modally</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff0595071610edb144b7514f0454f8bb/href">https://medium.com/media/ff0595071610edb144b7514f0454f8bb/href</a></iframe><p>The second view controller is a <em>DrawerViewController </em>that contains a single button that dismisses the view controller.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2b6005037c0f1f4fce5e37064744c3b/href">https://medium.com/media/e2b6005037c0f1f4fce5e37064744c3b/href</a></iframe><p>These two lines in the <em>MyViewController’s</em> <em>onButtonTap </em>method are required in order to replace the standard modal transition, which normally slides the presented view controller up from the bottom.</p><pre>drawerViewController.modalPresentationStyle = .custom        drawerViewController.transitioningDelegate = self</pre><p><strong>NOTE:</strong> Failing to set the <strong><em>modalPresentationStyle</em></strong> will result in the standard modal transition being used, regardless of whether a <em>transitioningDelegate</em> is set.</p><p>In order to assign <em>MyViewController </em>as the provider of the custom transition animation to a <em>DrawerViewController</em>, it must conform to the <a href="https://developer.apple.com/documentation/uikit/uiviewcontrollertransitioningdelegate"><em>UIViewControllerTransitioningDelegate</em></a> protocol.</p><h3>UIViewControllerTransitioningDelegate</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c85da86742dcbf2efff281594687ee8f/href">https://medium.com/media/c85da86742dcbf2efff281594687ee8f/href</a></iframe><p>These methods will be called by UIKit upon presentation or dismissal of the <em>DrawerViewController.</em></p><p>Different <strong>animation controllers</strong> can be returned in case different custom animations need to be used for presentation and dismissal. E.g., <em>MyFadeInTransitionAnimator, MyFadeOutTransitionAnimator.</em></p><p>To simplify this example, <em>MyViewController</em> conforms to <a href="https://developer.apple.com/documentation/uikit/uiviewcontrolleranimatedtransitioning"><em>UIViewControllerAnimatedTransitioning</em></a>.</p><h3>UIViewControllerAnimatedTransitioning</h3><p>Once a transition is initiated and an animation controller has been provided, UIKit will call the following <em>UIViewControllerAnimatedTransitioning</em> methods:</p><ul><li><a href="https://developer.apple.com/documentation/uikit/uiviewcontrolleranimatedtransitioning/1622032-transitionduration"><strong>transitionDuration(transitionContext:)</strong></a> returns the duration of the transition animation. Should be used by the <em>animateTransition </em>method when setting the aggregate animation duration.</li><li><a href="https://developer.apple.com/documentation/uikit/uiviewcontrolleranimatedtransitioning/1622061-animatetransition?language=objc"><strong>animateTransition(transitionContext:)</strong></a><strong> </strong>implements the custom transition animation(s).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fb7b006240df230c4114b01b596bc9f/href">https://medium.com/media/8fb7b006240df230c4114b01b596bc9f/href</a></iframe><ul><li>A <strong>transitionContext</strong> contains references to the participating view controllers. It also includes a <strong><em>containerView</em></strong> that all views being presented must be added to. Conforms to <a href="https://developer.apple.com/documentation/uikit/uiviewcontrollercontexttransitioning?language=objc">UIViewControllerContextTransitioning</a>.</li><li>It’s extremely important to call <a href="https://developer.apple.com/documentation/uikit/uiviewcontrollercontexttransitioning/1622042-completetransition"><strong><em>transitionContext.completeTransition(_:)</em></strong></a><strong><em> </em></strong>when the transition animation(s) has completed, since <strong>UIKit does not allow your app to receive touch events while a transition is in progress</strong>.</li></ul><p>That’s it!</p><h3>References</h3><p><a href="https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/CustomizingtheTransitionAnimations.html">Customizing Transition Animations</a> — Apple Developer Docs<br><a href="https://www.raywenderlich.com/322-custom-uiviewcontroller-transitions-getting-started">Custom UIViewController Transitions</a> — Ray Wenderlich<br><a href="https://theswiftdev.com/2018/04/26/ios-custom-transition-tutorial-in-swift/">iOS Custom Transition Tutorial</a> — The Swift Dev</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56d0bd2ad17b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncovering Inconsistent Keychain Behavior While Fixing a Valet iOS Bug]]></title>
            <link>https://medium.com/square-corner-blog/uncovering-inconsistent-keychain-behavior-while-fixing-a-valet-ios-bug-7c9beece0aa1?source=rss-1d52d86beed4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c9beece0aa1</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[Kevin Leong]]></dc:creator>
            <pubDate>Thu, 22 Feb 2018 16:55:59 GMT</pubDate>
            <atom:updated>2019-04-18T22:24:19.041Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago, a developer sent the following error stack trace to Square from their iOS app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecd81991dff3d24cc30c497169bd4448/href">https://medium.com/media/ecd81991dff3d24cc30c497169bd4448/href</a></iframe><blockquote>Heads up, we’ve moved! If you’d like to continue keeping up with the latest technical content from Square please visit us at our new home <a href="https://developer.squareup.com/blog">https://developer.squareup.com/blog</a></blockquote><p>This led to a patch of <a href="https://github.com/square/Valet">Valet</a>, Square’s popular open source library for managing iOS and macOS keychains. Along the way, we also uncovered a subtle but interesting inconsistency in keychain behavior on iOS and macOS.</p><p>This post will cover the following:</p><ul><li>A detailed look at the error;</li><li>An overview of the iOS keychain and Valet;</li><li>Debugging and patching Valet; and</li><li>How we stumbled upon the differing keychain behavior in iOS and macOS, and the factors that contribute to it.</li></ul><h3>Error Details</h3><pre>NSInvalidArgumentException’, reason: ‘-[__NSCFData isEqualToString:]: unrecognized selector sent to instance 0x6080000b97b0</pre><p>The error message above indicates that <strong>isEqualToString</strong> (an <strong>NSString</strong> method) is being called on an __<strong>NSCFData</strong> instance (a private subclass of <strong>NSData </strong>that does not implement <strong>isEqualToString</strong>).</p><p>Looking further down the stack trace, the first call that is not part of Apple’s <a href="https://developer.apple.com/documentation/corefoundation">CoreFoundation</a> framework is:</p><pre>-[VALValet migrateObjectsMatchingQuery:removeOnCompletion:]</pre><p>VALValet is a class in Valet, and the <strong>migrateObjectsMatchingQuery</strong> method calls <strong>isEqualToString</strong> once <a href="https://github.com/square/Valet/blob/2.2.3/Valet/VALValet.m#L426">here</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6ef8a766c4076e8abd78f126fde269a/href">https://medium.com/media/b6ef8a766c4076e8abd78f126fde269a/href</a></iframe><p>Immediately before the code calls<strong> isEqualToString</strong> and the crash occurs, the <strong>kSecAttrAccount</strong> value retrieved from the keychain entry is stored as an <strong>NSString</strong>:</p><pre>NSString *const key = keychainEntry[(__bridge id)kSecAttrAccount];</pre><p>The exception, however, indicates that <strong>key</strong> is actually an <strong>NSData</strong> object.</p><p>Why does Valet assume that the <strong>kSecAttrAccount</strong> value is a String?</p><p>Before answering this, having answers to these prerequisite questions is helpful:</p><ul><li>What is the iOS keychain?</li><li>What is Valet?</li><li>What does Valet’s <strong>migrateObjectsMatchingQuery</strong> method do?</li></ul><h3>What is the iOS Keychain?</h3><p>If you’re already familiar with the iOS keychain, feel free to skip this section.</p><p>One way of persisting data between app launches is via <a href="https://developer.apple.com/documentation/foundation/userdefaults">UserDefaults</a>, which is a key-value store with a simple API:</p><pre>let myUsername = &quot;foo&quot;</pre><pre><strong>// Store value in UserDefaults<br></strong>UserDefaults.standard.set(&quot;bar&quot;, forKey: myKey)</pre><pre><strong>// Retrieve data<br></strong>UserDefaults.standard.string(forKey: myKey)</pre><p>The iOS <a href="https://developer.apple.com/library/content/documentation/Security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html#//apple_ref/doc/uid/TP30000897-CH208-SW1"><strong>keychain</strong></a> is another persistence option, allowing apps to store sensitive data, such as passwords, in an encrypted SQLite database file on the device. Keychain entries can be retrieved and stored through the use of predefined attribute fields (e.g., <strong>kSecAttrAccount</strong>, <strong>kSecClass</strong>, <strong>kSecAttrService</strong>).</p><h4>What’s the difference between the iOS keychain and UserDefaults?</h4><p>The iOS keychain is secure storage (and has a hard-to-use API), while UserDefaults is entirely insecure (but has an easy-to-use API).</p><p>UserDefaults stores data in <strong>plain text </strong>in a .plist (property list) file within the application’s sandbox. Utilities like <a href="https://www.ibrowseapp.com/">iBrowse</a> and <a href="https://macroplant.com/iexplorer">iExplorer</a> can easily inspect files on a device, making UserDefaults only suited for storing non-sensitive data like user preferences and settings.</p><p>The following illustrates the minimum amount of code necessary to create and fetch a username/password entry in the the iOS keychain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/203797366ffb06ea06414294afd2d318/href">https://medium.com/media/203797366ffb06ea06414294afd2d318/href</a></iframe><p>Not only is keychain usage verbose, but every function that interacts with the keychain (e.g., <strong>SecItem*</strong>) returns a bevy of error codes (see <strong>OSStatus</strong> in <a href="https://opensource.apple.com/source/Security/Security-57740.60.18/base/SecBase.h">SecBase.h</a>) that need to be checked and handled.</p><h3>What is Valet?</h3><p>Dealing with the keychain is complex, prone to error, and usually includes a large amount of boilerplate code. Unfortunately, it’s also unavoidable for any app that needs to store account information or sensitive data.</p><p>To make keychain management easier, Valet was developed by Square as an open source library for both iOS and macOS that hides the complexities of the keychain under a simple key-value interface.</p><p>Storing and retrieving a username/password in the keychain via Valet is similar to UserDefaults:</p><pre>let myUsername = &quot;my-username&quot;; let myPassword = &quot;my-password&quot;</pre><pre>let valet = VALValet(<br>    identifier: Bundle.main.bundleIdentifier!, <br>    accessibility: .whenUnlocked<br>)</pre><pre><strong>// Store username/password<br></strong>valet?.setString(myPassword, forKey: myUsername)</pre><pre><strong>// Retrieve password by username<br></strong>valet?.string(forKey: myUsername)</pre><p>Now that we have more context, let’s return to our investigation of the error received by the developer.</p><h3>What does Valet’s migrateObjectsMatchingQuery Method do?</h3><p>As mentioned previously, the exception:</p><blockquote>NSInvalidArgumentException [__NSCFData isEqualToString:]: unrecognized selector</blockquote><p>occurs in VALValet’s <strong>migrateObjectsMatchingQuery</strong> method. What does this method do?</p><p>Typical usage of the <strong>migrateObjectsMatchingQuery </strong>method looks like this:</p><pre>let valet = VALValet(<br>    identifier: Bundle.main.bundleIdentifier!, <br>    accessibility: .whenUnlocked<br>)</pre><pre>let query: [String: Any] = [<br>    kSecAttrService as String: Bundle.main.bundleIdentifier as Any,<br>    kSecClass as String: kSecClassGenericPassword as Any<br>]</pre><pre><strong>valet?.migrateObjects(<br>    matchingQuery: query, <br>    removeOnCompletion: true<br>)</strong></pre><p><strong>migrateObjectsMatchingQuery:removeOnCompletion:</strong> allows an application to shift management of existing keychain entries to Valet. If the application was utilizing the keychain to persist data prior to using Valet, this method restructures existing keychain entries to a format that allows these entries to be updated or fetched via Valet’s simpler API.</p><pre>let query: [String: Any] = [<br>    <strong>kSecAttrService</strong> as String: Bundle.main.bundleIdentifier as Any,<br>    <strong>kSecClass</strong> as String: kSecClassGenericPassword as Any<br>]</pre><p>The <strong>query</strong> parameter is used to select the keychain entries to be migrated to Valet, and uses the standard keychain attribute field names as filter criteria.</p><p>Migration allows apps to transition to Valet without forcing users to re-enter account passwords or other information stored in the keychain.</p><h3>Taking a Closer Look at Where the Error Occurs</h3><p>Revisiting the code block in <strong>migrateObjectsMatchingQuery</strong> where the exception is thrown:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fc1aa3cbf91ba054764b1a48d26e475/href">https://medium.com/media/0fc1aa3cbf91ba054764b1a48d26e475/href</a></iframe><p>Prior to migration, this section of code is responsible for sanity checking the existing keychain entries that are candidates for migration. For example, to be eligible, existing entries must have <strong>kSecAttrAccount</strong> and <strong>kSecValueData</strong> values.</p><p>A line-by-line explanation:</p><pre>for (NSDictionary *const keychainEntry in <strong>queryResultWithData</strong>)</pre><p><strong>queryResultWithData</strong> is an Array containing data for the entries returned after searching the keychain using the <strong>query</strong> supplied to the <strong>migrateObjectsMatchingQuery</strong> method.</p><pre><strong>NSString</strong> *const <strong>key</strong> = keychainEntry[(__bridge id)kSecAttrAccount];</pre><p>Each entry’s <strong>kSecAttrAccount</strong> value is stored in the <strong>key</strong> variable. <strong>Note the assumption here that the value is a String.</strong> The compiler allows this due to the fact that <strong>NSDictionary</strong> values are <strong>id</strong> pointers, which allow implicit casts.</p><pre>if ([<strong>key isEqualToString:VALCanAccessKeychainCanaryKey]</strong>) { <br>    // We don&#39;t care about this key. Move along.<br>    continue;<br>}</pre><p>Before each entry is sanity checked, <strong>key</strong> is compared against <strong>VALCanAccessKeychainCanaryKey</strong> and all checks are skipped if a match is found.</p><p><strong>VALCanAccessKeychainCanaryKey</strong> is a string constant stored in the <strong>kSecAttrAccount</strong> field of an entry by Valet when performing exploratory (canary) keychain entry inserts. These inserts verify that the proper keychain accessibility was specified when initializing a Valet instance.</p><p>If the query results contain a canary entry, we want to skip any sanity checks for that entry. Canary entries are a special case that should not cause any migration sanity checks to fail.</p><p>Everything works fine when <strong>key</strong> (the value in an entry’s <strong>kSecAttrAccount</strong> field) is an <strong>NSString</strong>. The exception, however, proves that it’s possible for <strong>key</strong> to be an<strong> NSData</strong> object.</p><p>The problem is the assumption Valet makes that an entry’s <strong>kSecAttrAccount</strong> value will be an <strong>NSString </strong>object:</p><pre><strong>NSString</strong> *const <strong>key</strong> = keychainEntry[(__bridge id)kSecAttrAccount];</pre><h3>Why does Valet assume that the kSecAttrAccount value is an NSString?</h3><p>Apple’s documentation for the <a href="https://developer.apple.com/documentation/security/ksecattraccount">keychain value associated with the SecAttrAccount attribute</a> provides the following description:</p><blockquote>A key whose value is a <strong>string</strong> indicating the item’s [keychain entry’s] account name.</blockquote><p>From this, it seems reasonable to assume that <strong>kSecAttrAccount</strong> values will always be strings.</p><p>Also, from this example of Valet usage:</p><pre>let myUsername = &quot;my-username&quot;; let myPassword = &quot;my-password&quot;</pre><pre>let valet = VALValet(<br>    identifier: Bundle.main.bundleIdentifier!, <br>    accessibility: .whenUnlocked<br>)</pre><pre><strong>// Store username/password<br></strong>valet?.setString(myPassword, forKey: myUsername)</pre><pre><strong>// Retrieve password by username<br></strong>valet?.string(forKey: myUsername)</pre><p>Valet only accepts String arguments for keys (<strong>myUsername</strong> in the example above), which are then stored as <strong>kSecAttrAccount</strong> values in the keychain.</p><p>Any entries created by Valet abide by Apple’s type restriction on <strong>kSecAttrAccount</strong> values. However, for existing keychain entries, Valet makes the flawed assumption that either:</p><ul><li>All developers comply with these keychain type restrictions; or</li><li>The framework or operating system enforces type restrictions on keychain data.</li></ul><h3>Reproducing the Error</h3><p>The exception received by the developer, however, indicates that it is possible to store an NSData object in a keychain entry’s <strong>kSecAttrAccount </strong>field, which contradicts Apple’s documentation.</p><p>The following code snippet proves that this is indeed the case, and the same exception is thrown when attempting to migrate keychain entries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b4834acd82504f4ca2c97266f85b1d3/href">https://medium.com/media/8b4834acd82504f4ca2c97266f85b1d3/href</a></iframe><h3>Fix: Adding a Type Check</h3><p>Since it can no longer be assumed that <strong>kSecAttrAccount</strong> is always a string, we need to add a type check prior to the string comparison to avoid sending the <strong>isEqualToString</strong> message to a non-<strong>NSString</strong> object.</p><pre>if (<strong>[key isKindOfClass:[NSString class]] &amp;&amp; <br>    </strong>[key isEqualToString:VALCanAccessKeychainCanaryKey]) {</pre><pre>    // We don’t care about this key. Move along.<br>    continue;<br><strong>}</strong></pre><p>Since Valet always uses <strong>NSString</strong> values in the <strong>kSecAttrAccount</strong> field for entries it creates, a Valet canary entry’s key will always be an <strong>NSString</strong>. Therefore, adding this type check is a valid requirement.</p><h3>An Unintentional Find: Inconsistent behavior in macOS and iOS Keychains</h3><p>Next, we added the test below to verify our change (Valet is written in Objective C):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49df970c583b59c4bc09411e1ad72b73/href">https://medium.com/media/49df970c583b59c4bc09411e1ad72b73/href</a></iframe><pre>NSString *identifier = @&quot;my_identifier&quot;;<br>NSData *<strong>dataBlob</strong> = [@&quot;foo&quot; dataUsingEncoding:NSUTF8StringEncoding];<br><br>NSDictionary *<strong>keychainData</strong> = @{ <br>    (__bridge id)kSecAttrService : identifier, <br>    (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, <br><strong>    (__bridge id)kSecAttrAccount : dataBlob,<br></strong>    (__bridge id)kSecValueData : dataBlob<br>};</pre><p>The test deliberately stores <strong>dataBlob</strong>, which is an <strong>NSData</strong> object in the <strong>kSecAttrAccount</strong> field of <strong>keychainData</strong>, which is inserted in to the keychain. As expected, the fix prevents an exception from being thrown.</p><p>Interestingly, the last assertion passes on an iOS target but <strong>fails in a macOS</strong> <strong>environment </strong>(Valet can manage iOS and macOS keychains):</p><pre>NSError *error = <br>    [self.valet migrateObjectsMatchingQuery:query removeOnCompletion:NO];<br>    <br><strong>XCTAssertNil(error); // Passes for iOS, fails for macOS</strong></pre><p>Running the test on a macOS target resulted in a <strong>VALMigrationErrorKeyInQueryResultInvalid</strong> error, indicating that the keychain entry’s <strong>kSecAttrAccount</strong> value was <strong>nil</strong>. Recall that any keys that are candidates for migration must have a value in the <strong>kSecAttrAccount</strong> field.</p><p>Inserting an entry containing a <strong>kSecAttrAccount</strong> Data object on macOS results in the <strong>kSecAttrAccount</strong> value not being persisted if it is not the correct type. iOS, on the other hand, persists the <strong>kSecAttrAccount</strong> value regardless of whether it is the correct type or not.</p><p>Inspecting the keychain entry after inserting <strong>keychainData</strong> in both operating systems confirms that the <strong>kSecAttrAccount</strong> data value is stored successfully on iOS but not on macOS:</p><pre><strong>macOS:</strong></pre><pre>(lldb) po keychainEntry<br>{</pre><pre><strong>    /** MISSING ACCT VALUE !!! **/<br></strong>    cdat = &quot;2017-08-12 11:37:39 +0000&quot;;<br>    class = genp; // kSecClass<br>    labl = &quot;Keychain_With_Account_Name_As_NSData&quot;;<br>    mdat = &quot;2017-08-12 11:37:39 +0000&quot;;<br>    svce = &quot;my_identifier&quot;; // kSecAttrService<br>    &quot;v_Data&quot; = &lt;666f6f&gt;; // kSecValueData<br>    &quot;v_PersistentRef&quot; = &lt;...&gt;;<br>}</pre><pre><strong>iOS:<br><br></strong>(lldb) po keychainEntry<br>{<br>    <strong>/** PERSISTED kSecAttrAccount VALUE !!! **/<br></strong>    <strong>acct = &lt;666f6f&gt;;</strong><br>    agrp = &quot;&lt;*&gt;.com.squareup.Valet-iOS-Test-Host-App&quot;;<br>    cdat = &quot;2017-08-12 11:35:45 +0000&quot;;<br>    mdat = &quot;2017-08-12 11:35:45 +0000&quot;;<br>    musr = &lt;&gt;;<br>    pdmn = ak;<br>    svce = &quot;my_identifier&quot;; // kSecAttrService<br>    sync = 0;<br>    tomb = 0;<br>    &quot;v_Data&quot; = &lt;666f6f&gt;; // kSecValueData<br>    &quot;v_PersistentRef&quot; = &lt;67656e70 00000000 00000325&gt;;<br>}</pre><h3>Why does iOS persist the kSecAttrAccount value while macOS does not?</h3><p>A developer at Apple posted <a href="https://forums.developer.apple.com/thread/46429">this reply</a> to a thread inquiring about this very issue:</p><blockquote><strong>There are two implementations of the SecItem API:</strong></blockquote><blockquote>the <strong>iOS implementation</strong>, which is also used for iCloud Keychain on OS X</blockquote><blockquote>the <strong>OS X implementation</strong>, which is a compatibility shim that bridges over to the traditional keychain</blockquote><blockquote>Note Both are available in Darwin. Search the Security project for <strong>SecItemUpdate_ios</strong> and <strong>SecItemUpdate_osx</strong> to see how this works under the covers.</blockquote><blockquote><strong>The iOS implementation is based on SQLite.</strong> <strong>If you’re familiar with SQLite you’ll know that it is, at its core, untyped, and thus the iOS implementation has to do its own type conversion. This is why that implementation is somewhat forgiving on the types front.</strong> However…</blockquote><blockquote>IMPORTANT I strongly recommend that you use the types specified in the header. Other types do work but that’s an accident of the implementation rather than a designed in feature. Moreover, as there are two implementations, it’s not always the case that these accidents line up.</blockquote><blockquote>I realise that this rule is broken by various bits of Apple sample code.</blockquote><p>In short, these two factors contribute to this difference in behavior:</p><ul><li>iOS and macOS do not use the same data store for their keychains.</li><li>The keychain implementation is different for both operating systems.</li></ul><h4>iOS and macOS Use Different Keychain Data Stores</h4><p>SQLite, which is the data store backing the iOS keychain, uses <strong>type affinity </strong>rather than rigid typing, meaning a column’s datatype in SQLite is more a recommendation rather than a requirement.</p><p>From the <a href="http://sqlite.org/datatype3.html">SQLite documentation</a>:</p><blockquote>Any column can still store any type of data. It is just that some columns, given the choice, will prefer to use one storage class over another…<strong>A column with TEXT affinity stores all data using storage classes NULL, TEXT or BLOB</strong>.</blockquote><p>This explains the observed behavior in iOS, which allowed an <strong>NSData</strong> object to be stored in the <strong>kSecAttrAccount</strong> column, even though the recommended data type is a string.</p><h4>Differing Keychain Implementation on iOS and macOS</h4><p>iOS and macOS both use the <strong>SecItemUpdate</strong> function to update keychain entries. Its implementation can be found in <a href="https://opensource.apple.com/source/Security/Security-57740.60.18/OSX/libsecurity_keychain/lib/SecItem.cpp.auto.html">SecItem.cpp</a>, which is open sourced as part of Apple’s Security framework:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f82ee1bde790fe85ecd6934a70dd7b13/href">https://medium.com/media/f82ee1bde790fe85ecd6934a70dd7b13/href</a></iframe><p>It’s apparent from the <strong>can_target_(ios|osx)</strong> boolean values and <strong>SecItemUpdate_(ios|osx) </strong>functions that the codepaths are different for each operating system.</p><p>For interested readers, <strong>SecItemUpdate_ios</strong> is aliased via a preprocessor macro to the <strong>SecItemUpdate</strong> function in <a href="https://opensource.apple.com/source/Security/Security-57740.60.18/OSX/sec/Security/SecItem.c">SecItem.c</a>. <strong>SecItemUpdate_osx</strong> is defined in <a href="https://opensource.apple.com/source/Security/Security-57740.60.18/OSX/libsecurity_keychain/lib/SecItem.cpp.auto.html">SecItem.cpp</a>. The entire Security framework can be downloaded <a href="https://opensource.apple.com/tarballs/Security/">here</a>.</p><h4>Summary of Keychain Findings</h4><p>To summarize what we’ve learned about keychains as a result of this investigation:</p><ul><li>Both iOS and macOS do not return an error if a <strong>Data</strong> object is stored in a keychain entry’s <strong>kSecAttrAccount</strong> field.</li><li>iOS persists the <strong>kSecAttrAccount</strong> value, regardless of type, while macOS does not.</li><li>It’s clear that macOS keychains are persisted in a type safe database, or type checks have been added to the macOS codepath that do not exist on iOS.</li></ul><h3>Fixing the Test</h3><p>Returning back to the failing Valet test, in order to account for the differing keychain behavior across platforms, the following:</p><pre><strong>XCTAssertNil(error); // Passes for iOS, fails for macOS</strong></pre><p>needs to be replaced with:</p><pre># if <strong>TARGET_OS_IPHONE</strong><br>    XCTAssertNil(error);</pre><pre># elif <strong>TARGET_OS_MAC</strong></pre><pre>/**<br>  iOS allows kSecAttrAccount NSData entries, <br>  while OSX sets the value to nil for any non-string entry.<br>  */</pre><pre><strong>    XCTAssertEqual(<br>        error.code, <br>        VALMigrationErrorKeyInQueryResultInvalid<br>    );</strong></pre><pre># else<br>    [NSException raise:@&quot;UnsupportedOperatingSystem&quot; format:@&quot;Only OSX and iOS are supported&quot;];</pre><pre># endif</pre><p>With this change the test now passes, and a link to the final Valet fix can be found <a href="https://github.com/square/Valet/pull/114">here</a> on Github.</p><h3>Communicating Findings to the Developer</h3><p>After completing our investigation, we relayed to the developer that the crash was due to an <strong>NSData</strong> object being stored against a keychain entry’s <strong>kSecAttrAccount</strong> attribute.</p><p>They responded that their app had always stored <strong>kSecAttrAccount</strong> string values, but were using a third-party library that was also storing credentials containing <strong>kSecAttrAccount</strong> values in the keychain. It was highly probable that this library was inserting the offending keychain entry. The library, however, was critical to the app’s functionality and could not be removed.</p><p>It’s common to use the app’s main bundle identifier as the <strong>kSecAttrService</strong> attribute value, which acts as a namespace within the keychain. The developer’s code and the library were most likely storing entries under the same namespace.</p><p>The code used in the developer’s app to migrate their keychain entries to Valet:</p><pre>let valet = VALValet(<br>    identifier: Bundle.main.bundleIdentifier!, <br>    accessibility: .whenUnlocked<br>)</pre><pre><strong>let query: [String: Any] = [<br>    kSecAttrService as String!: Bundle.main.bundleIdentifier as Any,   <br>    kSecClass as String!: kSecClassGenericPassword as Any<br>]</strong></pre><pre>valet?.migrateObjects(<br>    matchingQuery: query, <br>    removeOnCompletion: true<br>)</pre><p>The query above returns all generic passwords stored under the app’s bundle identifier, and in this case, it included an entry stored by a third party library with a <strong>kSecAttrService</strong> Data object.</p><p>Updating the developer’s app to a version of Valet containing the fix resolved the issue for them.</p><p>I’d like to thank <strong>Eric Muller</strong> and <strong>Dan Federman</strong>, the creators of Valet, for helping to debug and fix this issue.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c9beece0aa1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/square-corner-blog/uncovering-inconsistent-keychain-behavior-while-fixing-a-valet-ios-bug-7c9beece0aa1">Uncovering Inconsistent Keychain Behavior While Fixing a Valet iOS Bug</a> was originally published in <a href="https://medium.com/square-corner-blog">Square Corner Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>