<?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 Ahmed Khalaf on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Khalaf on Medium]]></description>
        <link>https://medium.com/@ahmedkhalaf.92?source=rss-e30e8c841607------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pDEEGnyvLlSuIglYdhLfww.jpeg</url>
            <title>Stories by Ahmed Khalaf on Medium</title>
            <link>https://medium.com/@ahmedkhalaf.92?source=rss-e30e8c841607------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:09:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmedkhalaf.92/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[Rendering off The Main Thread in iOS]]></title>
            <link>https://medium.com/@ahmedkhalaf.92/rendering-off-the-main-thread-in-ios-80bd782e7136?source=rss-e30e8c841607------2</link>
            <guid isPermaLink="false">https://medium.com/p/80bd782e7136</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Ahmed Khalaf]]></dc:creator>
            <pubDate>Sat, 23 Mar 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-03-23T20:34:26.082Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the first lessons we learn in iOS development is that UIKit classes (UILabel, UIImageView, …etc) shouldn’t be touched outside the main thread. Sometimes we learn it <a href="https://stackoverflow.com/a/12927485/715593">the hard way</a>. However, this doesn’t mean we cannot do any form of rendering off the main thread.</p><p>Classes like NSAttributedString and UIImage come with <a href="https://developer.apple.com/documentation/foundation/nsattributedstring/1531631-draw">methods</a> for drawing to a given graphics context; an <a href="https://developer.apple.com/documentation/uikit/1623912-uigraphicsbeginimagecontextwitho?language=objc">image context</a> for our use case. This doesn’t mandate being done in a particular thread. Not only this, but UIKit enables us to export what’s drawn to the current context to a bitmap image using <a href="https://developer.apple.com/documentation/uikit/1623924-uigraphicsgetimagefromcurrentima">UIGraphicsGetImageFromCurrentImageContext</a>. This means we can do any complex drawing like we do with CoreGraphics in drawRect:, and then export this to a bitmap.</p><p>All what we have to do next is to display the resulting image in our view. This is easily achieved by setting the views <a href="https://developer.apple.com/documentation/quartzcore/calayer/1410773-contents">layer.contents</a> property to a CGImage representation of our image. And that’s it.</p><h3>Cool, but why?</h3><p>UIKit performance is great 99% of the time. However, it’s not the best we can acheive. UIKit performance degrades noticebly when rendering large scrolling amounts of text and images with varying sizes, in addition to relying on AutoLayout for sizing. <a href="https://developer.apple.com/videos/play/wwdc2018/220">AutoLayout came along way in iOS 12</a>, but earlier iOS versions are still in support, and no matter how fast AutoLayout becomes, it still works on the main thread.</p><p>AutoLayout is not only the slowing factor. Actual rendering and intrinsic content size calculation also happens on the main thread. I’ve profiled stuttering scrolling performances before and the culprit was none other than regular text drawing invoked from UILabel’s drawing.</p><h3>Rendering and Sizing</h3><p>If you notice, we’re dealing with two types of problems: (1) Rendering, i.e. the graphical content we see, and (2) Sizing, i.e. what space our rendered content will consume.</p><p>We talked about rendering methods above. If you notice, those rendering methods rely on a CGRect input, that is the bounding box of the graphical content. So, this implies a prior sizing step. Sizing images is usually easy; as we know beforehand where it would appear, and at what size. Text may be a bit trickier; as we usually fix a dimension (width or height) then let the text flow with respect to the desired alignment, consuming space depending on the font and other text attributes. Fortunately, there are more than one way to calculate bounding rectangles for attributed strings. The simplest method is NSAttributedString’s <a href="https://developer.apple.com/documentation/foundation/nsstring/1524729-boundingrect">boundingRect</a>. Other ways involve utilizing NSLayoutManager, NSTextContainer, and NSTextStorage trio for advanced text layout.</p><h3>A Simple Demo</h3><p>I made a very <a href="https://github.com/ahmedk92/PrerenderingDemo">simplistic demo</a> that showcases the gains in a scrolling use case. Notice the regular implementation (left) stutters on fast scrolling, while the prerendered implementation (right) scrolls like the wind. One cost is to engineer when to pre-load the pre-rendered conent. I went with an inefficient way for the sake of simplicity (i.e. loading all beforehand). This is a real cost for such approach.</p><h3>Where to go from here?</h3><p>I’m just exploring this technique myself. It’s not something new. There are already amazing libraries which adopt this approach; namely Ryan Nystrom’s <a href="https://github.com/GitHawkApp/StyledTextKit">StyledTextKit</a>, and <a href="https://texturegroup.org/">Texture</a> (AsyncDisplayKit).</p><h3>Notes</h3><p><em>[The following bullet list may be not formatted properly as nested lists are not supported by Medium]</em></p><ul><li>When using UIGraphicsBeginImageContextWithOptions, take some notes:</li><li>The third parameter is the scale at which the bitmap is generated. A zero values picks the device’s scale (i.e. 2x, 3x). This helpful in emulating vector drawing behavior in zoomable views by redrawing content at a higher scale (e.g. device scale * zoom scale).</li><li>Don’t forget to call UIGraphicsEndImageContext after done dealing with the image context. This is to clean up memory. This approach can use memory extensively, it’s a really important step.</li><li>The second parameter is whether to draw opaquely or transparent. If you know that your view is going to be not transparent, it’s good to set this to true, as transparency is a computationally expensive task. See this <a href="https://developer.apple.com/videos/play/wwdc2012/506/">WWDC session at 29:28 mark</a>.</li><li>Use a serial DispatchQueue instead of a gloabl queue if you’re going to render multiple views in series, or group them in a single block to be executed in a global queue. Anyways don’t execute each block individually in a gobal queue. This to avoid creating more threads than CPU can handle; what’s called “Thread Explosion”. See this <a href="https://developer.apple.com/videos/play/wwdc2018/219/?time=1002">WWDC talk at 16:42 mark</a>.</li><li>When using NSAttributedString’s boundingRect:</li><li>You have to use an NSAttributedString instance with at least .font and .foregroundColor attributes set, or else it won’t give correct results.</li><li>The first CGSize parameter it takes marks what constrained dimension it expects, and what other dimension to compute. For example, to emulate the behaviour of a UILabel with numberOfLines set to 0, you provide a fixed width, and a height value of .greatestFiniteMagnitude. <a href="https://github.com/ahmedk92/PrerenderingDemo/blob/a17dddf3bf609344499056c1b52e16bee40bf3ee/PrerenderingDemo/LabelModel.swift#L31">Example</a>.</li></ul><p><em>Originally published at </em><a href="https://ahmedk92.github.io/2019/03/23/Rendering-off-main-thread-in-iOS.html"><em>ahmedk92.github.io</em></a><em> on March 23, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80bd782e7136" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Non-Repeatable viewDidAppear Logic]]></title>
            <link>https://medium.com/@ahmedkhalaf.92/non-repeatable-viewdidappear-logic-aac31e4f324c?source=rss-e30e8c841607------2</link>
            <guid isPermaLink="false">https://medium.com/p/aac31e4f324c</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Ahmed Khalaf]]></dc:creator>
            <pubDate>Tue, 05 Feb 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-02-05T11:12:48.893Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes we need to show an alert, apply a gradient, or conditionally show another view controller on the startup of a view controller. We wish to do such thing in viewDidLoad, however we end up doing it in viewDidAppear(_:). This is because such purposes have requirements that are not fulfilled when viewDidLoad executes; e.g. frames are not yet correct, view hierarchy is not ready, …etc.</p><p>One annoyance with viewDidAppear(_:) is that it can get called multiple times. For example, if you present a new view controller, then dismiss it sometime after, it gets called again. You have to handle such logic that shouldn’t be repeated.</p><h3>Solutions that work, but I don’t quite like</h3><h4>1. Booleans</h4><p>One can introduce a Bool like viewAppeared; checking and setting it for once:</p><pre>var viewAppeared = false </pre><pre>override func viewDidAppear(_ animated: Bool) {  <br>  super.viewDidAppear(animated) </pre><pre>  if !viewAppeared { <br>    // Do non-repeatable logic...<br>  } </pre><pre>  viewAppeared = true</pre><pre>}</pre><p>It works. However, I tend to try to avoid “state variables” as much as I can (doesn’t mean I succeed much 😅). Although they look simple, bugs find their way around them. And in this particular situation, you may need to repeat some check you did earlier in viewDidLoad, and it gets less nice:</p><pre>var name: String? </pre><pre>override func viewDidLoad() { <br>  super.viewDidLoad() <br>  if let name = name { <br>    // conditional initial setup<br>  }<br>} </pre><pre>override func viewDidAppear(_ animated: Bool) { <br>  super.viewDidAppear(animated) </pre><pre>  if !viewAppeared { </pre><pre>    // this check again <br>    if let name = name { <br>    } <br>  } </pre><pre>  viewAppeared = true </pre><pre>}</pre><h4>2. Deferring with GCD</h4><p>Magic. GCD helps in executing code <em>later</em>. There are two ways to do it for our need: async and asyncAfter(deadline:execute:). We can use either in viewDidLoad to execute non-repeatable code “later enough”.</p><p>asyncAfter(deadline:execute:) is straight forward:</p><pre>override func viewDidLoad() { <br>  super.viewDidLoad() </pre><pre>  DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { <br>    // Non-repeated logic <br>  } <br>}</pre><p>Why 0.1 seconds? No idea. It’s just late enough. It works, but it depends on a magic number, we don’t know exactly when this code runs.</p><p>What about just async? It works too, no explicit delay needed. That’s because code in a DispatchQueue.main.async block <strong>is executed in the next </strong><a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html"><strong>run loop</strong></a>.</p><p>Believe me, I’ve read a lot about run loops, I still don’t understand them much. However, for the main thread, you can interpret them as time slices in which the main thread accepts input, updates UI, calculate layouts, and more importantly <strong><em>“polls”</em> code enqueued via </strong><strong>DispatchQueue.main.async</strong>.</p><p>So, When we dispatch code async on the main queue from the main thread, it doesn’t run immediately; it waits to be polled in the next run loop, leaving enough time for the requirements mentioned above to be fulfilled. Remember our blog post? 😂 Now let’s continue it. This GCD thing worth it’s own blog post.</p><blockquote><em>If you look at code I wrote (I hope you don’t), you’ll find me guilty of using this to hack my way through. It’s not good, I don’t recommend it. We should invest more time to really solve latency problems rather than working around them.</em></blockquote><h3>A Better Solution?</h3><p>Here I suggest a solution that I think is better. GCD gave us a hint, we need to queue tasks on viewDidLoad; but execute it later. So, what about queuing it on viewDidLoad, then execute it on viewDidAppear(_:)?</p><pre>private var viewDidAppearQueue: [() -&gt; ()] = [] </pre><pre>override func viewDidLoad() { <br>  super.viewDidLoad() <br>  viewDidAppearQueue.append { <br>    // Our non-repeatable logic <br>  } <br>} </pre><pre>override func viewDidAppear(_ animated: Bool) { <br>  super.viewDidAppear(animated) </pre><pre>  // Dequeue tasks and execute them in FIFO order <br>  while !viewDidAppearQueue.isEmpty { <br>    viewDidAppearQueue.removeFirst()() <br>  } <br>}</pre><p>We introduce a simple array of closures. We add our tasks as closures in viewDidLoad. Then in viewDidAppear(_:) we execute each closure and remove it from the array. If there are no tasks; nothing happens, just what we need.</p><p>We also don’t need to weakly capture self (i.e. [weak self] in) when appending closures. This is because strong references to the closures are lost when we remove them from the array. So, we should be safe.</p><p>Thanks for reading. Feedback is welcome.</p><p><em>Originally published at </em><a href="https://ahmedk92.github.io/2019/02/05/Non-Repeatable-viewDidAppear-Logic.html"><em>ahmedk92.github.io</em></a><em> on February 5, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aac31e4f324c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Experimenting With targetContentOffset: Uneven Pagination]]></title>
            <link>https://medium.com/@ahmedkhalaf.92/experimenting-with-targetcontentoffset-uneven-pagination-4c2cc2a18dbd?source=rss-e30e8c841607------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c2cc2a18dbd</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Ahmed Khalaf]]></dc:creator>
            <pubDate>Sat, 19 Jan 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-01-24T20:28:41.346Z</atom:updated>
            <content:encoded><![CDATA[<p>There are at least three ways of paginating content in iOS. Namely, via UIScrollView, UIPageViewController, and UICollectionView.</p><p>For simplicity, I’ll consider only horizontal pagination from now on in this post.</p><p>UIPageViewController paginates its contents by setting its transitionStyle property to .scroll. UIScrollView and UICollectionView paginate their content by setting their isPagingEnabled property to true.</p><p>It’s worth noting that all these solutions are essentially built upon UIScrollView. UIPageViewController uses a special UIScrollView subclass (private API I think) called _UIQueuingScrollView. UICollectionView is a UIScrollView subclass.</p><h3>Limitations</h3><h3>1. Page Size is Fixed</h3><p>A common trait among the previous solutions is the fixed page size. That is, the amount by which content is paged is always equal to the scrollView frame. If you want to have a page size different from the visible “frame”, you have to seek workarounds; e.g. this clever solutions [<a href="http://khanlou.com/2013/04/changing-the-size-of-a-paging-scroll-view/">1</a>, <a href="http://khanlou.com/2013/04/paging-a-overflowing-collection-view/">2</a>] by Khanlou.</p><h3>2. Uneven Page Size</h3><p>Another limitation is if you want more than a page size in a single flow. For example, when your flow can be considered a series of pairs, where each pair of pages are separated by a constant spacing, while each item of each pair is separated by a different amount of spacing. I think this is impossible to work around with the above solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*7i2zmiSobnn-Ujjy.png" /><figcaption>No space between inner pages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*8oiIH7whbxlpAprpBy-EYw.png" /><figcaption>50pt space between each pair</figcaption></figure><p>One can think of having more than one level of pagination to fix this. For example:</p><ol><li>A UIPageViewController for the pairs, while each pair is a UIpageViewController itself.</li><li>A UICollectionView for the pairs, while each pair is a UICollectionView itself.</li><li>Similar thing with raw UIScrollView.</li></ol><p>However, these solutions have problems.</p><ol><li>For the nested UIPageViewController it’s so easy to swipe an entire pair while not noticing. This is because the outer and the inner UIPageViewControllers have contentSize greater than the visible frame (since UIPageViewController always loads 3 pages if possible (left, center, right)). So, any pan gesture can both affect any of them.</li><li>Similar thing can happen too with nested UICollectionViews. However, it can be worked around by disabling prefetching on the outer UICollectionView. This way, the outer UICollectionView only loads one cell (pair cell), while the pair cell can load its full content; so the pan gesture would work fine with inner UICollectionView as expected. However, on fast scrolling, this seems to not work; and pairs are again skipped.</li></ol><h3>scrollViewWillEndDragging(_:withVelocity:targetContentOffset:) has something to say</h3><p>UIScrollViewDelegate has this interesting method that is called when the user ends dragging. It reports the velocity by which the user did their swipe, and (which is our focus) passes the expected content offset at which the scrollView would stop! So clever! And there’s more to it. It’s possible to change that expected offset so the scrollView smoothly stops at a desired position!</p><p>So, knowing this, we can “snap” the decelerating scrollView to a position of our choice, so there is a chance to solve our uneven page size problem.</p><h3>Idea</h3><p>(Using a UICollectionView of pairs, where each cell is a pair of UIView subclass)</p><p>Given an item width equal to the visible frame. Each pair of items are separated by 50 pts of space on each side. We can:</p><ol><li>We can partition of content into a series of evenly sized pairs (including spacing). That is, each pair width = item width * 2 + spacing (25 pts at each side).</li><li>When scrollViewWillEndDragging is called, we can inspect the targetContentOffset and see at what index of pairs that offset value should correspond. Such index can be achieved by dividing (integer division) the value of the targetContentOffset by the pair width.</li><li>Note that targetContentOffset always points to the leftmost of the screen. This causes a bias to the left side of scrolling, so that way, integer division would be inclined to get lesser indices; 1 is more likely to come than 2, 2 is more likely to come than 3, and so on… One way to overcome this is to offset the targetContentOffset a little to balance this bias; making it points to the middle of the screen rather than it leftmost edge. To achieve this, just add half of the visible frame width to the targetContentOffset before integer division.</li><li>Now we have a correct index of a pair. We only have to decide which part of the pair we want to snap to. So, the sizes of each part of the pair should be known to us. That way we can decide which part is close to the adjusted targetContentOffset calculated above (adjusted to the middle of visible frame). And that’s it. Now finally alter the value targetContentOffset to achieve our desired effect, e.g.: targetContentOffset.pointee.x = rightItemX.</li></ol><p>Notes:</p><ol><li>We don’t use isPagingEnabled here; we use normal scrolling. The default deceleration rate may be too slow; so setting the UICollectionView’s decelerationRate to .fast should do it.</li><li>We have to inset the UICollectionView by half the spacing at each side to achieve contentSize multiple to that of pair width.</li><li>Large swipes may cause jumping over a page. This avoidable by clamping the amount by which the targetContentOffset changes. It may also appear as a feature not a defect. 😄</li><li>Very weak swipes that are not enough to make a page change caused a choppy animation. I mitigated this by detecting it (non-zero velocity, same targetContentOffset) then setting the content offset with an animation.</li></ol><h3>Conclusion</h3><p>Here is a <a href="https://github.com/ahmedk92/UnevenPagination">demo in Swift</a> that implements what’s above.</p><p>Although the solution presented here may not be perfect, it’s the best I could come up with. It’s a tricky problem that I hadn’t find a complete solution for it so far.</p><p>Thanks for reading!</p><p><em>Originally published at </em><a href="https://ahmedk92.github.io/2019/01/19/Experimenting-With-targetContentOffset-Part-1-Uneven-Pagination.html"><em>ahmedk92.github.io</em></a><em> on January 19, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c2cc2a18dbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arabic As A Default Language for Your iOS App]]></title>
            <link>https://medium.com/@ahmedkhalaf.92/arabic-as-a-default-language-for-your-ios-app-228625e15968?source=rss-e30e8c841607------2</link>
            <guid isPermaLink="false">https://medium.com/p/228625e15968</guid>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[arabic]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Ahmed Khalaf]]></dc:creator>
            <pubDate>Fri, 10 Aug 2018 00:00:00 GMT</pubDate>
            <atom:updated>2019-01-31T14:12:45.154Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes you want to make an Arabic-only app. Or you may want to support some languages, but you want Arabic to be the default app language. Here we see how it’s done, as it’s not intuitive to figure out.</p><h3>Scenario 1: The app’s single language is Arabic</h3><p>You may be tempted to layout your views directly in Xcode’s Interface Builder exactly as your design guide suggests. For example, if your design is like the image below, you may decide to put the button on the leading side, and the textfield on the trailing side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*eYmh-JKCMCksef5e.png" /></figure><p>The problem with this approach is that iOS will consider this to be how you want your app to look in Left-to-Right mode. That is, back buttons in the navigation bar stil will be by default on the left, alongside the navigation controller’s back swipe gesture.</p><p>So, the better option is to implement it as if your project is localized. That is, Put the textfield on the leading side, and the button on the trailing side. But you may ask, what will flip our views to give us our desired outcome?</p><h3>Answer: CFBundleDevelopmentRegion</h3><ol><li>Open your project’s info.plist as source code (Right-click -&gt; open as source code).</li><li>Look for CFBundleDevelopmentRegion. You’ll probably find it something like $(DEVELOPMENT_LANGUAGE). Change that to ar.</li></ol><p>That’s it. Run your project and enjoy your flipped interface.</p><p>However, I don’t like this approach. As it may leave your project with a somewhat nonsensical project configuration. I mean, if you open your project settings (not target settings), you’ll find these configurations in the Localization section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*_klNjXas8J3PKkCJ.png" /></figure><p>It says English is the development language, while it’s really not the case. While you can remove it, and add Arabic, you don’t get the - Development Language part infront of it. Also, Xcode will generate Arabic localization files for your storyboards which you probably don’t need.</p><p>I prefer the following approach albeit a bit hacky.</p><p>Steps:</p><ol><li>Navigate to your project.xcodeproj.</li><li>Right-click and choose Show Package Contents.</li><li>Open project.pbxproj with a text editor.</li><li>⌘ + F and look for the word region. You should find two matches, developmentRegion and knownRegions. Change the en in their values to ar, like the image below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*4LpJBI__NKdxPcj0.png" /></figure><p>That’s it. You get Arabic as the development language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*wYxflcYiPcepK21q.png" /></figure><h3>Scenario 2: Arabic as first language in a localized app</h3><p>Your app is already localized. You support multiple languages. But you want the first run of your app to be in Arabic, and the user can change that later. What to do?</p><p>Before we begin, it’s better to know how iOS choose the right language for our app. It’s explained <a href="https://developer.apple.com/library/archive/qa/qa1828/_index.html">here in this official Q&amp;A</a>, but I’ll write the gist of it.</p><p>iOS selects the first language in the user’s language preferences list (in General &gt; Language &amp; Region of the Settings application). Then looks in your project for a matching .lproj folder. Such folder contains the relevant .strings files for the localized resource (e.g. Storyboard). Every language you support has a .lproj folder with the language prefix, e.g. ar.lproj, en.lproj, …etc. So, on app start, iOS selects the localization that <strong>it sees correct, and doesn’t refer to you (the developer) for such decision</strong>.</p><p>That is for apps supporting languages in the user’s language preferences list. If the user’s language preferences list doesn’t match any .lproj folders in your app, iOS uses the CFBundleDevelopmentRegion. And that’s basically how things work in <strong>Scenario 1</strong> above.</p><p>So, our task here is to bypass that preferences list check. Fortunately, iOS seems to store a copy of such preferences list in each app’s user defaults. So if you want tp retrieve it in run-time, you can query it like this:</p><pre>NSUserDefaults* defs = [NSUserDefaults standardUserDefaults]; NSArray* languages = [defs objectForKey:@&quot;AppleLanguages&quot;]; NSString* preferredLang = [languages objectAtIndex:0]; NSLog(@&quot;Current language is %@&quot;, preferredLang);</pre><p>This is a <a href="https://developer.apple.com/library/archive/samplecode/InternationalMountains/Listings/InternationalMountains_DetailViewController_m.html">code snippet</a> from Apple Samples on Localization.</p><p>Fortunately, this user defaults entry is writable. So, we can replace that preferences list with one of our own. An array of language identifiers where Arabic is the first is enough for Arabic to be the default, e.g. [&quot;ar&quot;].</p><p>So far so good. Now the question left is where to set that new array?</p><p>application:didFinishLaunchingWithOptions: is not early enough to set such key. The true starting point of any iOS app is a function called main. It may be unknown to Swift iOS developers, but it’s well-known for those who worked with Objective-C.</p><p>In Objective-C projects, you can easily find it in a file called main.m. It looks like this:</p><p>Objective-C:</p><pre>#import &lt;UIKit/UIKit.h&gt; <br>#import &quot;AppDelegate.h&quot;  </pre><pre>int main(int argc, char * argv[]) { <br>    @autoreleasepool { <br>        return UIApplicationMain(<br>            argc, <br>            argv, <br>            nil, <br>            NSStringFromClass([AppDelegate class])<br>        );<br>    } <br>}</pre><p>In Swift projects, it’s a bit weird. As described in <a href="https://www.hackingwithswift.com/example-code/uikit/how-to-subclass-uiapplication-using-uiapplicationmain">Hacking with Swift</a>, you need to delete @UIApplicationMain from your AppDelegate class, then add a file <strong><em>exactly</em></strong> named main.swift. For our purpose, the main.swift file will look like this:</p><pre>class MyApplication: UIApplication { <br>  override init() { <br>    let notFirstOpenKey = &quot;notFirstOpen&quot; <br>    let notFirstOpen = UserDefaults.standard.bool(forKey: notFirstOpenKey) <br>    if notFirstOpen == false { <br>      UserDefaults.standard.set([&quot;ar&quot;], forKey: &quot;AppleLanguages&quot;) <br>      UserDefaults.standard.set(true, forKey: notFirstOpenKey)<br>    } <br>    super.init() <br>  } <br>} </pre><pre>UIApplicationMain(<br>  CommandLine.argc, <br>  UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(<br>    to: UnsafeMutablePointer&lt;Int8&gt;.self, <br>    capacity: Int(CommandLine.argc) <br>  ), <br>  NSStringFromClass(MyApplication.self), <br>  NSStringFromClass(AppDelegate.self) <br>)</pre><p>The bottom part, UIApplicationMain, is explained in the <a href="https://www.hackingwithswift.com/example-code/uikit/how-to-subclass-uiapplication-using-uiapplicationmain">Hacking with Swift article above</a>. What’s relevant to us here is the implementation of the MyApplication subclass.</p><p>As you may be already understanding by now, MyApplication is our custom class implementation of UIApplication. So, its init method can be regarded as the very inception of our app; the first milliseconds of our app’s life. Here we can set the AppleLanguages key, and make use of its effect.</p><p>In the code snippet above, I do an additional check to see if we’ve done this before; to avoid unwanted repetition.</p><p>That’s it. We’re done. It’s finally over.</p><h3>References</h3><p><a href="https://www.ralfebert.de/ios-examples/xcode/change-development-language/">Changing default development language</a></p><p><em>Originally published at </em><a href="https://ahmedk92.github.io/2018/08/10/Arabic-As-A-Default-Language-for-Your-iOS-App.html"><em>ahmedk92.github.io</em></a><em> on August 10, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=228625e15968" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enabling Optimizations for CocoaPods in Debug Mode]]></title>
            <link>https://medium.com/@ahmedkhalaf.92/enabling-optimizations-for-cocoapods-in-debug-mode-ff75a7b97c32?source=rss-e30e8c841607------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff75a7b97c32</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[cocoapods]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Ahmed Khalaf]]></dc:creator>
            <pubDate>Fri, 15 Jun 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-10-09T18:41:23.068Z</atom:updated>
            <content:encoded><![CDATA[<p>Compiler optimizations are disabled by default in Debug mode. This is to enable a sane debug experience by avoiding omitted variables (or even whole blocks of code). Such omissions are often done as a part of the optimization phase in a compiler work.</p><h3>Problem</h3><p>Sometimes, we use a dependency (e.g. via CocoaPods) that may perofrm noticebly slower in Debug mode. Since it’s a dependency, and as long as it isn’t causing problems, we probably are not interested in debugging it. Therefore we can comfortably enable optimizations in Debug mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zEG_QqLpj_pqJp9K.png" /></figure><h3>⚠️ Not A Lasting Solution ⚠️</h3><p>This will get reset after the very first pod install. To overcome this, add a post-install CocoaPods “hook”:</p><pre>post_install do |installer|<br>      targetsToOptimizeAtDebug = [&#39;SwiftSoup&#39;]<br>      <br>      installer.pods_project.targets.each do |target|<br>          if targetsToOptimizeAtDebug.include? target.name<br>            target.build_configurations.each do |config|<br>                if config.name == &quot;Debug&quot;<br>                    config.build_settings[&#39;SWIFT_OPTIMIZATION_LEVEL&#39;] = &#39;-Owholemodule&#39;<br>                end<br>            end<br>          end<br>      end<br>  end</pre><h3>That’s it! ✅</h3><p>Now for every relevant pod, you can add it to the array above, and forget.</p><p><em>Originally published at </em><a href="https://ahmedk92.github.io/2018/06/15/Enabling-Optimizations-for-CocoaPods-in-Debug-Mode.html"><em>ahmedk92.github.io</em></a><em> on June 15, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff75a7b97c32" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>