<?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 Richard Yip on Medium]]></title>
        <description><![CDATA[Stories by Richard Yip on Medium]]></description>
        <link>https://medium.com/@richardyip?source=rss-b6fd7af81dd5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VsYaT4tzte6tR55Crtrzlw@2x.jpeg</url>
            <title>Stories by Richard Yip on Medium</title>
            <link>https://medium.com/@richardyip?source=rss-b6fd7af81dd5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:53:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@richardyip/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[Porting my iOS app to Andriod]]></title>
            <link>https://medium.com/@richardyip/porting-my-ios-app-to-andriod-8f8b88e9abcf?source=rss-b6fd7af81dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8b88e9abcf</guid>
            <dc:creator><![CDATA[Richard Yip]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 04:50:37 GMT</pubDate>
            <atom:updated>2026-07-21T04:50:37.062Z</atom:updated>
            <content:encoded><![CDATA[<p>My <a href="https://www.linkedin.com/search/results/all/?keywords=%23ios&amp;origin=HASH_TAG_FROM_FEED">#iOS</a> app <a href="https://www.linkedin.com/search/results/all/?keywords=%23where2sg&amp;origin=HASH_TAG_FROM_FEED">#where2SG</a> has reached maturity with clear seperation of UI, ViewModels, Models, Data and Networking.<br>Thinking of ways porting code to Android.</p><p>Got a few pathways.<br>Using the traditional IOS to Android code conversion of <a href="https://www.linkedin.com/search/results/all/?keywords=%23swift&amp;origin=HASH_TAG_FROM_FEED">#Swift</a> to <a href="https://www.linkedin.com/search/results/all/?keywords=%23kotlin&amp;origin=HASH_TAG_FROM_FEED">#Kotlin</a><br>But with recent massive updates to Swift and SwiftUI recently, especially Async / Await and <a href="https://www.linkedin.com/search/results/all/?keywords=%23lliquidglass&amp;origin=HASH_TAG_FROM_FEED">#lLiquidGlass</a>, it is quite difficult to present the equivalent within Android.</p><p>One way is to keep the business logic as Swift and develop from scratch the Android UI. Keep business logic common and start to develop new UI in Android.</p><p>Other suggest using KMP to share a single codebase for Android, IOS, web and desktop.<br>Maybe should consider porting to <a href="https://www.linkedin.com/search/results/all/?keywords=%23flutter&amp;origin=HASH_TAG_FROM_FEED">#Flutter</a> to support both <a href="https://www.linkedin.com/search/results/all/?keywords=%23iios&amp;origin=HASH_TAG_FROM_FEED">#IIOS</a> and <a href="https://www.linkedin.com/search/results/all/?keywords=%23andriod&amp;origin=HASH_TAG_FROM_FEED">#Andriod</a></p><p>Seems like got lots of options?<br>For me it’s like trying not to do too much. UI is just presentation, just grab whatever data needed for the views. The hard part is choosing, selecting and composing data needed.</p><p>As long the contract is established aka mostly struct data needed for presentation is confirmed, and logic and data is throughly tested; I will likely find the solution of just building Android UI with existing View Models, Models and Data models more than acceptable.<br>A bit hard since I am considering to replace <a href="https://www.linkedin.com/search/results/all/?keywords=%23realmswift&amp;origin=HASH_TAG_FROM_FEED">#RealmSwift</a> with <a href="https://www.linkedin.com/search/results/all/?keywords=%23swiftdata&amp;origin=HASH_TAG_FROM_FEED">#SwiftData</a>.<br>Maybe just normal <a href="https://www.linkedin.com/search/results/all/?keywords=%23sqlite&amp;origin=HASH_TAG_FROM_FEED">#Sqlite</a> will do.<br>J</p><p>ust a bit of rant.</p><p>Do welcome feedback and like to hear more of how you guys port apps from <a href="https://www.linkedin.com/search/results/all/?keywords=%23ios&amp;origin=HASH_TAG_FROM_FEED">#IOS</a> to <a href="https://www.linkedin.com/search/results/all/?keywords=%23android&amp;origin=HASH_TAG_FROM_FEED">#Android</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8b88e9abcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[where2SG next version update]]></title>
            <link>https://medium.com/@richardyip/where2sg-next-version-update-cdd642ec3f57?source=rss-b6fd7af81dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd642ec3f57</guid>
            <dc:creator><![CDATA[Richard Yip]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 03:20:06 GMT</pubDate>
            <atom:updated>2026-06-06T03:20:06.611Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s something you may heard about bus ghosting recently.<br>Lots of speculations why got no ETA from transport Apps and all of sudden bus comes arriving. Local bus enthusiast call it bus ghosting like bus just gone missing!</p><p>Most of the issues are buses not updating their location and thus missing in action or bunched up upon arrival.</p><p>Nothing much you can do when got no ETA data from buses. However almost no bus apps including official LTA app never include alternate data if ETA is no good. It’s data from traditional bus stop time table which uses first, last bus at bus stop and bus interval minutes. Just some work and using average bus speed, you can actually determine bus arrival at stop.</p><p>All current local bus apps in Singapore does not provide such alternative except maybe Goggle, Apple and international bus and train apps.</p><p>Here’s something I realised recently when updating bus arrivals for the app.<br>Early buses are strategically located along the route to start and arrive at designated bus stops on time. You can find such empty stationary buses with no passengers very early in morning with driver almost asleep or watching their favourite TikTok videos. These drivers are still doing their job, just waiting for the right time to start driving bus towards designated stops.</p><p>Almost all local bus apps does not include this use case and prefer not to show it all.</p><p>Commuters need more information in planning their bus trips especially early in the morning. Need to know first bus at stop and subsequent early buses.<br>Commuters like first early shift, kids going to school, army guys reporting to camp and night shift workers desperately going home to have some sleep.</p><p>Next version of my app <a href="https://www.reddit.com/user/where2SG/">u/where2SG</a> provide option to show ETA from bus location or timing using bus schedule. Also include this edge case to remove ghosting for early buses.</p><p>Do welcome comments, feedback and downloads of my next version of the app <a href="https://www.reddit.com/user/where2SG/">u/where2SG</a></p><p><a href="https://www.reddit.com/user/where2SG/">u/where2SG</a><br><a href="https://www.reddit.com/user/LTA/">u/LTA</a><br><a href="https://www.reddit.com/user/SBSTransit/">u/SBSTransit</a><br><a href="https://www.reddit.com/user/SMRTBuses/">u/SMRTBuses</a><br><a href="https://www.reddit.com/user/TowerTransit/">u/TowerTransit</a><br><a href="https://www.reddit.com/user/Go-Ahead/">u/Go-Ahead</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd642ec3f57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dates is just a moment in time]]></title>
            <link>https://medium.com/@richardyip/dates-is-just-a-moment-in-time-13fae7800455?source=rss-b6fd7af81dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/13fae7800455</guid>
            <dc:creator><![CDATA[Richard Yip]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 02:51:20 GMT</pubDate>
            <atom:updated>2024-01-04T02:51:20.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Most time, you are just happy with current locale for dates and timezones for the data received from Rest API.</p><p>What if your Rest API is local in a sense that provide date strings in local time zone? Two ways about it. Either do local or standard UTC dates.</p><p>Working with local time zones is myopic and prone to conversion errors computing dates and intervals.</p><p>I always reference dates from UTC and work from them.</p><p>Here’s an example code to read time string from local time zone and adjust dates to UTC.</p><pre>    private func parseStartEndTime(_ startString: String, endString: String) -&gt; (Date, Date) {<br>        var start = Date.distantPast<br>        var end = Date.distantFuture<br>        <br>        var startEndDates = (start, end)<br>        <br>        guard !startString.isEmpty else {<br>            return startEndDates<br>        }<br>        <br>        guard !endString.isEmpty else {<br>            return startEndDates<br>        }<br>        <br>        let now = Date()<br>        let nowComponents = Calendar.current.dateComponents([.day, .month, .year], from: now)<br>        <br>        start = dateFormatter.date(from: startString)!<br>        let startComponents = Calendar.current.dateComponents([.hour, .minute, .second], from: start)<br>        <br>        var components = DateComponents(calendar: Calendar.current, year: nowComponents.year, month: nowComponents.month, day: nowComponents.day, hour: startComponents.hour, minute: startComponents.minute, second: startComponents.second)<br>    <br>        start = components.date!<br><br>        end = dateFormatter.date(from: endString)!<br>        let endComponents = Calendar.current.dateComponents([.hour, .minute, .second], from: end)<br>        <br>        components = DateComponents(calendar: Calendar.current, year: nowComponents.year, month: nowComponents.month, day: nowComponents.day, hour: endComponents.hour, minute: endComponents.minute, second: endComponents.second)<br>    <br>        end = components.date!<br>        <br>        //  update start and end from local to UTC timezone<br>        var calender = Calendar(identifier: .gregorian)<br>        calender.timeZone = TimeZone(identifier: &quot;UTC&quot;)!<br>        var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }<br>        <br>        if secondsFromGMT &gt; 0 {<br>            components = DateComponents(calendar: calender, year: nowComponents.year, month: nowComponents.month, day: nowComponents.day, hour: startComponents.hour, minute: startComponents.minute, second: startComponents.second! - secondsFromGMT)<br>            start = components.date!<br>            <br>            components = DateComponents(calendar: calender, year: nowComponents.year, month: nowComponents.month, day: nowComponents.day, hour: endComponents.hour, minute: endComponents.minute, second: endComponents.second! - secondsFromGMT)<br>            end = components.date!<br>        }<br>        else {<br>            components = DateComponents(calendar: calender, year: nowComponents.year, month: nowComponents.month, day: nowComponents.day, hour: startComponents.hour, minute: startComponents.minute, second: startComponents.second! + secondsFromGMT)<br>            start = components.date!<br>            <br>            components = DateComponents(calendar: calender, year: nowComponents.year, month: nowComponents.month, day: nowComponents.day, hour: endComponents.hour, minute: endComponents.minute, second: endComponents.second! + secondsFromGMT)<br>            end = components.date!<br>        }<br><br>        if start.timeIntervalSince1970 &gt; end.timeIntervalSince1970 {<br>            end = calender.date(byAdding: .day, value: 1, to: end)!<br>        }<br>        <br>        startEndDates = (start, end)<br>        <br>        return startEndDates<br>    }</pre><p>Got start and time strings in local time zones.</p><p>Get current date in local time and update to full dates given only hours, minutes and seconds time string.</p><p>Next get seconds from GMT from local time zone.</p><p>Using a new calendar with UTC time zone and apply the difference in seconds for dates in UTC.</p><p>Hope you like this code snippet that helps you convert local time zone dates to UTC dates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13fae7800455" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tokenising and Parsing Texts with Swift]]></title>
            <link>https://medium.com/@richardyip/tokenising-and-parsing-texts-with-swift-7225ce1ed880?source=rss-b6fd7af81dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7225ce1ed880</guid>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[address]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Richard Yip]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 01:12:23 GMT</pubDate>
            <atom:updated>2023-10-14T01:45:54.558Z</atom:updated>
            <content:encoded><![CDATA[<p>Seems easy lah. But lots of hiccups trying this. In the end, need good test cases, word states, string management and lots of patience to make it work.</p><p><strong>Problem</strong></p><p>Got addresses from 3 different data sources. Each address is structured slightly different. Typical #Singapore address might be <strong>LORONG 37 GEYLANG</strong>, or <strong>BLK 441–455 SIN MING AVENUE/BRIGHT HILL DRIVE</strong>, maybe <strong>SULTAN GATE — ALIWAL STREET OFF STREET</strong></p><p>Need to normalise the addresses into string texts that easy for listing and sorting. Basically, to strip words into simple address text.</p><p><strong>Tokenizer</strong></p><p>import NaturalLanguage and used the tokenizer to split the address text into tokens / simple worlds. You can roll your own string tokenizser but I am using standard Apple framework.</p><pre>import Foundation<br>import NaturalLanguage<br><br>class AddressParser {<br>    <br>    var addressStack = Stack()<br>    <br>    func tokenizeText(for text: String) {<br>        <br>        let tokenizer = NLTokenizer(unit: .word)<br>        tokenizer.string = text<br>                <br>        tokenizer.setLanguage(.english)<br>        let fullStringRange = text.startIndex..&lt;text.endIndex<br>        <br>        tokenizer.enumerateTokens(in: fullStringRange) { (range, attributes) -&gt; Bool in<br>            debugPrint(text[range])<br>            addressStack.push(String(text[range]))<br>          return true<br>        }<br>        <br>        debugPrint(addressStack)<br>        addressStack.updateText()<br>        debugPrint(text)<br>        debugPrint(addressStack)<br>    }<br>}</pre><p>Once generated tokens, need to find some patterns and word states to extract or eliminate words.</p><p>Can consider if word is alpha, digits or alphanumeric first.</p><p>Next to static words that are easy to drop like addresses that starts with BLK</p><pre>    mutating func parseBlockText() {<br>        if text.hasPrefix(&quot;BLK &quot;) {<br>            text = String(text.dropFirst(4))<br>        }<br>        if text.hasPrefix(&quot;BLOCK &quot;) {<br>            text = String(text.dropFirst(6))<br>        }<br>        if text.hasPrefix(&quot;BLKS &quot;) {<br>            text = String(text.dropFirst(5))<br>        }<br>    }</pre><p>Once you have removed static words, it’s time to determine the pattern of words to eleminate. BLK is dropped.</p><p>Text</p><p>4001–4003/4026–4028/4033–4035 ANG MO KIO INDUSTRIAL</p><p>Tokens</p><p>4001 4003 4026 4028 4033 4035 ANG MO KIO INDUSTRIAL</p><p>4001, 4003, 4026, 4028, 4033 and alphanumeric and ANG, MO, KIO, INDUSTRIAL are alpha</p><pre>    mutating func beforeAddress() {<br><br>        var current = 0<br>        var next = current + 1<br>       <br>        repeat {<br>    <br>            if items[current].rangeOfCharacter(from: alphaNumerics) != nil &amp;&amp; items[next].rangeOfCharacter(from: alpha) != nil {<br>                debugPrint(items[current])<br>                debugPrint(current)<br>                debugPrint(next)<br>                debugPrint(items[next])<br>                <br>                var address = &quot;&quot;<br>                for k in next...items.count - 1<br>                {<br>                    address = address + &quot; &quot; + items[k]<br>                }<br>                text = address.trimmingCharacters(in: .whitespacesAndNewlines)<br>                <br>                return<br>            }<br>            <br>            if items[current].rangeOfCharacter(from: alphaNumerics) != nil &amp;&amp; items[next].rangeOfCharacter(from: alphaNumerics) != nil {<br>                <br>                debugPrint(items[current])<br>                debugPrint(current)<br>                debugPrint(next)<br>                current += 1<br>                next += 1<br>            }<br>            <br>            if items[current].rangeOfCharacter(from: alpha) != nil &amp;&amp; items[next].rangeOfCharacter(from: digits) != nil {<br>                debugPrint(current)<br>                debugPrint(next)<br>                <br>                debugPrint(items[current])<br>                return<br>            }<br>            <br>        } while next &lt; items.count - 1<br>    }</pre><p>Loop thru the address text with current and next indexes to identify the character type of two adjacent words.</p><p>Once found a pattern, in the case ignore adjacent words.</p><p>Then find a pattern whereby current is alphanumeric and next is alpha to stop, i.e. 4035 and ANG</p><p>You just need the string from next index to end of string.</p><p><strong>Test Case</strong></p><pre>import XCTest<br>@testable import where2Address<br><br>final class where2AddressTests: XCTestCase {<br><br>    let client = AddressParser()<br>    <br>    func testTwoWord() {<br>        let text = &quot;ALIWAL STREET&quot;<br>        client.tokenizeText(for: text)<br>        print(client.addressStack.output())<br>        XCTAssertEqual(client.addressStack.output(), text)<br>    }<br>    <br>    func testStartBlk() {<br>        let text = &quot;BLK 28 HOY FATT ROAD&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseBlockText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;28 HOY FATT ROAD&quot;)<br>    }<br>    <br>    func testStartBlock() {<br>        let text = &quot;BLOCK 676 YISHUN RING ROAD&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseBlockText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;676 YISHUN RING ROAD&quot;)<br>    }<br>    <br>    func testStartBlks() {<br>        let text = &quot;BLKS 59, 62-65 NEW UPPER CHANGI ROAD&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseBlockText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;59 62 65 NEW UPPER CHANGI ROAD&quot;)<br>    }<br><br>    func testStartBackLaneBetween() {<br>        let text = &quot;BACKLANE BET ARAB STREET-JALAN PINANG&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseBackLaneText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;ARAB STREET JALAN PINANG&quot;)<br>    }<br>    <br>    func testStartBackLaneOff() {<br>        let text = &quot;BACKLANE OFF GEMMILL LANE&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseBackLaneText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;GEMMILL LANE&quot;)<br>    }<br>    <br>    func testStartServiceRoadOff() {<br>        let text = &quot;SERVICE ROAD OFF BUKIT  TIMAH ROAD-SIXTH AVE&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseServiceRoadText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;BUKIT TIMAH ROAD SIXTH AVE&quot;)<br>    }<br>    <br>    func testStartServiceRoadBet() {<br>        let text = &quot;SERVICE ROAD BET HAMILTON RD-CAVAN RD&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseServiceRoadText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;HAMILTON RD CAVAN RD&quot;)<br>    }<br>    <br>    func testStartServiceRoadBetween() {<br>        let text = &quot;SERVICE ROAD BETWEEN PETAIN RD-ALLENBY RD&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseServiceRoadText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;PETAIN RD ALLENBY RD&quot;)<br>    }<br>    <br>    func testKerbsideText() {<br>        let text = &quot;- KERBSIDE TIONG BAHRU ESTATE&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseKerbsideText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;TIONG BAHRU ESTATE&quot;)<br>    }<br>    <br>    func testToText() {<br>        let text = &quot;BLK 998A TO 998B,999A TO 999B BUANGKOK CRESCENT&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseToText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;BLK 998A 998B 999A 999B BUANGKOK CRESCENT&quot;)<br>    }<br><br>    func testAndText() {<br>        let text = &quot;BLK 419, 420 AND 420A CLEMENTI AVENUE 1&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseAndText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;BLK 419 420 420A CLEMENTI AVENUE 1&quot;)<br>    }<br><br>    func testAlongText() {<br>        let text = &quot;BLK 45 &amp; 79 ALONG TELOK BLANGAH DRIVE&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseAlongText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;BLK 45 79 TELOK BLANGAH DRIVE&quot;)<br>    }<br>        <br>    func testEndServiceRoad() {<br>        let text = &quot;KENSINGTON PARK ROAD SERVICE ROAD&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseEndServiceRoadText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;KENSINGTON PARK ROAD&quot;)<br>    }<br>    <br>    func testEndOffStreet() {<br>        let text = &quot;BANDA STREET - SAGO LANE OFF STREET&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseEndOffStreetText()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;BANDA STREET SAGO LANE&quot;)<br>    }<br>    <br>    <br>    func testStartBlkNumberBeforeAddress() {<br>        let text = &quot;BLK 28A HOY FATT ROAD&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseBlockText()<br>        client.addressStack.updateToken()<br>        client.addressStack.beforeAddress()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;HOY FATT ROAD&quot;)<br>    }<br>    <br>    func testRemoveNumbersBeforeAlphaNuberAddress() {<br>        let text = &quot;BLK 158-161/163/168-174 LORONG 1 TOA PAYOH&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseBlockText()<br>        client.addressStack.updateToken()<br>        client.addressStack.beforeAddress()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;LORONG 1 TOA PAYOH&quot;)<br>    }<br>    <br>    func testRemoveNumbersBeforeAlphaAddress() {<br>        let text = &quot;BLK 4001-4003/4026-4028/4033-4035 ANG MO KIO INDUSTRIAL&quot;<br>        client.tokenizeText(for: text)<br>        client.addressStack.parseBlockText()<br>        client.addressStack.updateToken()<br>        client.addressStack.beforeAddress()<br>        let result = client.addressStack.output()<br>        XCTAssertEqual(result, &quot;ANG MO KIO INDUSTRIAL&quot;)<br>    }<br>}</pre><p>Takes some time to build this set of test cases but worth every second as I try to sort out state, logic and word patterns.</p><p><strong>Conclusion</strong></p><p>Though I could do the test cases later after sorting out code logic. But realized building the code togther with the test cases improves my understanding and productivity.</p><p>Thanks for reading and hope to have your feedback or comments.</p><p>#swift #naturallanguage #token #string #characterset #patternmatching #address</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7225ce1ed880" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Not really MVVM for the where2 app]]></title>
            <link>https://medium.com/@richardyip/not-really-mvvm-for-the-where2-app-bd018806e9cb?source=rss-b6fd7af81dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd018806e9cb</guid>
            <category><![CDATA[swift-combine]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mapkit]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Richard Yip]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 03:08:01 GMT</pubDate>
            <atom:updated>2023-08-14T03:08:01.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Model-View-ViewModel (MVVM) is an architecture design pattern used in mobile development.</p><p>However; in developing the car park features, I used a slightly different approach in the design and architecture.</p><p>Instead of strictly following MVVM, I use a simplified version of model / service and views. View Models are just published data structures.</p><p>Here’s what I mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AwqZXsChGDINmWg1qUT9A.jpeg" /><figcaption>Carpark model views</figcaption></figure><p>This feature requires a map view, a list view for type selection and filtering, a model / service that’s subscribed to location, consumes REST responses into a Realm table. The model published annotations for the map view and filtered lists for the list view.</p><p><strong>Networking</strong></p><p>Considering REST response data is typically 2000 plus records and do required to make 3 separate API calls to have a complete view of the data.</p><p>2 api calls containing static data are prefetched and loaded into the realm database before the app starts.</p><p>The other API call consists of carpark lot availability which is frequently called.</p><p>All these network APIs are packaged into a separate private module.</p><pre>public class DataMallCarParkClientAPI {<br>    <br>    public init() {}<br>    <br>    public func fetchDataMallCarParks(pageIndex: Int) async throws -&gt; DataMallCarParkResponse? {<br>        var components = URLComponents()<br>        components.scheme = &quot;http&quot;<br>        components.host = &quot;datamall2.mytransport.sg&quot;<br>        components.path = &quot;/ltaodataservice/CarParkAvailabilityv2&quot;<br>        components.queryItems = [<br>            URLQueryItem(name: &quot;$skip&quot;, value: String(format: &quot;%d&quot;, pageIndex))<br>        ]<br><br>        let url = components.url<br>        debugPrint(url as Any)<br>        <br>        var request = URLRequest(url: url!)<br>        request.httpMethod = &quot;GET&quot;<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField:&quot;Content-Type&quot;)<br>        request.setValue(&quot;&quot;, forHTTPHeaderField:&quot;AccountKey&quot;)<br>        request.timeoutInterval = 60.0<br><br>        debugPrint(request)<br>        let (data, _) = try await URLSession.shared.data(for: request)<br>        let result = try? JSONDecoder().decode(DataMallCarParkResponse.self, from: data)<br>        return result<br>    }<br>    <br>}</pre><p><strong>Location</strong></p><p>Published by the location service.</p><pre>    func fetchLocation() {<br>        locationService.$location<br>            .removeDuplicates()<br>            .receive(on: RunLoop.main)<br>            .sink(receiveCompletion: { location in<br>                print(&quot;location&quot;)<br>            }, receiveValue: { [self] location in<br>                if let location {<br>                    myLocation = location<br>                }<br>            }).store(in: &amp;cancellables)<br>    }</pre><p><strong>MapView</strong></p><p>Binds the annotation data, location and map region from the service / model.</p><p>0n lot type change, it remove current annotations and add new lot type annotations based on the bindings to display for the map region.</p><pre>struct CarParkMapView: UIViewRepresentable {<br>    @Binding var region: MKCoordinateRegion<br>    @Binding var regionStatus : RegionStatus<br>    @Binding var carParks: [CarParkAnnotation]<br>    @AppStorage(&quot;lotType&quot;) var lotType : CarParkLotType = .Car<br>    <br>    func makeUIView(context: UIViewRepresentableContext&lt;CarParkMapView&gt;) -&gt; MKMapView {<br>        let mapView = MKMapView()<br>        <br>        mapView.register(CarParkAnnotationView.self, forAnnotationViewWithReuseIdentifier:MKMapViewDefaultAnnotationViewReuseIdentifier)<br>        mapView.register(CarParkClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)<br>        <br>        mapView.userTrackingMode = .follow<br>        mapView.showsUserLocation = true<br>        mapView.isRotateEnabled = false<br>        mapView.isPitchEnabled = false<br>        mapView.showsCompass = false<br>        mapView.showsTraffic = true<br>        mapView.showsBuildings = true<br>        mapView.addAnnotations(carParks)<br>        mapView.delegate = context.coordinator<br>        return mapView<br>    }<br>    <br>    func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext&lt;CarParkMapView&gt;) {<br>                <br>        switch regionStatus {<br>        case .None:<br>            DispatchQueue.main.async {<br>                uiView.setRegion(region, animated: true)<br>                regionStatus = .Updated<br>            }<br>        case .Location:<br>            DispatchQueue.main.async {<br>                uiView.setCenter(region.center, animated: true)<br>                regionStatus = .None<br>            }<br>        case .Updated:<br>            break<br>        case .Annotation:<br>            uiView.removeAnnotations(uiView.annotations)<br>            uiView.addAnnotations(carParks)<br>            uiView.showAnnotations(uiView.annotations, animated: true)<br>            DispatchQueue.main.async {<br>                regionStatus = .Location<br>            }<br>        }<br>    }<br>}</pre><p><strong>List View</strong></p><p>Observes the published filtered nearby and car park lists from the model / view.</p><p>Updates the lot types, nearby and list status to the model / service.</p><p>Fires up repeating timers to fetch the latest nearby and list of carparks with lot availability from the model / service.</p><pre>struct CarParkMainView: View {<br>    @StateObject var ops = CarParkOperations()<br>    @AppStorage(&quot;lotType&quot;) var lotType : CarParkLotType = .Car<br>    @AppStorage(&quot;lotDisplay&quot;) var lotDisplay : CarParkDisplayType = .nearby<br>    <br>    var body: some View {<br>        NavigationStack {<br>            Picker(&quot;What is the lot type?&quot;, selection: $lotType) {<br>                Text(&quot;Car&quot;).tag(CarParkLotType.Car)<br>                Text(&quot;Motorcycle&quot;).tag(CarParkLotType.Motorcycle)<br>                Text(&quot;Heavy Vehicle&quot;).tag(CarParkLotType.HeavyVehicle)<br>            }<br>            .onChange(of: lotType, perform: { newValue in<br>                Task {<br>                    print(newValue)<br>                    await ops.filterCarParks()<br>                }<br>            })<br>            .navigationTitle(String(localized: &quot;Car Park&quot;))<br>            .padding(.leading, 10)<br>            .padding(.trailing, 10)<br>            .pickerStyle(SegmentedPickerStyle())<br><br>            Picker(&quot;Car Park&quot;, selection: $lotDisplay) {<br>                Text(&quot;Nearby&quot;).tag(CarParkDisplayType.nearby)<br>                Text(&quot;List&quot;).tag(CarParkDisplayType.list)<br>            }<br>            .navigationTitle(String(localized: &quot;Car Park&quot;))<br>            .padding(.leading, 10)<br>            .padding(.trailing, 10)<br>            .pickerStyle(SegmentedPickerStyle())<br>            <br>            switch lotDisplay {<br>            case CarParkDisplayType.nearby:<br>                NearbyCarParkView()<br>            case CarParkDisplayType.list:<br>                CarParkView()<br>            }<br>            Spacer()<br>        }<br>        .onAppear() {<br>            Task {<br>                await ops.setupCarParkUI()<br>            }<br>        }<br>        .listStyle(.plain)<br>    }<br>}</pre><p><strong>Model / Service</strong></p><p>The model is supported by 3 extension</p><p><strong>Main</strong></p><p>Published region, regionStatus, filtered car parks, filtered nearby car parks.</p><p>Add AppStorage for lotType, lotDisplay, lotSearchText</p><p>On init() fetch location, setup car park UI and setup car park annotation items.</p><p>One method called often is filter car parks.</p><pre>extension CarParkOperations {<br>    <br>    @MainActor func filterCarParks() async {<br>        await setupCarParkUI()<br>        switch lotType {<br>        case CarParkLotType.Car :<br>            switch lotDisplay {<br>            case CarParkDisplayType.nearby:<br>                let cars = carParks.filter{$0.lotType == .Car}<br>                let nearby = nearestCarParks(carParks: cars)<br>                if lotSearchText.isEmpty {<br>                    filteredNearbyCarParks = nearby<br>                }<br>                else {<br>                    filteredNearbyCarParks = searchNearbyCarParks(carParks: nearby, searchText: lotSearchText)<br>                }<br>            case CarParkDisplayType.list:<br>                let list = carParks.filter{$0.lotType == .Car}<br>                if lotSearchText.isEmpty {<br>                    filteredCarParks = list<br>                }<br>                else {<br>                    filteredCarParks = searchCarParks(carParks: list, searchText: lotSearchText)<br>                }<br>            }<br>        case CarParkLotType.Motorcycle:<br>            switch lotDisplay {<br>            case CarParkDisplayType.nearby:<br>                let motorcycles = carParks.filter{$0.lotType == .Motorcycle}<br>                let nearby = nearestCarParks(carParks: motorcycles)<br>                if lotSearchText.isEmpty {<br>                    filteredNearbyCarParks = nearby<br>                }<br>                else {<br>                    filteredNearbyCarParks = searchNearbyCarParks(carParks: nearby, searchText: lotSearchText)<br>                }<br>            case CarParkDisplayType.list:<br>                let list = carParks.filter{$0.lotType == .Motorcycle}<br>                if lotSearchText.isEmpty {<br>                    filteredCarParks = list<br>                }<br>                else {<br>                    filteredCarParks = searchCarParks(carParks: list, searchText: lotSearchText)<br>                }<br>            }<br>        case CarParkLotType.HeavyVehicle:<br>            switch lotDisplay {<br>            case CarParkDisplayType.nearby:<br>                let heavyVehicles = carParks.filter{$0.lotType == .HeavyVehicle}<br>                let nearby = nearestCarParks(carParks: heavyVehicles)<br>                if lotSearchText.isEmpty {<br>                    filteredNearbyCarParks = nearby<br>                }<br>                else {<br>                    filteredNearbyCarParks = searchNearbyCarParks(carParks: nearby, searchText: lotSearchText)<br>                }<br>            case CarParkDisplayType.list:<br>                let list = carParks.filter{$0.lotType == .HeavyVehicle}<br>                if lotSearchText.isEmpty {<br>                    filteredCarParks = list<br>                }<br>                else {<br>                    filteredCarParks = searchCarParks(carParks: list, searchText: lotSearchText)<br>                }<br>            }<br>        }<br>        await setupCarParkAnnotationItems()<br>        <br>    }</pre><p>It calls the setup carpark UI function first.</p><p>Depending on lotType, lotDisplay, lotSearchText; it filters the carparks accordingly to update filtered or filtered nearby carparks.</p><p>Lastly, setupCarParkAnnotationItems()</p><p><strong>Network and Realm</strong></p><p>Updates response data from network client to local realm database.</p><pre>extension CarParkOperations {<br>    <br>    func updateDataMallCarparks() async {<br>        await deleteDataMallCarparks()<br>        await fetchDataMallCarparks()<br>    }<br>    <br>    @MainActor<br>    private func deleteDataMallCarparks() async {<br>        do {<br>            let realm = try await Realm()<br>            try realm.write {<br>                let carparks = realm.objects(PublicCarparkAvaliabilityData.self)<br>                for item in carparks {<br>                    realm.delete(item)<br>                }<br>            }<br>        }<br>        catch {<br>            print(&quot;Unable to open realm: \(error)&quot;)<br>        }<br>    }<br>    <br>    func fetchDataMallCarparks() async {<br>        <br>        do {<br>            var nextIndex:Int<br>            nextIndex = try await fetchDataMallCarparks(indexToSkip: index)<br>            debugPrint(&quot;car park index is %d&quot;, nextIndex)<br>            while (nextIndex % batchSize == 0) {<br>                nextIndex = try await fetchDataMallCarparks(indexToSkip: nextIndex)<br>                debugPrint(&quot;car park index is %d&quot;, nextIndex)<br>            }<br>        }<br>        catch {<br>            print(&quot;Unable to open realm: \(error)&quot;)<br>        }<br>    }<br>}</pre><p><strong>Map Annotations</strong></p><p>Setup the car park annotation to show different glyph image depending on the lot type. Including map clustering for the annotation.</p><pre>extension CarParkOperations {<br>    <br>    @MainActor<br>    internal func setupCarParkAnnotationItems() async {<br>       <br>        var annotationItems = [CarParkAnnotation]()<br>        <br>        for item in carParks {<br>            if item.lotType == lotType {<br>                let annotationItem = CarParkAnnotation()<br>                annotationItem.title = item.carparkID<br>                annotationItem.subtitle = item.carparkID<br>                annotationItem.name = item.carparkID<br>                annotationItem.lotType = item.lotType<br>                annotationItem.coordinate = CLLocationCoordinate2D(latitude: item.latitude, longitude: item.longitude)<br>                annotationItems.append(annotationItem)<br>            }<br>        }<br>        carParkAnnotations = annotationItems<br>        regionStatus = .Annotation<br>    }<br>}</pre><p>Summary<br>I had great fun is coding this feature and learnt more about modern Apple frameworks.</p><p>Do like your feedback and comments.</p><p><a href="https://www.linkedin.com/feed/hashtag/?keywords=swift&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#swift</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=swiftui&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#swiftui</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=combine&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#combine</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=swiftconcurrency&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#swiftconcurrency</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=mvvm&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#mvvm</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=lta&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#lta</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=mapkit&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#mapkit</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=carpark&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#carpark</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=car&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#car</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=motorcycle&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#motorcycle</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=heavyvehicle&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#heavyvehicle</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=location&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#location</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=annotation&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#annotation</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=map&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#map</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=list&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7096668176159031296">#list</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd018806e9cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[App database updates with Swift Concurrency]]></title>
            <link>https://medium.com/@richardyip/app-database-updates-with-swift-concurrency-693978ebde6b?source=rss-b6fd7af81dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/693978ebde6b</guid>
            <dc:creator><![CDATA[Richard Yip]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 03:17:02 GMT</pubDate>
            <atom:updated>2023-07-24T03:52:50.155Z</atom:updated>
            <content:encoded><![CDATA[<p>For this post, I will be talking about using Swift Concurrency to update mobile data base for my app, where2.</p><p><strong>Data layers</strong></p><p>Basically, I have defined 3 types of data for the app.</p><p>First is codable structs for network response data.</p><p>Next is for persistance data which in my case Realm objects.</p><p>Last are struct data which is Identifiable for services and SwiftUI.</p><p>This make it simple for further modularisation if need. Currently, I have create separate modules for networking.</p><p><strong>Update workflow for services and UI</strong></p><p>This is basic workflow for data.</p><p>Delete local data from database.</p><p>Fetch data from network API.</p><p>Update response data to database.</p><p>Filter and combine objects from database for services and SwiftUI.</p><p>Would be nice if these workflows work in sequence. However, networking is often asyncronous, meaning no idea when data fetch is completed. Need ways to lock and unlock database while updating and usually need to be performed at main thread. Services and UI code run on main thread too. Hence, would be very bad experience when user has to wait for minutes for all updates to be done.</p><p>With Swift Concurrency features like await, async, task and actor, I am able to code simple functions and run them asynchronously and thread safe while preserving UI quick response.</p><p><strong>Network response data</strong></p><blockquote>public func fetchPagedBusStops(pageIndex: Int) async throws -&gt; BusStopResponse? {</blockquote><blockquote>var components = URLComponents()</blockquote><blockquote>components.scheme = “http”</blockquote><blockquote>components.host = “datamall2.mytransport.sg”</blockquote><blockquote>components.path = “/ltaodataservice/BusStops”</blockquote><blockquote>components.queryItems = [</blockquote><blockquote>URLQueryItem(name: “$skip”, value: String(format: “%d”, pageIndex))</blockquote><blockquote>]</blockquote><blockquote>let url = components.url</blockquote><blockquote>debugPrint(url as Any)</blockquote><blockquote>var request = URLRequest(url: url!)</blockquote><blockquote>request.httpMethod = “GET”</blockquote><blockquote>request.setValue(“application/json”, forHTTPHeaderField:”Content-Type”)</blockquote><blockquote>request.setValue(“”, forHTTPHeaderField:”AccountKey”)</blockquote><blockquote>request.timeoutInterval = 60.0</blockquote><blockquote>debugPrint(request)</blockquote><blockquote>let (data, _) = try await URLSession.shared.data(for: request)</blockquote><blockquote>let result = try? JSONDecoder().decode(BusStopResponse.self, from: data)</blockquote><blockquote>return result</blockquote><blockquote>}</blockquote><p>I am using public API from Land Transport Authority to access bus stop data.</p><p>The API does not support paging and relies on skip index to download a range of data which makes it a pain in the arse to use!</p><p>Beside this parameter, notice the function is marked with async throws and BusStopResponse which is the data received from this API.</p><p>async always works together with await.</p><blockquote>Apple introduces a new concurrency feature i.e., asynchronous (async) from Swift 5.5. Async:- stands for asynchronous, which means to execute the methods/program asynchronously. Await:- is the keyword to be used for calling async methods. Await is awaiting the result.</blockquote><p><strong>Client service code for network response</strong></p><blockquote>private func fetchBusStops(indexToSkip: Int) async throws -&gt; Int {</blockquote><blockquote>var nextIndex = -1</blockquote><blockquote>let busRealm = BusRealm()</blockquote><blockquote>let client = DataMallBusClientAPI()</blockquote><blockquote>let busStopResponse = try await client.fetchPagedBusStops(pageIndex: indexToSkip)</blockquote><blockquote>if let busStops = busStopResponse?.busStops {</blockquote><blockquote>nextIndex = await busRealm.updateBusStops(currentIndex: indexToSkip, busStops: busStops)</blockquote><blockquote>return nextIndex</blockquote><blockquote>}</blockquote><blockquote>else {</blockquote><blockquote>return nextIndex</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><p>fetchBusStops needs to know what index to skip which is later used by fetchPagedBusStops for fetching the response from network code.</p><p>Do note the function fetchBusStops is also marked async as asynchronous code.</p><p>DataMallBusClientAPI is the network class for the function fetchPagedBusStops.</p><blockquote>actor BusRealm {</blockquote><blockquote>@MainActor</blockquote><blockquote>func updateBusStops(currentIndex: Int, busStops: [BusStop]) async -&gt; Int {</blockquote><blockquote>var nextIndex = 0</blockquote><blockquote>do {</blockquote><blockquote>let realm = try await Realm()</blockquote><blockquote>try realm.write {</blockquote><blockquote>for busStop in busStops {</blockquote><blockquote>let busStopData = BusStopData(busStop: busStop)</blockquote><blockquote>realm.add(busStopData)</blockquote><blockquote>}</blockquote><blockquote>nextIndex = currentIndex + busStops.count</blockquote><blockquote>return nextIndex</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><blockquote>catch {</blockquote><blockquote>print(“Error”, error)</blockquote><blockquote>}</blockquote><blockquote>return nextIndex</blockquote><blockquote>}<br>}</blockquote><p>After getting a response and list of bus stops, I call on the function updateBusStops from the actor BusRealm.</p><p>This function allows me to write the list of bus stops to the Realm database. Notice this is a actor not class keyword.</p><p>Main difference is to prevent race condtions and isolate access from multiple threads without syncrhonisation. Look at this essential blog about actors in Swift from <a href="https://www.avanderlee.com/swift/actors/">Antoine Van Der Lee</a> about this.</p><p>The function is marked with @MainActor so that the function continues to run in the main thread which Realm requires; unless you are bothered with running Realm instances in different configurations.</p><blockquote>You cannot share realm instances across threads. To use the same Realm file across threads, open a different realm instance on each thread. As long as you use the same configuration, all Realm instances will map to the same file on disk.</blockquote><p>The function updateBusStops returns the accumulated index for the next network API call fetchPagedBusStops(pageIndex: Int)</p><blockquote>private func fetchBusStops() async {</blockquote><blockquote>do {</blockquote><blockquote>var nextIndex = 0</blockquote><blockquote>nextIndex = try await fetchBusStops(indexToSkip: index)</blockquote><blockquote>debugPrint(“bus stop index is %d”, nextIndex)</blockquote><blockquote>while (nextIndex % batchSize == 0) {</blockquote><blockquote>nextIndex = try await fetchBusStops(indexToSkip: nextIndex)</blockquote><blockquote>debugPrint(“bus stop index is %d”, nextIndex)</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><blockquote>catch {</blockquote><blockquote>print(“Error”, error)</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><p>Since this LTA API does not support paging, I can only work with index to skip and batch size.</p><p>Starting with initial index 0 and keep request network data in the while loop to check number of response is equal to batch size.</p><blockquote>@MainActor</blockquote><blockquote>private func deleteBusStops() async {</blockquote><blockquote>do {</blockquote><blockquote>let realm = try await Realm()</blockquote><blockquote>try realm.write {</blockquote><blockquote>let allBusStops = realm.objects(BusStopData.self)</blockquote><blockquote>for busStop in allBusStops {</blockquote><blockquote>realm.delete(busStop)</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><blockquote>catch {</blockquote><blockquote>print(“Error”, error)</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><p>This is the client code to delete existing bus stops from the Realm database.</p><p>And finally, this is the public method call by the client service to delete and update bus stops.</p><blockquote>public func updateBusStops() async {</blockquote><blockquote>await deleteBusStops()</blockquote><blockquote>await fetchBusStops()</blockquote><blockquote>}</blockquote><p>Hope you gain some new insights about Swift Concurrency on network, database and client services.</p><p>Do welcome for comments and feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=693978ebde6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create private modules for your app using Swift Package Manager]]></title>
            <link>https://medium.com/@richardyip/create-private-modules-for-your-app-using-swift-package-manager-cc5e066acb36?source=rss-b6fd7af81dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc5e066acb36</guid>
            <category><![CDATA[spm]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[cocoapods]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Richard Yip]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 02:28:58 GMT</pubDate>
            <atom:updated>2023-03-22T21:46:24.205Z</atom:updated>
            <content:encoded><![CDATA[<p>Create private modules for your app using Swift Package Manager</p><p>CocoaPods vs Swift Package Manager? Which code dependency manager I prefer now?</p><p>Been using CocoaPods long time. But recently getting tired and fedup with resources needed and security hoops got to jump to make it work.</p><p>Been on a banking project once, with no admin privileges on the MacBook Pro and need to setup gem, ruby and cocoapods. Like have to beg bank IT admins to help me setup cocoapods. Wasted 3 days of my life and totally embrassing.</p><p>Cocoapods is designed not to be efficient.</p><blockquote>You will have to wait a long time the first time you install your dependencies, even if it’s just one, as CocoaPods will have to download the main Specs repository on your Mac. This will also happen on every pod update command when you want to update your dependencies.</blockquote><blockquote>Your main project will be modified to be able to use all of your dependencies. It’s also true that you can remove the CocoaPods integration by using the command pod deintegrate.</blockquote><blockquote>Every time you build your project, all your dependencies will also be built, which leads to slower build times.</blockquote><p><a href="https://www.codementor.io/blog/swift-package-manager-5f85eqvygj">https://www.codementor.io/blog/swift-package-manager-5f85eqvygj</a></p><p>Also discovered it is quite hard to sort out the dependencies of private repositories and CI for builds using cocoapods. Guess it is just too many moving parts, i.e. 30 plus private dependent repositories to make it work all the time for app deployment.</p><p>For SPM, you can either add public or private repositories / frameworks directly into xCode as described by Apple Documentation on SPM</p><p><a href="https://developer.apple.com/documentation/xcode/creating-a-standalone-swift-package-with-xcode">Creating a standalone Swift package with Xcode | Apple Developer Documentation</a></p><p>Although you can add packages locally in reference to your app, I much prefer to seperate them into seperate repositries. I kept both the package and main app as separate private repositories within GitHub.</p><p>Example network code within the Sources folder of the package.</p><pre>public class DataMallBusClientAPI {<br>    <br>    func fetchPagedBusStops(pageIndex: Int) async throws -&gt; BusStopResponse? {<br>    <br>        var components = URLComponents()<br>        components.scheme = &quot;http&quot;<br>        components.host = &quot;datamall2.mytransport.sg&quot;<br>        components.path = &quot;/ltaodataservice/BusStops&quot;<br>        components.queryItems = [<br>            URLQueryItem(name: &quot;skip&quot;, value: String(format: &quot;$%d&quot;, pageIndex))<br>        ]<br><br>        let url = components.url<br>        <br>        var request = URLRequest(url: url!)<br>        request.httpMethod = &quot;GET&quot;<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField:&quot;Content-Type&quot;)<br>        request.setValue(&quot;&quot;, forHTTPHeaderField:&quot;AccountKey&quot;)<br>        request.timeoutInterval = 60.0<br><br>        let (data, _) = try await URLSession.shared.data(for: request)<br>        let result = try? JSONDecoder().decode(BusStopResponse.self, from: data)<br>        return result<br>    }<br>    <br>    func fetchPagedBusServices(pageIndex: Int) async throws -&gt; BusServiceResponse? {<br>    <br>        var components = URLComponents()<br>        components.scheme = &quot;http&quot;<br>        components.host = &quot;datamall2.mytransport.sg&quot;<br>        components.path = &quot;/ltaodataservice/BusServices&quot;<br>        components.queryItems = [<br>            URLQueryItem(name: &quot;skip&quot;, value: String(format: &quot;$%d&quot;, pageIndex))<br>        ]<br><br>        let url = components.url<br>        <br>        var request = URLRequest(url: url!)<br>        request.httpMethod = &quot;GET&quot;<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField:&quot;Content-Type&quot;)<br>        request.setValue(&quot;&quot;, forHTTPHeaderField:&quot;AccountKey&quot;)<br>        request.timeoutInterval = 60.0<br><br>        debugPrint(request)<br>        let (data, _) = try await URLSession.shared.data(for: request)<br>        let result = try? JSONDecoder().decode(BusServiceResponse.self, from: data)<br>        return result<br>    }<br><br>    func fetchPagedBusRoutes(pageIndex: Int) async throws -&gt; BusRouteResponse? {<br>    <br>        var components = URLComponents()<br>        components.scheme = &quot;http&quot;<br>        components.host = &quot;datamall2.mytransport.sg&quot;<br>        components.path = &quot;/ltaodataservice/BusRoutes&quot;<br>        components.queryItems = [<br>            URLQueryItem(name: &quot;skip&quot;, value: String(format: &quot;$%d&quot;, pageIndex))<br>        ]<br><br>        let url = components.url<br>        <br>        var request = URLRequest(url: url!)<br>        request.httpMethod = &quot;GET&quot;<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField:&quot;Content-Type&quot;)<br>        request.setValue(&quot;&quot;, forHTTPHeaderField:&quot;AccountKey&quot;)<br>        request.timeoutInterval = 60.0<br><br>        let (data, _) = try await URLSession.shared.data(for: request)<br>        let result = try? JSONDecoder().decode(BusRouteResponse.self, from: data)<br>        return result<br>    }<br>    <br>    func fetchBusArrivals(busStopCode: String) async throws -&gt; BusArrivalAtStopResponse? {<br>    <br>        var components = URLComponents()<br>        components.scheme = &quot;http&quot;<br>        components.host = &quot;datamall2.mytransport.sg&quot;<br>        components.path = &quot;/ltaodataservice/BusArrivalv2&quot;<br>        components.queryItems = [<br>            URLQueryItem(name: &quot;BusStopCode&quot;, value: busStopCode)<br>        ]<br><br>        let url = components.url<br><br>        var request = URLRequest(url: url!)<br>        request.httpMethod = &quot;GET&quot;<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField:&quot;Content-Type&quot;)<br>        request.setValue(&quot;&quot;, forHTTPHeaderField:&quot;AccountKey&quot;)<br>        request.timeoutInterval = 60.0<br><br>        let (data, _) = try await URLSession.shared.data(for: request)<br>        let result = try? JSONDecoder().decode(BusArrivalAtStopResponse.self, from: data)<br>        return result<br>    }<br>    <br>}</pre><p>Example network test code within the Tests folder of the package.</p><pre>final class where2BusTests: XCTestCase {<br>    <br>    let client = DataMallBusClientAPI()<br>    <br>    func testFetchBuses() async throws {<br>        let result = try await client.fetchPagedBusStops(pageIndex: 1000)<br>        XCTAssertNotNil(result != nil, &quot;fetch bus nil&quot;)<br>        debugPrint(result as Any)<br>    }<br>    <br>    func testFetchBusServices() async throws {<br>        let result = try await client.fetchPagedBusServices(pageIndex: 0)<br>        XCTAssertNotNil(result != nil, &quot;fetch bus services nil&quot;)<br>        debugPrint(result as Any)<br>    }<br>    <br>    func testFetchBusRoutes() async throws {<br>        let result = try await client.fetchPagedBusRoutes(pageIndex: 0)<br>        XCTAssertNotNil(result != nil, &quot;fetch bus routes nil&quot;)<br>        debugPrint(result as Any)<br>    }<br>    <br>    func testFetchBusArrivals() async throws {<br>        let result = try await client.fetchBusArrivals(busStopCode: &quot;14389&quot;)<br>        XCTAssertNotNil(result == nil, &quot;fetch bus arrivals at stop nil&quot;)<br>        debugPrint(result as Any)<br>    }<br>}</pre><p>This makes it quite easy to code and test within the package.</p><p>After creating the package with source and test codes, I created the git repository and uploaded to Github as a private.</p><p>SPM allows developers to add packages into their app using the following format for either public or private respository.</p><p><a href="https://github.com/user/packageRepository">https://github.com/user/packageRepository</a></p><p>When you declared the package as public repository, just follow the default flow as what Apple document shows.</p><p><a href="https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app">Adding package dependencies to your app | Apple Developer Documentation</a></p><p>However, if the package is declared as private, you need to restrict access to the package to certain developers. One way is to use Personal Access Tokens to share the private package repository to their projects.</p><p>Here’s the document from Github on creating Personal Access Tokens.</p><p>https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token</p><h3>Summary</h3><p>And the winner is SPM for me.</p><p>No need admin privileges to setup like CocoaPods for gem, ruby or brew.</p><p>Fast, dependencies are not rebuild every time you build the project.</p><p>You can define which branch, main or dev, versions for Apple platforms.</p><p>Just share Personal Access Tokens to enable selected developers to access the github packages.</p><p>Hope you like the post and sample codes. Do love your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc5e066acb36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Importing CSV. The old way and now using Apple native frameworks, tabular data]]></title>
            <link>https://medium.com/@richardyip/importing-csv-the-old-way-and-now-using-apple-native-frameworks-tabular-data-374b82c8386b?source=rss-b6fd7af81dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/374b82c8386b</guid>
            <category><![CDATA[tabular-data]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[csv]]></category>
            <dc:creator><![CDATA[Richard Yip]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 01:11:45 GMT</pubDate>
            <atom:updated>2023-03-24T08:44:27.968Z</atom:updated>
            <content:encoded><![CDATA[<p>For the app that I created, they are cases whereby I don’t need data via Rest api. Meaning, some of them doesn’t need to be updated often and required web hosting and storage like cloud. Trying to save some bucks without online storage.</p><p>One way is to create simple MSExcel or Apple Numbers for the data. Once updated, can be easily exported as CSV into Xcode project</p><h3>The old way</h3><p>Either you build your own CSV parser or use some third party library. For me, it was CSVImport which works quite nicely. I also use SwiftyJSON for converting strings to basic primitive types. Can do without Cocoapods too. Also, very handy for networking.</p><p>I have been using Realm to store the imported data. Realm provides great way to query and filter data.</p><p>Example code to import bus fares using CSVImport</p><pre>struct BusTrainFare {<br>    var startDistance:NSDecimalNumber!<br>    var endDistance:NSDecimalNumber!<br>    var cardBusAdult:NSDecimalNumber!<br>    var cashBusAdult:NSDecimalNumber!<br>    var cardBusChild:NSDecimalNumber!<br>    var cashBusChild:NSDecimalNumber!<br>    var cardBusWorkfare:NSDecimalNumber!<br>    var cashBusWorkfare:NSDecimalNumber!<br>    var cardBusSeniorCitizen:NSDecimalNumber!<br>    var cashBusSeniorCitizen:NSDecimalNumber!<br>    var cardTrainBefore745Adult:NSDecimalNumber!<br>    var cardTrainOtherTimeAdult:NSDecimalNumber!<br>    var cashTrainAdult:NSDecimalNumber!<br>    var cardTrainBefore745Child:NSDecimalNumber!<br>    var cardTrainOtherTimeChild:NSDecimalNumber!<br>    var cashTrainChild:NSDecimalNumber!<br>    var cardTrainBefore745Workfare:NSDecimalNumber!<br>    var cardTrainOtherTimeWorkfare:NSDecimalNumber!<br>    var cashTrainWorkfare:NSDecimalNumber!<br>    var cardTrainBefore745SeniorCitizen:NSDecimalNumber!<br>    var cardTrainOtherTimeSeniorCitizen:NSDecimalNumber!<br>    var cashTrainSeniorCitizen:NSDecimalNumber!<br>    var sentosaExpress:NSDecimalNumber!<br>}<br><br>func getFaresByLine (_ completionHandler: @escaping (Bool) -&gt; ()) {<br>        <br>        let path = Bundle.main.path(forResource: &quot;BusAndTrainFares&quot;, ofType: &quot;.csv&quot;)<br>        let importer = CSVImporter&lt;BusTrainFare&gt;(path: path!)<br>        <br>        importer.startImportingRecords{ recordValues -&gt; BusTrainFare in<br>            <br>            let startDistance = NSDecimalNumber.init(string: recordValues[0])<br>            let endDistance = NSDecimalNumber.init(string: recordValues[1])<br>            let cardBusAdult = NSDecimalNumber.init(string: recordValues[2])<br>            let cashBusAdult = NSDecimalNumber.init(string: recordValues[3])<br>            let cardBusChild = NSDecimalNumber.init(string: recordValues[4])<br>            let cashBusChild = NSDecimalNumber.init(string: recordValues[5])<br>            let cardBusWorkfare = NSDecimalNumber.init(string: recordValues[6])<br>            let cashBusWorkfare = NSDecimalNumber.init(string: recordValues[7])<br>            let cardBusSeniorCitizen = NSDecimalNumber.init(string: recordValues[8])<br>            let cashBusSeniorCitizen = NSDecimalNumber.init(string: recordValues[9])<br>            let cardTrainBefore745Adult = NSDecimalNumber.init(string: recordValues[10])<br>            let cardTrainOtherTimeAdult = NSDecimalNumber.init(string: recordValues[11])<br>            let cashTrainAdult = NSDecimalNumber.init(string: recordValues[12])<br>            let cardTrainBefore745Child = NSDecimalNumber.init(string: recordValues[13])<br>            let cardTrainOtherTimeChild = NSDecimalNumber.init(string: recordValues[14])<br>            let cashTrainChild = NSDecimalNumber.init(string: recordValues[15])<br>            let cardTrainBefore745Workfare = NSDecimalNumber.init(string: recordValues[16])<br>            let cardTrainOtherTimeWorkfare = NSDecimalNumber.init(string: recordValues[17])<br>            let cashTrainWorkfare = NSDecimalNumber.init(string: recordValues[18])<br>            let cardTrainBefore745SeniorCitizen = NSDecimalNumber.init(string: recordValues[19])<br>            let cardTrainOtherTimeSeniorCitizen = NSDecimalNumber.init(string: recordValues[20])<br>            let cashTrainSeniorCitizen = NSDecimalNumber.init(string: recordValues[21])<br>            let sentosaExpress = NSDecimalNumber.init(string: recordValues[22])<br>            <br>            return BusTrainFare.init(startDistance: startDistance,<br>                                     endDistance: endDistance,<br>                                     cardBusAdult: cardBusAdult,<br>                                     cashBusAdult: cashBusAdult,<br>                                     cardBusChild: cardBusChild,<br>                                     cashBusChild: cashBusChild,<br>                                     cardBusWorkfare: cardBusWorkfare,<br>                                     cashBusWorkfare: cashBusWorkfare,<br>                                     cardBusSeniorCitizen: cardBusSeniorCitizen,<br>                                     cashBusSeniorCitizen: cashBusSeniorCitizen,<br>                                     cardTrainBefore745Adult: cardTrainBefore745Adult,<br>                                     cardTrainOtherTimeAdult: cardTrainOtherTimeAdult,<br>                                     cashTrainAdult: cashTrainAdult,<br>                                     cardTrainBefore745Child: cardTrainBefore745Child,<br>                                     cardTrainOtherTimeChild: cardTrainOtherTimeChild,<br>                                     cashTrainChild: cashTrainChild,<br>                                     cardTrainBefore745Workfare: cardTrainBefore745Workfare,<br>                                     cardTrainOtherTimeWorkfare: cardTrainOtherTimeWorkfare,<br>                                     cashTrainWorkfare: cashTrainWorkfare,<br>                                     cardTrainBefore745SeniorCitizen: cardTrainBefore745SeniorCitizen,<br>                                     cardTrainOtherTimeSeniorCitizen: cardTrainOtherTimeSeniorCitizen,<br>                                     cashTrainSeniorCitizen: cashTrainSeniorCitizen,<br>                                     sentosaExpress: sentosaExpress)<br>            <br>            }.onFinish { importedRecords in<br>            <br>                self.listOtherFares.removeAll()<br>                for record in importedRecords {<br>                    self.listOtherFares.append(record)<br>                }<br>        }<br>    }<br>}</pre><p>I have use and tested third party framework like CSVImport via Cocoapods.</p><h3>The new and native way</h3><p>Recently found out by using Apple Tabular data, I can actually import CSV data without any third party frameworks. Basically, it treats CSV as rows and columns which is exactly what I needed. Plus point, you can build ML models from CSV files. BTW, it also works with JSON.</p><pre>class BusAndTrainFares :Object {<br>    @Persisted var startDistance: Double = 0.0<br>    @Persisted var endDistance: Double = 0.0<br>    @Persisted var cardBusAdult:Int = 0<br>    @Persisted var cashBusAdult:Int = 0<br>    @Persisted var cardBusChild:Int = 0<br>    @Persisted var cashBusChild:Int = 0<br>    @Persisted var cardBusWorkfare:Int = 0<br>    @Persisted var cashBusWorkfare:Int = 0<br>    @Persisted var cardBusSeniorCitizen:Int = 0<br>    @Persisted var cashBusSeniorCitizen:Int = 0<br>    @Persisted var cardTrainBefore745Adult:Int = 0<br>    @Persisted var cardTrainOtherTimeAdult:Int = 0<br>    @Persisted var cashTrainAdult:Int = 0<br>    @Persisted var cardTrainBefore745Child:Int = 0<br>    @Persisted var cardTrainOtherTimeChild:Int = 0<br>    @Persisted var cashTrainChild:Int = 0<br>    @Persisted var cardTrainBefore745Workfare:Int = 0<br>    @Persisted var cardTrainOtherTimeWorkfare:Int = 0<br>    @Persisted var cashTrainWorkfare:Int = 0<br>    @Persisted var cardTrainBefore745SeniorCitizen:Int = 0<br>    @Persisted var cardTrainOtherTimeSeniorCitizen:Int = 0<br>    @Persisted var cashTrainSeniorCitizen:Int = 0<br>    @Persisted var sentosaExpress:Int = 0<br>}<br><br><br>class BusAndTrainFaresOperations: NSObject {<br>    <br>    func importFaresCSV() {<br>    <br>        let columnNames = [&quot;startDistance&quot;,&quot;endDistance&quot;,&quot;cardBusAdult&quot;,&quot;cashBusAdult&quot;,&quot;cardBusChild&quot;,&quot;cashBusChild&quot;, &quot;cardBusWorkfare&quot;, &quot;cashBusWorkfare&quot;, &quot;cardBusSeniorCitizen&quot;, &quot;cashBusSeniorCitizen&quot;, &quot;cardTrainBefore745Adult&quot;, &quot;cardTrainOtherTimeAdult&quot;, &quot;cashTrainAdult&quot;, &quot;cardTrainBefore745Child&quot;, &quot;cardTrainOtherTimeChild&quot;,  &quot;cashTrainChild&quot;, &quot;cardTrainBefore745Workfare&quot;, &quot;cardTrainOtherTimeWorkfare&quot;, &quot;cashTrainWorkfare&quot;, &quot;cardTrainBefore745SeniorCitizen&quot;, &quot;cardTrainOtherTimeSeniorCitizen&quot;, &quot;cashTrainSeniorCitizen&quot;, &quot;sentosaExpress&quot;]<br>        let columnTypes: [String : CSVType] = [&quot;startDistance&quot;: .double, &quot;endDistance&quot;: .double, &quot;cardBusAdult&quot;: .integer, &quot;cardBusChild&quot;: .integer, &quot;cardBusWorkfare&quot;: .integer, &quot;cashBusWorkfare&quot;: .integer, &quot;cardBusSeniorCitizen&quot;: .integer, &quot;cashBusSeniorCitizen&quot;: .integer, &quot;cardTrainBefore745Adult&quot;: .integer, &quot;cardTrainOtherTimeAdult&quot;: .integer, &quot;cashTrainAdult&quot;: .integer, &quot;cardTrainBefore745Child&quot;: .integer, &quot;cardTrainOtherTimeChild&quot;: .integer, &quot;cashTrainChild&quot;: .integer, &quot;cardTrainBefore745Workfare&quot;: .integer, &quot;cardTrainOtherTimeWorkfare&quot;:.integer, &quot;cashTrainWorkfare&quot;:.integer, &quot;cardTrainBefore745SeniorCitizen&quot;:.integer, &quot;cardTrainOtherTimeSeniorCitizen&quot;: .integer, &quot;cashTrainSeniorCitizen&quot;: .integer, &quot;sentosaExpress&quot;: .integer]<br>        <br>        let options = CSVReadingOptions(hasHeaderRow: true, delimiter: &quot;,&quot;)<br>        guard let fileUrl = Bundle.main.url(/service/forresource: &quot;BusAndTrainFares&quot;, withExtension: &quot;csv&quot;) else { return }<br><br>        let dataFrame2 = try! DataFrame(contentsOfCSVFile: fileUrl,<br>                                        columns: columnNames,<br>                                        types: columnTypes,<br>                                        options: options)<br>        <br>        do {<br>            let realm = try Realm()<br>            try realm.write {<br>                let fares = realm.objects(BusAndTrainFares.self)<br>                for item in fares {<br>                    realm.delete(item)<br>                }<br>            }<br>        }<br>        catch {<br>            print(&quot;Error&quot;, error)<br>        }<br>                <br>        for row in dataFrame2.rows {<br>            let fares = BusAndTrainFares()<br>            if let startDistance = row[0] as? Double {<br>                fares.startDistance = startDistance<br>            }<br>            if let endDistance = row[1] as? Double {<br>                fares.endDistance = endDistance<br>            }<br>            if let cardBusAdult = row[2] as? Int {<br>                fares.cardBusAdult = cardBusAdult<br>            }<br>            if let cashBusAdult = row[3] as? Int {<br>                fares.cashBusAdult = cashBusAdult<br>            }<br>            if let cardBusChild = row[4] as? Int {<br>                fares.cardBusChild = cardBusChild<br>            }<br>            if let cashBusChild = row[5] as? Int {<br>                fares.cashBusChild = cashBusChild<br>            }<br>            if let cardBusWorkfare = row[6] as? Int {<br>                fares.cardBusWorkfare = cardBusWorkfare<br>            }<br>            if let cashBusWorkfare = row[7] as? Int {<br>                fares.cashBusWorkfare = cashBusWorkfare<br>            }<br>            if let cardBusSeniorCitizen = row[8] as? Int {<br>                fares.cardBusSeniorCitizen = cardBusSeniorCitizen<br>            }<br>            if let cashBusSeniorCitizen = row[9] as? Int {<br>                fares.cashBusSeniorCitizen = cashBusSeniorCitizen<br>            }<br>            if let cardTrainBefore745Adult = row[10] as? Int {<br>                fares.cardTrainBefore745Adult = cardTrainBefore745Adult<br>            }<br>            if let cardTrainOtherTimeAdult = row[11] as? Int {<br>                fares.cardTrainOtherTimeAdult = cardTrainOtherTimeAdult<br>            }<br>            if let cashTrainAdult = row[12] as? Int {<br>                fares.cashTrainAdult = cashTrainAdult<br>            }<br>            if let cardTrainBefore745Child = row[13] as? Int {<br>                fares.cardTrainBefore745Child = cardTrainBefore745Child<br>            }<br>            if let cardTrainOtherTimeChild = row[14] as? Int {<br>                fares.cardTrainOtherTimeChild = cardTrainOtherTimeChild<br>            }<br>            if let cashTrainChild = row[15] as? Int {<br>                fares.cashTrainChild = cashTrainChild<br>            }<br>            if let cardTrainBefore745Workfare = row[16] as? Int {<br>                fares.cardTrainBefore745Workfare = cardTrainBefore745Workfare<br>            }<br>            if let cardTrainOtherTimeWorkfare = row[17] as? Int {<br>                fares.cardTrainOtherTimeWorkfare = cardTrainOtherTimeWorkfare<br>            }<br>            if let cashTrainWorkfare = row[18] as? Int {<br>                fares.cashTrainWorkfare = cashTrainWorkfare<br>            }<br>            if let cardTrainBefore745SeniorCitizen = row[19] as? Int {<br>                fares.cardTrainBefore745SeniorCitizen = cardTrainBefore745SeniorCitizen<br>            }<br>            if let cardTrainOtherTimeSeniorCitizen = row[20] as? Int {<br>                fares.cardTrainOtherTimeSeniorCitizen = cardTrainOtherTimeSeniorCitizen<br>            }<br>            if let cashTrainSeniorCitizen = row[21] as? Int {<br>                fares.cashTrainSeniorCitizen = cashTrainSeniorCitizen<br>            }<br>            if let sentosaExpress = row[22] as? Int {<br>                fares.sentosaExpress = sentosaExpress<br>            }<br>            <br>            do {<br>                let realm = try Realm()<br>                try realm.write({<br>                    realm.add(fares)<br>                })<br>            }<br>            catch {<br>                print(&quot;Unable to open realm: \(error)&quot;)<br>            }<br>        }<br>    }<br>}<br></pre><p>Does the same as CVSImport. In this case setup the Realm object struct to hold data for realm. Define the column names, types, separator type and create DataFrame to load the CSV.</p><h3><strong>Summary</strong></h3><p>Remove third party frameworks when importing and parsing CSV files.</p><p>Got lots of flexibility to manipulate data through sorting rows, columns and filtering. Best part is able to create ML models based on imported CSVs. Got plans to try out ML with another dataset soon.</p><p>Minimum iOS version iOS15.0+</p><p>Hope you like the sample codes and explanation. Do like yout feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=374b82c8386b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Alamofire to Swift Concurrency for Networking]]></title>
            <link>https://medium.com/@richardyip/from-alamofire-to-swift-concurrency-for-networking-28703b950c9c?source=rss-b6fd7af81dd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/28703b950c9c</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[cocoapods]]></category>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[swift-networking]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <dc:creator><![CDATA[Richard Yip]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 00:36:43 GMT</pubDate>
            <atom:updated>2023-03-11T00:36:43.510Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Long time ago, about 5 years. Alamofire was on fire because it make networking easier for Objective C in iOS development.</strong></p><p>[AlamofireWrapper request:RequestMethodGET URLString:@”http://something.com&quot; parameters:nil encoding:RequestParameterEncodingURL headers:nil success:^(NSURLRequest * _Nullable request, NSHTTPURLResponse * _Nullable response, NSDictionary * _Nullable json) {</p><p>NSLog(@”Success”);</p><p>// Get the required information from the response JSON</p><p>} failure:^(NSURLRequest * _Nullable request, NSHTTPURLResponse * _Nullable response, NSError * _Nullable error) {</p><p>NSLog(@”Failure”);</p><p>}];</p><p>Typically, you build the request, url string, parameters, headers and depending on success or failure, you get response and json data.</p><p>However, success and failure are quite ambiguous. For a request to be truly successful, network response must be 200 and json returned must be validated for correctness.</p><p>Also, complexity arises whenever you have paging and multiple requests to complete some sensible network data for your data model. Lazy developers usually aggregate or combine network data for services and UI views. In the end, you begin have really huge Dictionaries or JSON for both network and UI views. Best to separate and have distinct data structures between network, services and views.</p><p>Multiple requests give rise to pyramid of doom codes, too many nested requests and giving multiple pathways for responses and data received. Very hard to test and debug.</p><p>Alamofire latest versions support Swift. Although much better, it still doesn’t address the above issues.</p><p>If not Alamofire, go native and use Apple network API? Why not? Don’t need another 3rd party framework. Also, can forget about using CocoaPods and try moving towards Swift Package Manager. To me, the less time and effort to setup dependency codes, the better! Complete control within xCode. Another issue is security. One time, need almost 3 days to set up Cocoapods environment for banking project. Need root privileges on the Mac which I don’t have.</p><p><a href="https://medium.com/@rashadsh/cocoapod-vs-spm-in-swift-2fe52764b31a"><strong><em>Cocoapod vs SPM in Swift</em></strong></a></p><p><a href="https://medium.com/@rashadsh/cocoapod-vs-spm-in-swift-2fe52764b31a"><em>Apple has created an official package manager called Swift Package Manager (AKA SPM or SwiftPM) that helps us manage…</em></a></p><p><a href="https://medium.com/@rashadsh/cocoapod-vs-spm-in-swift-2fe52764b31a"><em>medium.com</em></a></p><p><em>Before Swift 5.5, in order to make a network request, we must use the closure-based URLSession ‘s dataTask(with:completionHandler:) method to trigger a request that runs asynchronously in the background. Once the network request is completed, the completion handler will give us back the result from the network request.</em></p><p>Most recent network codes with Swift are still using closure based URLSession’s dataTask. Got lots of tutorials on the HOWTO. However, problems with nested requests, aka pyramid of doom codes can still occurs.</p><p>Another issue are asynchronous codes running in the background. No way to know exactly what queue or thread is it running? For single and simple network request, it’s no big deal, just make sure it’s on the main queue in the completion code. For multiple and complex requests, you are likely to switch between or use different queues for each requests which makes debugging a nightmare. Also, do consider race conditions for data received especially on the main thread.</p><blockquote>func fetchData(url: URL, completion: @escaping (Result&lt;Data, MyError&gt;) -&gt; Void) {</blockquote><blockquote>let request = URLRequest(url: url)</blockquote><blockquote>fetch(request: request) { (result: Result&lt;Data, MyError&gt;) in</blockquote><blockquote>DispatchQueue.main.async {</blockquote><blockquote>completion(response))</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><p>Response is done but how to determine error and response together makes a valid successful API call? Still need further validation for correctness.</p><p>Also lots of developers starts to make network request generic. Got lots of ideas of making complete REST API calls for GET, PUT, POST and DELETE calls. For most cases especially public apis, developers can only make GET or the most POST calls. Not sure you really need to implement all types.</p><p><em>A RESTful API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to the reading, updating, creating and deleting of operations concerning resources.</em></p><p>Do you need to all components of the REST Api generic, being able to swap and test each parameter? Sometimes, being direct is most effective!</p><p><em>What are the 3 components of a RESTful API?</em></p><p><strong><em>REST Components</em></strong></p><p><em>Resource Path (request target)</em></p><p><em>HTTP Verb.</em></p><p><em>Body.</em></p><p><em>Header.</em></p><p>Which at last comes to what I would like to use now for iOS networking code.</p><p>Recently there are two new wonderful Apple technologies for networking.</p><p>First is Swift Combine to which I first tried initially but found it quite cumbersome and hard to debug. Found Combine is more really suited for publish / subscribe model rather than request / response model that’s more suited for networking.</p><p><em>What is swift combine used for?</em></p><p><em>Overview. The Combine framework provides a declarative Swift API for </em><strong><em>processing values over time</em></strong><em>. These values can represent many kinds of asynchronous events. Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers.</em></p><p>The other technology that I much preferred now is Swift Concurrency. Best part is I can write code in sequence that can run asynchronously. Starting with async and await and later actors, I was able to solve major networking issues that exists long time for my app.</p><p>For the time being, I leave you with a link to show how modern swift concurrency works. Later, I will demonstrate some codes using async, await and actors to solve really primitive public API in later blogs.</p><p><a href="https://www.kodeco.com/books/modern-concurrency-in-swift/v1.0/chapters/2-getting-started-with-async-await">Modern Concurrency in Swift, Chapter 2: Getting Started With async/await</a></p><p><strong>Do really like to have your feedback and comments.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28703b950c9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>