# Random > Please scroll down ## Posts - [The Hidden Memory Leak in Your Combine Code: A Swift Developer's Guide](https://redflowerinc.com/the-hidden-memory-leak-in-your-combine-code-a-swift-developers-guide/): How forgetting [weak self] can silently kill your app’s performance Introduction Picture this: You’ve just shipped your beautifully crafted iOS app. It uses Combine for reactive programming, follows MVVM architecture, and the code looks clean. But users are complaining about crashes and sluggish performance. After hours of debugging, you discover the culprit: memory leaks caused by retain cycles in your Combine subscriptions. Today, we’ll dive deep into one of the most common yet overlooked issues in Swift development: memory leaks in Combine’s sink operator. The Innocent-Looking Code That Leaks Let’s start with a real-world example that looks perfectly reasonable: Spoiler […] - [Optimizing Number Formatting: The Power of Bitwise Operations in iOS](https://redflowerinc.com/optimizing-number-formatting-the-power-of-bitwise-operations-in-ios/): Introduction When working with number formatters in performance-sensitive applications, caching is essential. Our original key generation method was functional but inefficient. By optimizing the key computation, we significantly improved performance and memory usage. The Old Approach Previously, the key was generated using a multiplication-based formula: While this approach worked, it relied on large multiplications, making it inefficient and prone to overflow for larger values. Additionally, constructing the key as an NSString added unnecessary overhead. The Optimized Approach We improved efficiency by replacing multiplications with bitwise operations and optimizing string handling: Why This is Better 1. Bitwise Operations for Speed – Using bit […] - [Using objc files in Swift project when using cocoa pods](https://redflowerinc.com/using-objc-files-in-swift-project-when-using-cocoa-pods/): Objective-C and Swift Integration in Xcode with Bridging Headers When integrating Objective-C code in a Swift-based project, a Bridging Header is used to enable communication between the two languages. Below are the details based on the project settings and how it has been configured in the provided screenshots. Key Steps to Enable Objective-C in a Swift Project Using Pods 1. Configuring the Bridging Header • In the Build Settings, search for bridging. • Locate the Objective-C Bridging Header field under Swift Compiler – General. • Set the path to your bridging header file. For example: Project/Project-Bridging-Header.h 2. Enable Precompilation for the Bridging Header • Ensure that the Precompile […] - [Preventing Memory Leaks and Crashes with DispatchGroup and Weak Self in Swift](https://redflowerinc.com/preventing-memory-leaks-and-crashes-with-dispatchgroup-and-weak-self-in-swift/): MAIN THREAD – CRASHED closure #1 (Swift.Bool) -> () in YourProject.addPublisherHandler() -> () :0Combine0x1a551b000 + 44748Combine0x1a551b000 + 44640Combine0x1a551b000 + 79636Combine0x1a551b000 + 78876Combine0x1a551b000 + 77648Combine0x1a551b000 + 77260Redflowerclosure #3 () -> () in YourProject.fetchDetails() -> () ViewModel+Network.swift:47Redflowerreabstraction thunk helper from @escaping @callee_guaranteed () -> () to @escaping @callee_unowned @convention(block) () -> () :0libdispatch.dylib_dispatch_call_block_and_releaselibdispatch.dylib_dispatch_client_calloutlibdispatch.dylib_dispatch_main_queue_drainlibdispatch.dylib_dispatch_main_queue_callback_4CFCoreFoundationCFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUECoreFoundation__CFRunLoopRunCoreFoundationCFRunLoopRunSpecificGraphicsServicesGSEventRunModalUIKitCore-[UIApplication _run]UIKitCoreUIApplicationMainOKExmain main.m:330x0 + 0 It looks like the crash is caused by accessing self inside a DispatchGroup.notify closure after self has already been deallocated. This happens because, by default, closures capture strong references to self, which can lead to retain cycles or crashes if the object is released before […] - [Improve Swift Code Efficiency: Utilize let for Constants](https://redflowerinc.com/improve-swift-code-efficiency-utilize-let-for-constants/): Use let instead of var: When you know that a variable won’t change, declare it as a constant using let. This allows the Swift compiler to make optimizations. In Swift, the let keyword is used to declare a constant, which means the value it holds cannot be changed once it is set. This immutability allows the Swift compiler to make certain optimizations. Value Propagation: If a constant is initialized with a literal value or a simple expression, the compiler can replace uses of the constant with its initial value. This is known as constant propagation. This can eliminate unnecessary memory […] - [Swift Code Optimization: Best Practices and Performance Boost](https://redflowerinc.com/boost-swift-performance-inlining-functions-enumerated-types-and-optimal-collections/): Swift offers several techniques to optimize your code: Use let instead of var: When you know that a variable won’t change, declare it as a constant using let. This allows the Swift compiler to make optimizations. More details here Lazy Initialization: Use lazy keyword for expensive computations. The value gets computed only when it is accessed for the first time. Avoid Using High-Level Functions Unnecessarily: High-level functions like map, filter, reduce are very convenient, but they can be slower than simple for loops. Inlining Functions: Small functions can be inlined using the @inline(__always) attribute. This can potentially improve performance by […] - [Video learning series 3: Adding a fade in effect to the watermark](https://redflowerinc.com/video-learning-series-3-adding-a-fade-in-effect-to-the-watermark/): To add a fade-in effect to the watermark, you can use a CABasicAnimation on the opacity property of the watermark layer. Here’s how you can modify the addWatermark(to:watermark:) function to add a fade-in effect: In this modified function, the opacity of the watermarkLayer is initially set to 0 (completely transparent). A CABasicAnimation is created to animate the opacity from 0 to 0.5 over a duration of 5.0 seconds. The animation begins at time zero (AVCoreAnimationBeginTimeAtZero), is not removed when completed, and continues to apply its effect after its active duration (fillMode = .forwards). The animation is added to the watermarkLayer […] - [Video learning series 2: Exporting a Video with a Watermark using AVFoundation in Swift](https://redflowerinc.com/video-learning-series-2-exporting-a-video-with-a-watermark-using-avfoundation-in-swift/): In a previous post, we discussed how to add a watermark to a video using AVFoundation in Swift. Now, we will take it a step further and learn how to export the video with the watermark. https://redflowerinc.com/adding-a-watermark-to-a-video-using-avfoundation-in-swift/ Creating the Export FunctionFirst, let’s create a function that exports a video with a watermark. This function will take an input URL of a video, an output URL to save the video, and a UIImage of a watermark. Understanding the CodeThis function starts by calling the addWatermark(to:watermark:) function to create a composition of the video and the watermark. If the watermark cannot be […] - [Video learning series 1: Adding a watermark to a video using AVFoundation in Swift](https://redflowerinc.com/adding-a-watermark-to-a-video-using-avfoundation-in-swift/): In this blog post, we will learn how to add a watermark to a video using AVFoundation in Swift. AVFoundation is a powerful framework for working with audiovisual media on iOS and macOS. It provides a range of functionalities, including the ability to add watermarks to videos. Creating a Watermark FunctionFirst, let’s create a function that adds a watermark to a video. This function will take a URL of a video and a UIImage of a watermark, and return a mutable composition of the video and the watermark. Understanding the CodeThis function creates a mutable composition and a mutable track, […] - [Identifying Performance Bottlenecks in Number Formatter Creation and Usage](https://redflowerinc.com/optimizing-your-code-using-instruments/): Recently I was working on optimizing a part of the code, where we create a formatter, cache it and then use this formatter hundreds of time. This is a pretty harmless piece of code where you basically create a formatter, and then cache it. We retrieve the formatter from the cache using a key and save it in the cache. I extracted the stack trace from instruments. This is as shown below. Seems like there is something fishy going on. If you look closely at the arrow, you can see there is a regenerate method being called. Let’s dig in […] - [Handling Navigation Bar and Safe Area Insets in iOS](https://redflowerinc.com/handling-navigation-bar-and-safe-area-insets-in-ios/): In this blog post, we’ll discuss a common scenario in iOS development: adjusting the layout of your views based on the presence of a navigation bar and the safe area insets of the device. This is particularly relevant for devices with notches, like the iPhone X and later models, where the safe area insets can affect the positioning of your views. Let’s start by examining a snippet of Swift code: This code is doing a few things: Checking for a navigation bar: The if let navigationBar = self.navigationController?.navigationBar line checks if the current view controller is embedded in a navigation […] - [Setting the attributes for a navigation controller](https://redflowerinc.com/setting-the-attributes-for-a-navigation-controller/): When setting the attributes of a navigation bar, it’s common to set the attributes on the navigation bar. This was possible before iOS 13, but from this version onwards, we would need to use UINavigationBarAppearance which is an object for customizing the appearance of a navigation bar. After creating a UINavigationBarAppearance object, use the methods and properties of this class to specify the appearance you want for items in the navigation bar. Use the inherited properties from UIBarAppearance to configure the background and shadow attributes of the navigation bar itself. You can use the code snippet pasted above to customize your navigation bar. - [Understanding NSAttributedString in iOS Development](https://redflowerinc.com/understanding-nsattributedstring-in-ios-development/): When working with text in iOS development, developers often need to apply various attributes to text strings, such as font styles, paragraph styling, and writing directions. In this blog post, we’ll explore how to use NSAttributedString to apply these attributes to text and create visually appealing user interfaces. NSAttributedString and Text Attributes NSAttributedString is a powerful class in iOS development that allows developers to apply different attributes to text strings. These attributes can include font styles, paragraph styling, text color, and more. By using NSAttributedString, developers can create rich text with customized formatting. Creating an NSAttributedString Let’s break down a […] - [Automating macOS System Settings with JavaScript for Automation (JXA)](https://redflowerinc.com/automating-macos-system-settings-with-javascript-for-automation-jxa/): Introduction Automation can be a powerful tool to streamline repetitive tasks and customize your computing environment. In this blog post, we’ll explore how to use JavaScript for Automation (JXA) on macOS to interact with System Settings, focusing on changing the tracking speed for the mouse. Prerequisites Before diving into the code, ensure that you have a basic understanding of JavaScript and macOS System Settings. Additionally, make sure that your script runner, in this case, osascript, has the necessary permissions to control System Settings. The Code Code Breakdown Launching System Settings The script begins by revealing and bringing the System Settings […] - [Supporting Right To Left Languages](https://redflowerinc.com/supporting-right-to-left-languages/): RTL (Right-to-Left) languages are languages where text is written from right to left, contrary to the left-to-right direction of most languages. Some of the prominent RTL languages include: These languages are written and read from right to left, impacting not only the direction of the script but also the layout and design of documents, websites, and other materials. When we use constraints to place views, we tend to do the following The above code will fix the RTL languages. If you want to know more about localizing images for RTL, you can follow this link - [Using visual studio code to compile and run projects on Xcode/Simulator directly](https://redflowerinc.com/using-visual-studio-code-to-compile-and-run-projects-on-xcode-simulator-directly/): You can use the below command line to run your project directly from Visual Studio Code Sure, let’s break down the command line into its individual parts and explain each one: xcodebuild -scheme pom -destination 'platform=iOS Simulator,name=iPhone 12 mini,OS=16.0' This command is used to build the pom scheme of your Xcode project for a specific destination. The destination in this case is an iOS Simulator running iOS 16.0 on an iPhone 12 mini. xcodebuild is a command-line tool provided by Xcode that lets you perform build actions on your projects or workspaces. xcrun simctl install booted /Users/dk/Library/Developer/Xcode/DerivedData/pom-giguhgtpjuelvmdmgdxggjfgevzr/Build/Products/Debug-iphonesimulator/pom.app This command is […] - [How to call deep links within a WKWebView](https://redflowerinc.com/how-to-call-deep-links-within-a-wkwebview/): When using a web view within the app, if you click on a deep link, it won’t open the deep link and the handlers in the app delegate won’t be invoked. This is expected. In order to fix this, you would need to implement delegate of the WKWebview and then intercept the traffic to handle it separately. This is how you can do it. - [Leverage method swizzling to test network calls](https://redflowerinc.com/5825-2/): Method swizzling is a technique used in Swift and Objective-C to modify or exchange the implementations of methods at runtime. It’s a powerful and flexible technique, but it should be used with caution because it can lead to unexpected behavior and hard-to-maintain code if not used carefully. We can actually leverage this mock network calls and use it to tests. For e.x. let’s consider you are trying to download a set of names. /v1/department/history/names Hit this api and download all data into a JSON. You can name it as v1_department_history_names.json Store this in the resources bundle of your app. Lets […] - [Encrypting a string using kCCAlgorithmAES](https://redflowerinc.com/encrypting-a-string-using-kccalgorithmaes/): You can use it as shown below Finally convert it back to the string - [Using Mirror type in Swift to convert Struct into a dictionary](https://redflowerinc.com/using-mirror-type-in-swift-to-convert-struct-into-a-dictionary/): In Swift, you can convert a struct into a dictionary by using the Mirror type, which provides a way to introspect the values of an instance of a struct or class. Here’s an example of how you can convert a struct into a dictionary: In this example, we create a Person struct with three properties: name, age, and email. Then we create a Mirror instance using the reflecting initializer, which takes the struct as a parameter. We then create an empty dictionary with a string key and an Any value. We iterate over the Mirror instance’s children using a for […] - [How to call async methods from objective-c](https://redflowerinc.com/5738-2/): Consider the below piece of code, its written in Swift and it uses Async/Await. In order to use this code in Swift, you would do this This can be called from objective-c directly as follows The Objective-C method implementation synthesized by the compiler will create a detached task that calls the async Swift method perform(operation:) with the given string, then (if the completion handler argument is not nil) forwards the result to the completion handler. The synthesized Objective-C method implementation will create a detached task that calls the async throws method sayHello(operation:). If the method returns normally, the String result will be delivered to the completion handler in the first […] - [How to make your code more Swifty using NS_SWIFT_NAME](https://redflowerinc.com/how-to-make-your-code-more-swifty-using-ns_swift_name/): NS_SWIFT_NAME is an attribute in Objective-C that is used to specify a Swift-compatible name for an Objective-C symbol. When writing Objective-C code that needs to be accessed from Swift, it is often necessary to provide alternate names for Objective-C symbols that have names that do not conform to Swift’s naming conventions. For example, in Objective-C, it is common to prefix method names with a two-letter code that indicates the class the method belongs to (e.g., UIView addSubview:). However, in Swift, this prefix is not used, and the method would be accessed as addSubview(_:). To provide a Swift-compatible name for an […] - [How to fix navigation controller constraints when loading SwiftUI from UIKit](https://redflowerinc.com/how-to-fix-navigation-controller-constraints-when-loading-swiftui-from-uikit/): Considering you use a UIKit app as shown below. When you load a SwiftUI view from UIKit you would use a hosting controller to load. At this instance, most likely you will see a small gap at the top. This happens because of the conflict between the navigation controllers of UIKit and SwiftUI. To fix this you can do the following. Add a view controller in the middle, and set the hosting controllers constraints inside that controller. Here is a example on how to do that You can load the middle controller from UIKit as follows - [Creating a new Xcode project without Storyboard in Xcode 14](https://redflowerinc.com/creating-a-new-xcode-project-without-storyboard-in-xcode-14/): By default when you create a Xcode project, it lets you choose whether you want to create it in Storyboard or SwiftUI. If you choose storyboard, it will automatically create a storyboard for you in Xcode 14. In order to remove the storyboard, you would need to do the following Delete the Main.storyboard file. 2. Go to Targets -> Select your target -> Click on the Info tab3. Delete the row Main Storyboard file base name 4. Expand Application scene manifest. Drill down and delete the row Storyboard name. 5. Open SceneDelegate class and update the code in the following […] - [Using protocols to display different types of json responses from the server](https://redflowerinc.com/using-protocols-to-display-different-types-of-json-responses-from-the-server/): Assume you have the following json. If you notice carefully, the data is almost similar to each other. Our goal is to give us a single data structure, which will store the details shown here. To begin with, let’s define a protocol Let’s define the Codable object for these responses. You can easily convert the string into a Codable object using the tool here https://app.quicktype.io/ Now let’s define the actual method to decode this json. You can notice we have a single return type called Transaction. Display the data as shown below - [Why you should be using nullable/nonnull when calling objective-c code in Swift ?](https://redflowerinc.com/why-you-should-be-using-nullable-nonnull-when-calling-objective-c-code-in-swift/): Let’s say you have the following method in objective-c When you import this in Swift, you will be importing the code as follows As you can see from the above code, you are actually importing as implicitly unwrapped optionals. This can be a problem, if you are trying to unwrap a null object. You can try to resolve this by using the following code snippet. By using nullable and nonnull, you can actually tell the swift compiler whats the type that needs to be imported. You can simplify the process of annotating your Objective-C code by marking entire regions as […] - [How to connect Lark Calendar with Apple Calendar](https://redflowerinc.com/how-to-connect-lark-calendar-with-apple-calendar/): Open your settings and click on the Calendar option. Now open your internet accounts on your mac. Generate your device user name and password. Click on Add Other Account - [Questions to ask when joining a new company as an iOS engineer](https://redflowerinc.com/questions-to-ask-when-joining-a-new-company/): What timezone will you be working in? Are all team members working in the same timezone? This is especially important; otherwise, you may end up working a 24-hour shift. Imagine if the person responsible for making code design decisions sits in another timezone or country; you will end up wasting a lot of time waiting for them to come online. How long does it take for the app to run on the device from click to running mode? You don’t want to wait for a long time between runs. Less than thirty seconds should be fine. When developing a feature, […] - [Building for iOS, but the linked and embedded framework * was built for iOS + iOS Simulator.](https://redflowerinc.com/building-for-ios-but-the-linked-and-embedded-framework-was-built-for-ios-ios-simulator/): I am sure many of us have seen this warning when building your Xcode projects. With the release of Xcode 13.2, this warning has turned into an error. Basically this says that, your target has been compiled for arm64, but the embedded/linked framework is compiled for arm64 and x86 architecture. You would need to remove the x86 arch, so that only the arm64 architecture remains. This is pretty straight forward. You can use the LIPO command line tool. First let’s confirm what are the architectures present in the given framework. You should see that it contains arm64 and x86 architectures. […] - [Using DispatchGroup to sequentially execute tasks in Swift](https://redflowerinc.com/using-dispatchgroup-to-sequentially-execute-tasks-in-swift/): One of the most common use cases when building an app is to fetch data from a server and then display it. This can achieved by multiple means. For this blog post, we would like to query three URLs and display the data, only when all the three URLs have returned in order. Callbacks are an easy way to achieve this. We also can use task dependency and queues to achieve this. But due to the asynchronous nature of the server calls, we won’t be able to maintain the order. The code below will prove it to you. As you […] - [Implement Merge Intervals in Swift](https://redflowerinc.com/implement-merge-intervals-in-swift/): Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. Constraints: 1 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti <= endi <= 104 Visualize the input as a continuous list of numbers as shown below If you are given an input [1,3] [2,6] [8,10] you can see that the […] - [Accessing non static constant in static function of swift class](https://redflowerinc.com/accessing-non-static-constant-in-static-function-of-swift-class/): I came across this question on stackoverflow. https://stackoverflow.com/questions/32346456/accessing-non-static-constant-in-static-function-of-swift-class Basically it asked, how we can access instance members from static functions. The answer would be no, we can’t access instance variables from static method. But this is possible using a singleton design pattern. The actual code is shown below This is how I can alter it. There you go. - [the MOST simplest way to write a closure or completion handler](https://redflowerinc.com/the-most-simplest-way-to-write-a-closure-or-completion-handler/): I swear, this will be the most simple way to write a closure. Lets consider the return type to be Void Start with the input parameters Next lets move on to the return type Now lets combine the above statements Let’s make use of this, as a completion handler It’s that simple. Now, lets use this logic when using a Map To make it easier, the closure is very similar to the one we described above. You can use this logic to construct your completion handlers - [Find out the type of media from URL in Swift](https://redflowerinc.com/find-out-the-type-of-media-from-url-in-swift/) - [Using Result enum in Swift](https://redflowerinc.com/using-result-enum-in-swift/): Let’s consider you are trying to download a json. You have a completion handler as shown below If you look at the method declaration, you can see that it has a completion handler to it. You can use the completion handler as shown below when using the Download method. This type of code design is good. But we can make the code more cleaner, by making use of the Result enum is Swift. The Result enum is available since Swift 5 and allows us to define a success and failure case. The type is useful for defining the result of […] - [Automatically add copyright license for new files in Xcode](https://redflowerinc.com/automatically-add-copyright-license-for-new-files-in-xcode/): If you are planning to add a copyright license for new files automatically, this is how you do it. Here are the most commonly used macros. Xcode reads the templates from a plist. I am assuming for the sake of this post, you would be using a workspace. Go to your workspace location. Create a plist at this location. You can create a plist by going to New file and selecting property list. Insert the below text into the plist Now go ahead and save the plist. That’s it. Next time you create a new file, you will automatically see […] - [XCTest - Handling camera/photos/location permissions alerts when running UX tests](https://redflowerinc.com/xctest-handling-camera-photos-location-permissions-alerts-when-running-ux-tests/): When running UX tests, we are often interrupted by alerts as shown below. Whats a good way to handle this ? There are two ways you can handle these alerts. You can either use addUIInterruptionMonitor or waitForExistence APIs to handle the alerts. You can use the below diagram to determine what you should be using. Let’s consider your app always asks for the photos library permission when it opens up. I would handle this using a addUIInterruptionMonitor API as shown below. In the above code snippet, we are clicking the Allow access to all Photos button. You can alter the […] - [How to implement rounded corners for buttons in SwiftUI](https://redflowerinc.com/how-to-implement-rounded-corners-for-buttons-in-swiftui/): Normally when implementing buttons in iOS, which needs rounded corners, we use the corner radius API to round the corners. In order to do this, you would need to calculate the height and then divide by a number you deem suitable. This is not always a suitable choice, since you would always need to fetch the height and estimate the denominator. The newer and easier way to do this in SwiftUI, is to use the Capsule API. https://developer.apple.com/documentation/swiftui/capsule A capsule shape is equivalent to a rounded rectangle where the corner radius is chosen as half the length of the rectangle’s […] - [When to use @State and @BindableObject](https://redflowerinc.com/when-to-use-state-and-bindableobject/) - [Keychain wrapper in objective-c](https://redflowerinc.com/keychain-wrapper-in-objective-c/): Computer users often have small secrets that they need to store securely. For example, most people manage numerous online accounts. Remembering a complex, unique password for each is impossible, but writing them down is both insecure and tedious. Users typically respond to this situation by recycling simple passwords across many accounts, which is also insecure. The keychain services API helps you solve this problem by giving your app a mechanism to store small bits of user data in an encrypted database called a keychain. When you securely remember the password for them, you free the user to choose a complicated […] - [Leveraging CoreML to generate personalized videos in iOS applications similar to Google and Apple Photos](https://redflowerinc.com/leveraging-coreml-to-generate-personalized-videos-in-ios-applications-similar-to-google-and-apple-photos/): If you have used the Photos app and Google Photos app on the iPhone, you might have noticed, it generates videos automatically for you. Basically it will group similar photos or videos and then make a personalized video for you. How do they do it ? Let’s try doing the same using CoreML framework in iOS. CoreML is a framework provided by apple to Integrate machine learning models into your app. Core ML supports Vision for analyzing images, Natural Language for processing text, Speech for converting audio to text, and Sound Analysis for identifying sounds in audio. Core ML itself builds on top of low-level primitives like Accelerate and BNNS, as well as Metal Performance […] - [Passing ObservableObject and StateObject between SwiftUI and UIKit](https://redflowerinc.com/passing-observableobject-and-stateobject-between-swiftui-and-uikit/): In this tutorial, I will be explaining how we can go pass data between SwiftUI and UIKit. It’s pretty straightforward to use observable and state objects when passing data between SwiftUI views. When it comes to UIKit, you cannot directly pass these objects. There is a lot more you need to do. To visualize, my UX will be as shown below. I will declare an observable object in SwiftUI code. It will have a @published variable to show an error. This in turn will pop up an alert showing the error. Next we will write the SwiftUI view. This will […] - [Using ForEach in SwiftUI to iterate through Views](https://redflowerinc.com/using-foreach-in-swiftui-to-iterate-through-views/): You will commonly need to iterate through similar views and display them in SwiftUI. For e.g. similar to the image shown below. Normally we would use ForEach to iterate and display them. ForEach is a structure that computes views on demand from an underlying collection of identified data. In order to make it work, you must provide a unique id. Either the collection’s elements must conform to Identifiable or you need to provide an id parameter to the ForEach initializer. Below is the snippet of code, I use to iterate through them. I use an unique id here. This coding style can be helpful when you […] - [Calling APIs inside SquareSpace](https://redflowerinc.com/calling-apis-inside-squarespace/): Square space is a no code platform. You are constrained by what it provides. Let’s consider you are developing a website to display your favorite books. You want to dynamically query a URL and display the data in your website. There isn’t a straightforward way to do this now. In this tutorial I will explain how you can do this. Goto square space, and add a new page. Once there, go and add a code snippet as below. Next, you would need to select the HTML option. Uncheck the checkbox display source. This is very important. Else it will display […] - [Find the largest number by swapping adjacent digits if they have the same parity in Swift](https://redflowerinc.com/find-the-largest-number-by-swapping-adjacent-digits-if-they-have-the-same-parity-in-swift/): Problem description: You are given a number. You can swap two adjacent digits, if they are both odd or even. For e.g. given (3,8), you can’t swap them. But you can swap (5,9) since they are both odd. They have the same parity. A similar problem is explained here https://www.youtube.com/watch?v=qEIGhVtZ-sg Function description: swapDigitsAndGetLargestNumber(number: String) Returns: Largest number formed from the string. Example 1 Input: 117596801 Output: 975118601 Example 2 Input: 68019 Output: 86091 Keep in mind, you can only swap if they have the same parity. Pseudo code Convert the string into a array of numbers Start with the left […] - [Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.](https://redflowerinc.com/given-string-num-representing-a-non-negative-integer-num-and-an-integer-k-return-the-smallest-possible-integer-after-removing-k-digits-from-num/): The explanation is here https://www.youtube.com/watch?v=3QJzHqNAEXs We use a stack here to store the values. If the previous number is greater than the current number, we will remove the previous number. Else store the number in the stack. - [Executing Timer in background in iOS](https://redflowerinc.com/executing-timer-in-background-in-ios/): Timer dispatch sources generate events at regular, time-based intervals. You can use timers to initiate specific tasks that need to be performed regularly. For example, games and other graphics-intensive applications might use timers to initiate screen or animation updates. You could also set up a timer and use the resulting events to check for new information on a frequently updated server. All timer dispatch sources are interval timers—that is, once created, they deliver regular events at the interval you specify. When you create a timer dispatch source, one of the values you must specify is a leeway value to give […] - [Coming soon in 2020: objc_direct](https://redflowerinc.com/coming-soon-in-2020-objc_direct/): Before you start reading this tutorial, please read about method swizzling. The Objective-C model of object-oriented programming is based on message passing to object instances. In Objective-C one does not call a method; one sends a message.  In Objective-C, the target of a message is resolved at runtime, with the receiving object itself interpreting the message. A method is identified by a selector or SEL — a unique identifier for each message name, often just a NUL-terminated string representing its name — and resolved to a C method pointer implementing it: an IMP.[18] A consequence of this is that the message-passing system has no type checking. The object to which the message is directed — […] - [1 Minute cheatsheet to begin ANDROID development for iOS developers](https://redflowerinc.com/1-minute-cheatsheet-to-begin-android-development-for-ios-developers/): This table is geared towards iOS developers who want to start working on android. You can refer this table whenever you are confused about what component to use in android, and also what tool to accomplish a task. I have tried to make it 1:1. So its easy to google the information needed. iOS Android Quicktime Vysor AutoLayout ConstraintLayout ViewDidAppear OnResume ViewDidLoad OnCreate dealloc Destroy ViewWillDisappear OnPause ViewControllers Activity Push/Present View Controllers Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); PNG WebP images (https://developer.android.com/studio/write/convert-webp) iExplorer (to look into files inside the device) Device explorer comes with the Device (/data/data) https://developer.android.com/studio/debug/device-file-explorer ChildViewControllers […] - [How to implement a custom Notification Center in Swift](https://redflowerinc.com/implementing-nsnotificationcenter-in-swift/): Notifications are a very helpful tool, when you need to send messages between two modules which are very loosely coupled. In this blog post, I will implement my own NSNotificationCenter in Swift. Let’s start with the basic data structure needed to hold a Notification. I am using a Dictionary, which contains an array to hold the notifications. You can alter this data structure according to your requirements. Each app will have a single notification center. I am going with a singleton to accomplish this. I will be using a Dictionary to store the notifications. The key will be the notification […] - [1372. Longest ZigZag Path in a Binary Tree](https://redflowerinc.com/1372-longest-zigzag-path-in-a-binary-tree/): You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Choose any node in the binary tree and a direction (right or left). If the current direction is right, move to the right child of the current node; otherwise, move to the left child. Change the direction from right to left or from left to right. Repeat the second and third steps until you can’t move in the tree. Zigzag length is defined as the number of nodes visited – 1. (A single node has a length of 0). Return the longest ZigZag path contained in that […] - [Word ladder implementation in Swift](https://redflowerinc.com/word-ladder-implementation-in-swift/): https://leetcode.com/problems/word-ladder/ This post contains the implementation for the leetcode problem shown in the link above. A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. Example 1: Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> […] - [Permutations of a string in Swift](https://redflowerinc.com/permutations-of-a-string-in-swift/): Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: Input: nums = [0,1] Output: [[0,1],[1,0]] Example 3: Input: nums = [1] Output: [[1]] Constraints: 1 <= nums.length <= 6 -10 <= nums[i] <= 10 All the integers of nums are unique. Explainer : Let’s start with three characters ABC. We start with the first character. Start by swapping A with the other characters. A is swapped with A, A is swapped with B and A is swapped with C. We get the following values ABC, BAC […] - [Interacting with Javascript in WKWebView](https://redflowerinc.com/interacting-with-javascript-in-wkwebview/): You can use the WKWebView class to embed web content in your app. To do so, create a WKWebView object, set it as the view, and send it a request to load web content. After creating a new WKWebView object using the initWithFrame:configuration: method, you need to load the web content. Use the loadHTMLString:baseURL: method to begin loading local HTML files or the loadRequest: method to begin loading web content. In order to send a message from WKWebView to objective-c code, you would need to do add script message handler to the webview. In the above code, I initialized a new webview and added a script handler called reloadAnalyticsViewHandler to the webview […] - [Magical Candy Bags](https://redflowerinc.com/magical-candy-bags/): Magical Candy BagsYou have N bags of candy. The ith bag contains arr[i] pieces of candy, and each of the bags is magical!It takes you 1 minute to eat all of the pieces of candy in a bag (irrespective of how many pieces of candy are inside), and as soon as you finish, the bag mysteriously refills. If there were x pieces of candy in the bag at the beginning of the minute, then after you’ve finished you’ll find that floor(x/2) pieces are now inside.You have k minutes to eat as much candy as possible. How many pieces of candy […] - [Element Swapping](https://redflowerinc.com/element-swapping/): Given a sequence of n integers arr, determine the lexicographically smallest sequence which may be obtained from it after performing at most k element swaps, each involving a pair of consecutive elements in the sequence. Note: A list x is lexicographically smaller than a different equal-length list y if and only if, for the earliest index at which the two lists differ, x’s element at that index is smaller than y’s element at that index. Signature int[] findMinArray(int[] arr, int k) Input n is in the range [1, 1000]. Each element of arr is in the range [1, 1,000,000]. k […] - [When do we use [weak self] [unowned] [self]](https://redflowerinc.com/using-self-weak-unowned/): Explaining weak and strong variables is better with an example. Let’s start with two classes Driver and Car. Don’t use Playgrounds to test this code. deinit doesn’t get called in playgrounds Run the code, you should see the class getting initialized, but never getting de-initialized. Let’s dig into why this is not happening. In ViewDidLoad, we are assigning the driver object to the car object and vice versa as shown here There is a retain cycle formed here, with each class referring to a strong variable of the other class. Hence even if the class wants to de-initialize it’s not […] - [Using network link conditioner to test network conditions on Simulator And Device](https://redflowerinc.com/using-network-link-conditioner-to-test-network-conditions-on-simulator-and-device/): Most mobile apps work on client-server architecture. They need to fetch data from the server and then display it to the user. If you have a diverse range of users, you would need to definitely test their network conditions. Some users will be using your app in very low network conditions. Thankfully, apple provides us with tools to test low network conditions. Go to https://developer.apple.com/download/more/?q=Additional%20Tools and download the Xcode 11 tools. In the downloaded package, go to Hardware, and click on Network Link Conditioner.prefPane. This will install the conditioner. You can access this via the System Preferences. This can be […] - [Implementing UIScrollView using constraints without using content size](https://redflowerinc.com/implement-uiscrollview-using-constraints-no-need-to-use-content-size/): UIScrollView is a view that allows the scrolling and zooming of its contained views. UIScrollView is the superclass of several UIKit classes including UITableView and UITextView. The central notion of a UIScrollView object (or, simply, a scroll view) is that it is a view whose origin is adjustable over the content view. It clips the content to its frame, which generally (but not necessarily) coincides with that of the application’s main window. A scroll view tracks the movements of fingers and adjusts the origin accordingly. The view that is showing its content “through” the scroll view draws that portion of itself based on the new origin, […] - [Learning Auto Layout without using Storyboards in Swift](https://redflowerinc.com/learning-auto-layout-without-using-storyboards-in-swift/): My goal in this tutorial is to create views using constraints. I will try to use it in such a way that, anyone can use these constraints to build a more complex layout. The view I would like to create is similar to a UITableViewCell. Create a view and place it at the top of the superview. For every view, you need to set translatesAutoresizingMaskIntoConstraints = false otherwise the custom auto layout constraints won’t work. If your view is the top most view, make use of the safeAreaLayoutGuide to help with safe area insets. roundView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0).isActive = true […] - [How to localize images in iOS/Swift [RTL]](https://redflowerinc.com/how-to-localize-images-in-ios-swift/): Consider you are developing a movie app which is supposed to be released in all over the world. You get a poster image from your marketing team, and you will need to display text on it as shown below. The below image is for left to right language. The text is on the right side. It’s easy to handle the text using the method call NSLocalizedString("redflower", comment: "This is the name of my website") For arabic or right to left languages, it’s a different ball game. The image should be displayed as shown below. As you can see the image […] - [All the things you can do using Properties in Swift](https://redflowerinc.com/all-the-things-you-can-do-using-properties-in-swift/): Set the property as read only Add a setter to the property. Make a note of newValue. This is a predefined swift variable which holds the new value you just passed in. DidSet and WillSet. This is self explanatory Make a note of the keywords oldValue and newValue. These are predefined values in Swift to hold the old and new property values. Take a look at the output below. The first time, the value of the property setterAndGetter is empty. The second time you call this property, it prints the older value. Next we move on to PropertyWrapper. A property […] - [Using ObservableObject to animate in SwiftUI](https://redflowerinc.com/using-observableobject-to-animate-in-swiftui/): It’s pretty easy to accomplish this animation using the ObservableObject. Let me show you how. Use the below class to display all your views one by one. Display your views DaySwiftUIView using a for loop. Let’s write the actual class which does this animation. The single line of code which animates the view is .animation(Animation .spring(response: 0.3, dampingFraction: 0.5, blendDuration: 0.5) //.easeInOut(duration: 0.5) .delay(Double(self.delay))) Inside your swift class which is shown below, use the offset property to set the frame depending on the @Published property as shown here..offset(x: self.settings.removeDayView ? 0 : size.width, y: 0) UserSettings is the name of […] - [Struct vs Class in Swift](https://redflowerinc.com/struct-vs-class-in-swift/): If you look at structs and classes in Swift, they seem similar, but the most fundamental difference between them is how they handle values passed to them. In general Struct is pass by value, whereas Class is pass by reference. I will explain the difference by showing an example. In the above code, I have declared a variable h1.var h1 = hello() In the next line, I assign h1 to h2 and set a different name.var h2 = h1h2.name = "redflower2 struct" If you print the values of h1 and h2, you will see that, they print out different names. […] - [Child View Controller. Why use them ?](https://redflowerinc.com/child-view-controller-why-use-them/): Ever wondered why you would go through the hassle of adding a new view controller instead of just using a UIView. This is how you would be adding a child view controller and removing them. Why use them ? By adding as a child view controller, you don’t need to set the frame of the view you just loaded. The OS will take care of this. If you had used UIView, the frame size would need to be set manually. When adding as a view controller, you can use it in many different ways. For e.g. you can push it […] - [Method swizzling in Swift and ObjectiveC](https://redflowerinc.com/method-swizzling-in-swift/): Method Swizzling is the ability that Objective-C Runtime gives us, to switch the implementation of an existing selector at runtime. I came across an article in NSHipster which does method swizzling. The link to the article is here https://nshipster.com/swift-objc-runtime/ For convenience or to work around a bug in a framework, or because there’s just no other way, you need to modify the behavior of an existing class’s methods. Method swizzling lets you swap the implementations of two methods, essentially overriding an existing method with your own while keeping the original around. The article uses dispatch_once to perform method swizzling. This […] - [Interoperability between C++, Objective-C, Swift and SwiftUI](https://redflowerinc.com/interoperability-between-c-objective-c-swift-and-swiftui/): The below diagram shows the pattern I have been following to make my integration easy between the various parts of my code. Dependencies: iOS 13 is the deployment target Let’s start with an Xcode Objective-C project. Let’s name the project Interoperability. Please pay careful attention to your project name. You would be using the name to include the header file which is generated by Xcode. e.g. #import "interoperability-Swift.h" I will explain this part later in this blog. Let’s start with the UX. I have used SwiftUI. Pay attention to this snippet of code below. What I have done here is, […] - [Fisher Yates In Place shuffle implementation](https://redflowerinc.com/fisher-yates-in-place-shuffle-implementation/): In swift you could also use var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] arr.shuffle() Both will give you similar performance when you measure it using XCTest. Here is a chart to prove it. - [Doubly Circular linked list in Swift using Generics](https://redflowerinc.com/doubly-circular-linked-list-in-swift-capable-using-generics/): Let’s try writing the data structure to support the animation as shown below. Basically you need to have multiple views be able to move back and forth. I went with circular linked list since, it maintains a pointer to the next and previous nodes. I wrote the data structure using Generics, this way we are able to use it to support different data types. The data structure is shown below. You can test the code as shown below. As you can see, for now I have tested this with UIView, String and Int. This is the code for testing the […] - [Dispatch and global queues](https://redflowerinc.com/dispatch-and-global-queues/): Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently. Work submitted to dispatch queues executes on a pool of threads managed by the system. Except for the dispatch queue representing your app’s main thread, the system makes no guarantees about which thread it uses to execute a task. You schedule work items synchronously or asynchronously. When you schedule a work item synchronously, your code waits until that item finishes execution. When you schedule a work item asynchronously, your code continues executing while the […] - [How I solved the duplicate symbols issue when integrating google frameworks SDK for iOS ?](https://redflowerinc.com/how-i-solved-the-duplicate-symbols-issue-when-integrating-google-frameworks-sdk-for-ios/): Recently I was integrating the new google sign in SDK into my project. https://developers.google.com/identity/sign-in/ios/sdk This was a new version and I was integrating it after a couple of months. I followed the usual, and when I compiled my project, I started getting these compile errors. duplicate symbol 'OBJC_IVAR$_GTMAppAuthFetcherAuthorizationArgs.request' in: pathInBuildDebug.build/Objects-normal/arm64/GTMAppAuthFetcherAuthorization.o pathInGoogleFolder/GoogleSignInDependencies.framework/GoogleSignInDependencies(GTMAppAuthFetcherAuthorization_8eb40aa9262502d90d50b6a28bea1d68.o) duplicate symbol '_OBJC_IVAR$_GTMAppAuthFetcherAuthorization._shouldAuthorizeAllRequests' in: pathInBuildDebug.build/Objects-normal/arm64/GTMAppAuthFetcherAuthorization.o duplicate symbol 'OBJC_IVAR$_OIDExternalUserAgentIOSCustomBrowser.canOpenURLScheme' in: pathInBuildDebug.build/Objects-normal/arm64/OIDExternalUserAgentIOSCustomBrowser.o pathInGoogleFolder/GoogleSignInDependencies.framework/GoogleSignInDependencies(OIDExternalUserAgentIOSCustomBrowser_0ecc41f590539d34b9efeb9577094ab4.o) duplicate symbol '_OBJC_IVAR$_OIDExternalUserAgentIOSCustomBrowser._appStoreURL' in: pathInBuildDebug.build/Objects-normal/arm64/OIDExternalUserAgentIOSCustomBrowser.o pathInGoogleFolder/GoogleSignInDependencies.framework/GoogleSignInDependencies(OIDExternalUserAgentIOSCustomBrowser_0ecc41f590539d34b9efeb9577094ab4.o) There were a lot of errors, but I have pasted only a subset. Most errors said duplicate symbols. That gave me a idea that I might be already including these header files. […] - [Sample program using timers to update the rows in TableView](https://redflowerinc.com/sample-program-using-timers-to-update-the-rows-in-tableview/): It has to do the following: - [Different types of Closures in Swift](https://redflowerinc.com/different-types-of-closures-in-swift/) - [Designated and Convenience Initializers in Swift](https://redflowerinc.com/designated-and-convenience-initializers-in-swift/): All of a class’s stored properties—including any properties the class inherits from its superclass—must be assigned an initial value during initialization. Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. These are known as designated initializers and convenience initializers. Normally you would have a single init method. You would initialize it using the above call. Consider you need to initialize it with a name. Then you would add another initializer as shown below. At this point you would need to add a convenience keyword for the init function. It’s that […] - [Reading and Writing to a JSON in Swift](https://redflowerinc.com/reading-and-writing-to-a-json-in-swift/): Lets consider you have a sample JSON as shown belowhttps://gist.github.com/kmdarshan/cfa6a940268f7091faf886ed63b3b559 You can make use of Codable Library (https://developer.apple.com/documentation/swift/codable) in Swift to read and write data from a JSON. Firstly you need to map your data from the JSON onto a Struct as shown below. Once you have done that, its easy to read it using the decode and encode libraries in swift. https://gist.github.com/kmdarshan/897f3e54ab4f133c25af4512be7e4ff1 Let’s consider you have the below JSON. It’s an array. Everything seems fine, until you notice that the loan_amount is a String and Int. This will fail to parse normally. You would need to go about this […] - [Implementing factory design pattern in Swift](https://redflowerinc.com/implementing-factory-design-pattern-in-swift/): https://gist.github.com/kmdarshan/d425061bba80394fe1dc7405c3efb074 - [How to stop the debugger in a platform agnostic way ?](https://redflowerinc.com/how-to-stop-the-debugger-in-a-platform-agnostic-way/) - [Find minimum in a rotated sorted array](https://redflowerinc.com/find-minimum-in-a-rotated-sorted-array/): https://gist.github.com/kmdarshan/8a0ba0deef7663848caca97ae0710c98 - [Fizzbuzz implementation in Swift](https://redflowerinc.com/fizzbuzz-implementation-in-swift/): https://gist.github.com/kmdarshan/be310634e6fce034ccf1c0d53fd843e8 - [How to align icons in a stack view in iOS](https://redflowerinc.com/how-to-align-icons-in-a-stack-view-in-ios/): Sometimes using storyboard to do your alignment is easier than doing it via code. Here are the steps. Select all the icons, you want to add to the stack view. Click on the Embed in StackView at the bottom of the Xcode editor. Refer video. - [Using AttributedString in Swift](https://redflowerinc.com/using-attributedstring-in-swift/): https://gist.github.com/kmdarshan/431f579bb204fc81560bdcc325e3ab95 - [Detecting interlaced videos using FFMpeg](https://redflowerinc.com/detecting-interlaced-videos-using-ffmpeg/): If you observe the output below, you will see that the progressive, repeated fields , single frame and multiple frame have values in them. This should give you an idea that it’s an interlaced video. Also most interlaced videos will have an ‘i’ in them. e.g. 1080i - [Exporting an AVAsset in iOS](https://redflowerinc.com/exporting-an-avasset-in-ios/) - [Detecting exception crashes in xcode](https://redflowerinc.com/detecting-exception-crashes-in-xcode/) - [76. Minimum Window Substring in Swift](https://redflowerinc.com/76-minimum-window-substring-in-swift/): Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string. Example 1: Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. Example 2: Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window. Example 3: Input: s = "a", t = "aa" […] - [Find Median from Data Stream](https://redflowerinc.com/find-median-from-data-stream/): The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values. For example, for arr = [2,3,4], the median is 3. For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5. Implement the MedianFinder class: MedianFinder() initializes the MedianFinder object. void addNum(int num) adds the integer num from the data stream to the data structure. double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted. Example 1: Input ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] [[], […] - [Largest Triple Products in Swift](https://redflowerinc.com/largest-triple-products-in-swift/): Largest Triple Products You’re given a list of n integers arr[0..(n-1)]. You must compute a list output[0..(n-1)] such that, for each index i (between 0 and n-1, inclusive), output[i] is equal to the product of the three largest elements out of arr[0..i] (or equal to -1 if i < 2, as arr[0..i] then includes fewer than three elements).Note that the three largest elements used to form any product may have the same values as one another, but they must be at different indices in arr. Signature int[] findMaxProduct(int[] arr) Input n is in the range [1, 100,000]. Each value arr[i] […] - [String comparison in Swift and Objective C](https://redflowerinc.com/string-comparison-in-swift-and-objective-c/): https://gist.github.com/kmdarshan/36abd7d48f5175704f2a4e764130ac7c - [How to send a NSNotification in React Native to Javascript?](https://redflowerinc.com/how-to-send-a-nsnotification-in-react-native/): Send a notification from Objective C to React Native. Follow the link below to see how you can send a notification from Javascript to Objective-C and then back again to JS front end. https://gist.github.com/kmdarshan/0910d6d130badec29744792bf99e3b6d - [All the new features in iOS 11](https://redflowerinc.com/all-the-new-features-in-ios-11/): Drag and drop In iOS 11 https://en.wikipedia.org/wiki/Apple_File_System app store multiple days / user reviews iOS 11 – 64bit only. 32 bit apps not supported anymore High sierra last release to support 32bit release Jan 2018 – 64bit only app store Xcode 9 is much faster Semantic highlight – useful for functions opening and closing braces Brand new refactoring system (swift, c, c++, objective c) Xcode 9 has swift 4 Swift – String easier to use, unicode correctness Codable prototype 40% faster Swift/Objective C projects Searching and indexing faster Github integration (not sure if bitbucket is supported) Undefined Behavior sanitizer Main […] - [How to setup your project in Xcode to support multiple frameworks and sub-projects using XCCONFIGS?](https://redflowerinc.com/how-to-setup-your-project-in-xcode-to-support-multiple-frameworks-and-sub-projects/): If you have multiple targets use config files. This is the way to create them. Below is a sample of what you can specify in the config files. ARCHS = arm64 CLANG_CXX_LANGUAGE_STANDARD = gnu++98 CLANG_CXX_LIBRARY = libstdc++ LD_NO_PIE = NO OTHER_LDFLAGS = -Wl,-warn_compact_unwind HEADER_SEARCH_PATHS = ../code/ FRAMEWORK_SEARCH_PATHS = ../debug One of the things you can notice is that I am specifying that we only support 64bit architecture. You can also specify the framework and header search paths. This will enable you to easily edit the paths. Once you create the config files you need to set this config file to […] - [ipps90legacy.h not found error](https://redflowerinc.com/ipps90legacy-h-not-found-error/): Goto https://software.intel.com/en-us/articles/intel-ipp-legacy-libraries and download the links for your OS. Then follow the installation text file inside the zipped file. The password is specified in the installation file. Once downloaded extract the headers and libs into the proper folder. e.g. /opt/intel/include… - [Counting words in a sentence](https://redflowerinc.com/counting-words-in-a-sentence/): https://gist.github.com/kmdarshan/ea10fa9c6312a88e55f5b2a3dad38146 - [How to set content offset for collection view using NSLayoutConstraint](https://redflowerinc.com/how-to-set-content-offset-for-collection-view-using-nslayoutconstraint/):   As you can see in the above video, the last row of the photos is getting cut by the buttons. Ideally you would need to have the collection view scroll up, so that the last row is correctly visible. This can be done by setting the content offset programmatically. Today I would be showing you another way to do it when using storyboards. First you need to set constraints in your storyboard between the superview and the container as shown below. After setting this, lets move on to the code. You need to connect this view to constraint in […] - [Remember to set this option when setting constraints in auto layout](https://redflowerinc.com/remember-to-set-this-option-when-setting-constraints-in-auto-layout/): Always, when you set the constraints in auto layout in iOS,  set the update option as shown in the pictures below : Also in most cases uncheck “Relative to margin” option.   - [Developing a hybrid solution with KIF and UIAutomation frameworks](https://redflowerinc.com/developing-a-hybrid-solution-with-kif-and-uiautomation-frameworks/): Will KIF support targeting elements in WKWebView ? By now, you must have already known that KIF wouldn’t support accessing and tapping elements in WKWebView. This would surely cause a lot of problems for automation tests which were written to access UIWebView. [tester waitForViewWithAccessibilityLabel:@”SIGN IN”]; The above call will surely fail in WKWebView. In most cases, the login screen would be written in HTML to make it work in all platforms and make it compatible with single sign on. Google and Yahoo are some of the examples. To solve this either, you can keep the app always logged in, which […] - [Planr : Easiest way to plan events](https://redflowerinc.com/planr-easiest-way-to-plan-events/) - [Preprocessor macros and configuration](https://redflowerinc.com/preprocessor-macros-and-configuration/): In your xcode settings, you might have seen the configurations as shown below: You can find the current configuration : xcodebuild -workspace test.xcworkspace -scheme “UXtests” -showBuildSettings You would use it in the code as follows : #ifdef TESTING // do something #endif But how would you apply the debug and testing configurations. These preprocessor statements can’t be applied when you run your project by running command + r. These can be used through the command line as follows: xcodebuild -workspace Test.xcworkspace -scheme “ux tests” -derivedDataPath build/DerivedData -configuration Testing Thats how you use it. Next time someone asks you, remember this. - [Rendering an image on the iOS simulator](https://redflowerinc.com/renderingx-an-image-on-the-ios-simulator/): I have come across posts saying that the image doesn’t render on the iOS simulator. In order to generate an image, you get the pixels using this call. CIImage* ciImage = [CIImage imageWithCVPixelBuffer:pixelBuffer]; This will always fail on the simulator. The workaround to fix this would be creating a frame of your own, and then reading the pixels yourself into the buffer. Here is the code to do that: NSDictionary* options   =@{ (NSString*)kCVPixelBufferIOSurfacePropertiesKey : [NSDictionary dictionary] };CVPixelBufferRef pixelBuffer = NULL;CVReturn err = CVPixelBufferCreate( NULL, width, height,(OSType)HSPixelFormatToCoreVideoPixelFormat(inPixelFormat),  (__bridge CFDictionaryRef)options, &pixelBuffer); Here comes the crucial part, in the simulator you would manually need to read the […] - [Changing the default layer used by UIView in iOS](https://redflowerinc.com/changing-the-default-layer-used-by-uiview-in-ios/): How to do it ? +(Class)layerClass {     return [CAEAGLLayer class] or [CAMetalLayer class]; } Why should you do it ? Your view draws content using Metal or OpenGL ES, in which case you would use a CAMetalLayer or CAEAGLLayer object. There is a specialized layer class that offers better performance. You want to take advantage of some specialized Core Animation layer classes, such as particle emitters or replicators. ## Pages - [Treat by Shutterfly](https://redflowerinc.com/treat-by-shutterfly/) - [Adobe Premiere Clip](https://redflowerinc.com/adobe-premiere-clip/): Make video clips automatically from your videos. This has been discontinued for the more advanced Premiere Rush. - [Apps](https://redflowerinc.com/adobe-premiere-rush/) - [Portfolio](https://redflowerinc.com/apps/): Adobe Premiere Rush Professional level, easy to use video editing tool for creative professionals. It’s available on windows, mac, android and iOS. Click here to know more Link to app store Adobe Premiere Clip Easy to use iOS app to create videos automatically with soundtracks. Planr iOS app Technology stack – ObjectiveC, Mongo, Apple push notification service Chat and plan events with friends within the app.  Treat by Shutterfly Technology stack – ObjectiveC, REST, JSON, CoreData, CoreText, PHP, Javascript Treat is a new kind of greeting card service from Shutterfly, and we’re changing the way you connect with your favorite […] - [Contact](https://redflowerinc.com/contact/): kmdarshan at gmail dot com - [Patents](https://redflowerinc.com/patents/): Creating image product design by distributed users in a true temporal parallel fashion. ObjectiveC, Java, Socket programming  US Patent Number: 20150032637 A computer-implemented method includes allowing a first user to initiate a design of an image product on a first device, allowing the design of the image product to be shared to mobile devices operated by second users, receiving personalized messages comprising a plurality of pixels from the first user or the second users by a network-based image service system, storing personalized messages from the first user or the second users in different layers at a data center in the […] - [Code](https://redflowerinc.com/code/): My implementations for commonly asked questions in interviews. Method names are in italics. You can find the full implementation in this link https://github.com/kmdarshan/practice or you can refer to individual implementations as shown below. Reverse a string reverseString(str: String) Reverse string in place reverseStringInPlace Print two sum in a array printTwoSum Implement Queue using Stacks QueueUsingStacks Binary Search Tree And Check For Validity BST https://github.com/kmdarshan/practice/blob/master/binarySearchTree.swift Combine Two Sorted Arrays https://github.com/kmdarshan/practice/blob/master/combine_sorted_arrays.swift Print Common Numbers In Arrays printCommonNumbersIn Validate the brackets BracketValidator Get the maximum people living in a particular year GetMaximumYearPeopleLiving Adjacency graph / Graph Coloring Problem AdjacencyGraph graphColoringProblem Reverse Words in a Array https://github.com/kmdarshan/practice/blob/master/reverseWords.swift Graph Traversal (Breadth First Search and Depth […] - [Projects](https://redflowerinc.com/projects/): Contacts Selector for iOS Objective C Sample project to read contacts from facebook and iPhone address book. Click here to know more.   Craigslist Jobs Downloader Python, MySql The python scripts will download all jobs available on Craigslist. Its completely written in python. It also has a thread pool to run multiple downloads at once. Its hosted on GitHub. You can download the project from there. Click here to know more. PostIt Java, Swing Simple application to save notes and files. Click here to know more. ScreenCapture Java, Swing Application to take screenshots of the desktop. Click here to know […] - [About](https://redflowerinc.com/about/): I code, develop and learn. I learn a lot from the web, and I want to give back, so that it would help others. This blog is basically my way of giving back to the software community. Contact me at kmdarshan at gmail com [comment]: # (Generated by Hostinger Tools Plugin)