Skip to main content

Posts

Showing posts with the label Intermediate

Printing Staircase Pattern : Swift coding challenge

In this post, we can try interesting pattern printing challenge in Swift. The problem statement goes like this " Print a staircase of given size 'n'. Make sure that its base and height are both equal to n, and the image is drawn only using `#` symbols and spaces. The last line is not preceded by any spaces." Expected Output : # ## ### #### ##### ###### Working solution: func makePatternOf ( _ size : Int ) { var str = "" // 1 for index in ( 0 ..< size ) { let stop = size -index-1; // 2 for _ in 0 ..< stop { str. append ( " " ) ; } // 3 for _ in 0 .. . index { str. append ( "#" ) ; } print ( str ) str = "" } } makePatternOf ( 6 ) Loop to visit every row of stair case. Loop for appe...

Codility National Coding Week Sep-2021 : String transformation solution in Swift

In this post Swift 5.0 solution given for National Coding Week Sep-2021 challenge. Given a string S of letters 'a' and/or 'b', replaces some consecutive sequence "abb" in S by "baa". Example,  S = "ababb" then  "ababb" → "abbaa" → "baaaa". Working solution :      public func solution ( _ S : inout String ) -> String {       var hasFound = true       var res = Array(S)       // 1       while hasFound && res.count > 2 {         hasFound = false         //2         for index in 0 ..<res.count- 2 {           // 3           if res[index] == "a" && res[index+ 1 ] == "b" && res[index+ 2 ] == "b" {             hasFound = true             res[index] = "b"         ...

Keeping app alive in Background State

Smart phones reinforces multitasking possible with all extends. In such cases the app enters to non-foreground (background & suspended) state from various user interactions such as pressing home button, switching apps or even when it could be simply pressing from power button (or Even it could be from System events). These events can cause a suspended app to be returned to the background, or cause a not running app to be launched directly into the background. System events can cause a suspended app to be returned to the background, or cause a not running app to be launched directly into the background. Background Execution Sequence Why I am stressing these points ?  In my recent app I introduced a new feature where I need to: Show a timer that ticks every seconds. A sound file that plays on each seconds. A local notification has to fire on completion of every timer. All the above has to be run in background state without interrupting timer progress bar...

5 Common pitfalls while starting iOS app

In this article I listed 5 most common missteps while starting iOS application. Typically beginners might have taken these approaches.  1. Internet connectivity status checking over response error : It is essential to check network connectivity status offline or online before starting services.  To test reachability you might wrote in response callback :  Problem : Time consuming in case URL takes tool long to respond. More over you cannot rely on server to check connectivity. Simply because server may be down at the moment you sent request. Solution : Use Apple’s Reachability class. It can monitor network status of WiFi or Cellular data instantly. Notifies in case network status changes. Bonus - Also make sure app works in iPv6 network as well. 2. Textfield behind keyboard :  Credit : Stackoverflow.com We start developing app in Xcode and run in Simulator. By default keyboard preference of simulator is hidden and we kept using Mac keybo...

Protocol Oriented Programming (POP) in Swift

A protocol declares a programmatic interface that any class or structs or enums may choose to implement. It act as blueprints rather than parents. POP is a new approach for programming where you decorate your classes, structs or enums using protocols. By default swift does not support multiple inheritance, therefore problem pops out when you want to add multiple abilities to your class. Protocol OP lets you to add new abilities to a class or struct or enum via protocols which can support multiple implementations. For instance a ‘Car Engine’ protocol can implemented from ‘Petrol engine’’ and  ‘Electric engine’ protocol. Syntax : What about Object Oriented Programming (OOP) ? Creating abstract (methods without implementation) classes or base classes mainly done from inheritance. Every subclasses will have the ability of their super classes (unless ‘final’ method type ). A subclass can override that ability, add specific one. OOP works perfect till y...

Quickest way to test Apple Push Notification Service APNS

We got plenty of applications powered by Apple Push notification feature and even we know how it's implemented.  At the end when it comes for testing, simulator won’t help you out. We need actual hardware device. Since Xcode 7, you can now test apps on your device without a program membership. However, to configure push notifications you need a push notification certificate for your App ID, which requires the program membership. Now assume that your server is not ready to trigger notifications. Well, it doesn't stop you testing and see the magic working ! Listed below best options for the same. From online portals : http://apns-gcm.bryantan.info/ http://pushtry.com/ http://www.pushwatch.com/ From Mac app : https://itunes.apple.com/in/app/apn-tester-free/id626590577?mt=12 https://github.com/noodlewerk/NWPusher I have used NWPusher and I will recommend the same. ;-)  So, here its recipe  Key items  [1] PEM file [2] Device toke...

Popular posts from this blog

Implementing autocompletion OTP field in iOS

Long waiting is over. !!  iOS 12 brings Autofill for OTP text field which is close to Android provided a decade back. Previously in iOS we used to toggle between OTP text screen and message inbox.  Which was hard to remember and time consuming resulting a bad user experience. Personally, I have been asked from the client/customer couple of times to implement autocompletion for OTP field and took me a lot of time to convey that it is not possible in iOS. Why Autofill was not possible previously?  We all know that Apple gives at most care for user privacy. When we see iOS architecture, each individual app is like a separate island. There is no inter-app bridge between apps (exception for Keychain and URLSchemes APIs which gives very limited scope). Thus we cannot read message content from inbox. Where to start Autofilling? First of all, the target SMS need to have the OTP Code with prefix string "Code" or "Passcode"on its message content. Beware of OTP c...

Animating label text update - choosing a better way

Recently I published a countdown app .  At one point of development - I have to show a timer on a UILabel which ticks on each seconds. As usual I started  setting text to a label object - self .timerLabel.text = someString Easy piece of cake right !?   But wait ... it won't take much user attention when timer ticks on every seconds. So I decided to make use of a simple animation while label gets text update. I found there are dozens of ways to animate a label. In this short article, I listed 3 best way you can animate text on a label. ( Spoiler Alert 👀- I decided to go with 3rd option)  1. Fade In - Fade out animation : CATransition class has got transition type `fade`. With timing function of CATransition - I was able to see the below result. let animation: CATransition = CATransition () animation.timingFunction = CAMediaTimingFunction (name: CAMediaTimingFunctionName .easeInEaseOut) animation.type = CATransitionType .fade animation.subtype = C...

Cached Async Image in SwiftUI

 SwiftUI’s AsyncImage is handy, but every time your view appears, it refetches the image—leading to flicker, delays, and unnecessary network use. What if you could fetch once, then reuse instantly? That's exactly what the Cached Async Image  delivers: a memory-powered caching layer that keeps SwiftUI image loading smooth, snappy, and resilient. First a simple in-memory cache without disk persistence. This will be thread-safe and auto-purges under memory pressure. A Singleton wrapping NSCache for URL → UIImage caching as follows : final class ImageCache {   static let shared = ImageCache()   private init() {}   private let cache = NSCache<NSURL, UIImage>()   func image(for url: URL) -> UIImage? {     cache.object(forKey: url as NSURL)   }   func insertImage(_ image: UIImage?, for url: URL) {     guard let image else { return }     cache.setObject(image, forKey: url as NSURL)   }   func clearAll() { ...

Understanding Task { }, Task.detached { }, and Task { @MainActor in … } in Swift Concurrency

Swift’s concurrency model introduced a cleaner and safer alternative to GCD. But with this came a common confusion: When should I use Task {} , Task.detached {} , and Task { @MainActor in ... } ? If you’ve ever wondered which one to pick, this article will clear it up with simple explanations and real-world guidance.

UICollectionViewCell shows with wrong size on First time - Solved

We commonly use Collection view where its cell size calculated run time. The flow layout delegate is responsible to return individual cell sizes. BUT in most of the cases, delegate method `collectionView: layout sizeForItem:` expects cell size too early. Before generating actual cell size. extension YourViewController : UICollectionViewDelegateFlowLayout { func collectionView ( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize (width: externalWidth, height: externalHeight) } } For instance, if a cell size depends on external view and its frame is not yet ready - results with wrong (or outdated) cell size. Typically happens for the first time view controller laid out all views. You can find similar queries in StackOverflow community : Collection view sizeForItemNotWorking UICollectionViewCell content wrong size on first load How to refresh UICollec...