Showing posts with label iOS. Show all posts
Showing posts with label iOS. Show all posts

Friday, April 22, 2022

Guide to manage secrets in SwiftUI app

You are developing the app and a time comes when you need to integrate with other systems like Auth0, Firebase, or some other system that you need for your app. 

Tip: Never put the secrets in the code and check in to the repository. 

I have found that keeping the secrets separate from the code is the best way possible. So how do we do it? 

Step 1 - Create a Configuration file

Create a configuration file that will keep the secret variables and the values for your app. e.g. you are integrating RevenueCat in your application to manage the subscription. RevenueCat requires you to create an API key for the purchases and use that in your app. 

Select New File and search for Configuration Settings File. Select the template and name the file and create it. 


New configuration file


Once the file is created you can add the secret api key in the file. The format you want to follow is <variable name> = <value> e.g. let's name the variable PURCHASES_API_KEY then the value entry in the file will be 

PURCHASES_API_KEY = thisIs_yoursecretapikeyforpurchases

Step - 2 Add an entry to info.plist file

Now add a String entry to your info.plist file and reference the variable in the entry as shown below

 

Info.plist file entry

Step - 3 Access the value in swift

Each source code follows some kind of pattern or something for generic code. Like accessing something from the Bundle, I am posting a sample code that you can use to access the variable but check your source code for any pattern that might be followed for this kind of code, or do what you feel like a good code for you. 

var purchaseKey = ""

    if let key = Bundle.main.infoDictionary?["PURCHASES_API_KEY"] as? String {

      purchaseKey = key

    }

    else {

      purchaseKey = ""

    }


Step - 4 Where to keep the secrets

If you are building an enterprise app there will be a CI/CD pipeline and you would save the secrets in the vault provided by the Tooling. e.g. AzureDev Ops or Bitrise etc. 

What if you are an Indie dev and you just build the app just on your laptop and just deploy it directly to AppStore connect? Well, you can use some browser-based Password managers and put your secrets there. 

Alternatively, you can just create a secure Note by locking the Note. 


The choice is completely yours how you want to keep your secrets secrets but never keep them in your source code :)

The same applies to your GoogleServices json file, do not check in the file with your source code. Keep it separate. 

Tip: Add these secret files to the gitignore file of your repo so that you never accidentally check in them.

Now, what if you have check-in a secret to your git repo and it is in the history now? Well, subscribe and stay updated with the next post where we talk about how to keep an eye on your secrets in your code and what can you do if you check them in accedently. 

Happy coding!!

Thursday, March 24, 2022

Every iOS developer should know these Xcode tricks

 As iOS Developer you must be spending 8-9 hours of the day using Xcode. It is really important that you know the IDE to get most out of it and get more efficient with coding.

Refresh Canvas and close/open canvas


While using SwiftUI one of things you interact most is SwiftUI previewer and we see the Resume button on the previewer and have to click it to so many times. 



Well there is a keyboard shortcut that can make your life easier. By default it is set to Option + Command + P but you can reconfigure it your liking. e.g. I have set it to Command + P


and to do this I had to remove the shortcut for Print. Let's be very clear we do not do Print command from Xcode every day :), So I choose the nearest key to the default one.

Another good shortcut to know if Opening and closing the Canvas, May be there are times where you want to just focus on code and get some more real estate to work with and just want to close the canvas and then once done you want to reopen it again. You can use Option + Command + return to toggle the canvas visibility. Again you can use Xcode keybinding to reconfigure it to your liking.

Open Quickly

If you are working on large project and working on few files then you must know this feature of Xcode. Open quickly let's you open files with you know the name of the file. Press Command + Shift + O to open it and then just start trying the name and you will see the list


A companion option to this one is show only recent files toggle in the project navigator. When enabled it will only show the files you have recently interact with. 



Rename refactoring

Tuesday, March 22, 2022

How to enable spell checking in XCode

 Do you get a lot of PR comments for spelling mistakes? Then this will help you a lot to fix those issue while you are typing.

You can navigated to Edit -> Format -> Spelling and Grammar  and then select ✔Check Spelling While Typing option so that you get live spell checking.




As you can see in screenshot my misspelled word is highlighted with dotted red underline. 

Enjoy Coding!!

Guide to SwiftUI layout and presentation controls in iOS

SwiftUI Layout Containers


It is always better to know about all the tools before you start your DIY project. You need to know what tools are available and what each tool can be used for. The same strategy can be applied to UI design. If you know all the available tools provided by the SwiftUI framework then you will be able to apply that knowledge to the beautiful designs that your designer has provided you with. Following are the Layout containers provided by SwiftUI.

HStack

you can refer HStack as a horizontal stack. You want to stack your controls shown in the image below. 

Horizontal plates stacking


The views in SwiftUI are aligned in a similar fashion as shown in image below

SwiftUI HStack


LazyHStack

As the name says this is a Lazy container. As the keyword, Lazy in a programming language is a strategy to delay the initialization until it is needed. The views in the LazyStack are not initialized until they are needed. 

You can try this code and see how it works. 

import SwiftUI


struct CustomText: View {

  private let index: Int

  init(index: Int) {

    print("init CustomText \(index)")

    self.index = index

  }

  var body: some View {

    Text("This is custom text view")

  }

}


struct ContentView: View {

    var body: some View {

      ScrollView(.horizontal) {

        LazyHStack {

          ForEach(0...100, id:\.self) { index in

            CustomText(index: index)

          }

        }

      }

    }

}

It should look like as shown in image below when you first run it. 

LazyHStack Image


VStack

The Stack is referred to as vertical stack e.g. as shown in the image below


Vertical Stack plates


The corresponding SwiftUI views are stacked in a similar fashion as shown in the image below.

SwiftUI VStack


LazyVStack

LazyVStack works very similar to LazyHStack, it's just that it will align the items vertically. Before you read further, I want you to try the code from the LazyHStack section and just change the LazyHStack to LazyVStack. 

Check the output in the debug window. Must be wondering what is going on there. All the items are getting rendered. 

So what should you do it fix it? Try it before looking at the code below. 

|

|

|

I am sure you have tried it. The thing is that you need to change the ScrollView to be .vertical.

import SwiftUI


struct CustomText: View {

  private let index: Int

  init(index: Int) {

    print("init CustomText \(index)")

    self.index = index

  }

  var body: some View {

    Text("This is custom text view")

  }

}


struct ContentView: View {

    var body: some View {

      ScrollView(.vertical) {

        LazyVStack(alignment: .center, spacing: 50) {

          ForEach(0...100, id:\.self) { index in

            CustomText(index: index)

          }

        }

      }

    }

}

Monday, June 22, 2020

WWDC 2020 Keynote Highlights


AirPods

• AirPods now magically switch between your devices as you use devices that would logically call for AirPods to be connected
• AirPods Pro now supports spacial audio to emulate a theatre like immersive surround sound experience… this takes into a account head movement to map the sound field and anchor it to your device, so if you move your device and head the surround sound pivots to keep you at the centre! 

AppleWatch and WatchOS7

• You can now have multiple rich complications on the one watch face
• You can now download tailored watch faces, or create your own pre configured watch faces and share them via iMessage 
• Maps on watch will include the new cycling directions from Maps 
• Workouts now includes ‘Dance’ and it can tell if you’re dancing with your whole body, just lower or just upper body
• Core training, Functional strength training and cool downs also added 
• The activity app is completely redesigned on iPhone and has been renamed to ‘Fitness’ 
• Sleep tracking is finally here! It allows you to set goals on bedtime and wake times. 
• In the evening, your phone can start a ‘wind-down’ process which will turn on do not disturb and can start your meditation app or some relaxing music 
• The wake up alarm can be Taptic so you don’t wake your partner
• When you’re sleeping you have to tap the screen for it to light up to show time
• There is now a hand washing feature in WatchOS that makes sure you’re washing your hands effectively and for long enough

Privacy

• ‘Sign in with Apple’ now allows developers to help users move their existing accounts across to sign in with apple access 
• With location sharing, you can choose to share your precise, or just approximate location 
• Apps have to have a privacy policy, but it’s usually hidden, so they now have a ‘nutrition label’ style label on the App Store page so you can see a summary of the apps privacy practices. 

Home

• Apple, Amazon and Google have formed an alliance on smart home standards
• Homekit is now open sourced
• The flow for adding Homekit devices 
• Activity zones and face recognition now supported for all cameras in Home, and it will recognise faces of friends and family you’ve tagged in your photos app
• You can now view cameras and your doorbell camera on Apple TV! 


AppleTV

• AppleTV supports the new Xbox adaptive controller and the new Elite controller
• You can use PIP anywhere within AppleTV (so watch the news while you use a workout app etc)
• Airplay now supports 4K 

MacOS

• The new version of MacOS is called MacOS Big Sur
• The OS has been refined, it has more of an iOS feel
• New icons, controls, surfaces
• Consistent highlight tints in apps, rounded row selection styles
• Control centre can be customised and you can add quick actions to your top bar
• Notifications look and are grouped like in iOS
• The new iOS widgets have been bought to the Mac too 
• MacOS Messages: Now has refined search; supports message effects, Memoji stickers and the other enhancements that were added to group chats 
• Catalyst has updates including Total Pixel control, Mac specific interactions and date pickers
• Safari on MacOS: redesigned, more effective tab management, page translation built in

Mac is moving to their own Apple silicon (ARM chips) 

• All the new native Apple apps work on the new chips…. Including Xcode, Final cut etc
• Using a new tool called Universal2 developers can use a single binary to make apps work on both the Apple Silicon and old Intel Macs 
• Microsoft and Adobe are already onboard and have built many of their apps to work on the new Apple Silicon
• Microsoft Office is already built out to support the new Apple chips … and Powerpoint is using Metal for rendering. 
• Adobe Lightroom and Photoshop have also been converted
• Rosetta2 converts existing Mac apps automatically… even games can be converted for the user automatically…. (They demo’d the latest Tomb Raider) 
• iPhone and iPad apps will run on the new Arm MACs completely unmodified! 

Sunday, May 24, 2020

Todo app using SwiftUI

It's time again and I started learning the iOS programming again as SwiftUI looks cool.

I spent couple of weeks going through the swift programming documentation and watched the WWDC videos. 

Note: This is an ongoing blog, which I update as I add more features to my TodoApp.

Learning


Follow along the Swift documentation. Try to code along the examples. Just go through the documentation even if you don't understand the whole thing just try to read all the documentation and get yourself aware with the concepts. This is will help later while reading the code of some
open source project. 

And.. read the documentation again. This is what I am doing now, this time try to understand and repeat until it becomes muscle memory. this is ongoing process.

SwiftUI


Follow the SwiftUI tutorials and try to recreate them. 

Videos


One of my colleague suggested WWDC videos and watch them in the order. 


Blogs

After going through all those videos and tutorials, I have decided to start creating something. So what is first app everyone build, it's Todo app. 

iOS-TodosApp


Download the Github repo to follow along and try the completed features.

Features


  • Create a new Todo
  • Context menu to Complete or Delete a Todo
  • Show completed tasks
  • Add Priority
  • Add Date

Upcoming


  • Edit 
  • Persist the data
  • Add Notification
  • Add Location
  • Login functionality

Learnings while doing TodoApp

Thursday, August 13, 2015

WKWebView for Hybrid Apps in iOS 8

With the release of iOS 8, Apple has brought so many changes in the Framework existing classes and have introduced new classes.

For Hybrid App development we introduced UIWebView, Which is used for displaying the Web content. 

However, with the release of iOS Apple has introduced a new class called WKWebView. which is derived from UIView here is the inheritance chain for WKWebView.

NSObject
|
UIResponder
|
UIView
|
WKWebView

WKWebView is also derived from UIView similar to UIWebView, So what are the difference in both.


Performance


Tuesday, August 5, 2014

Swift – All you need to know – Part 1

As we are studying the Swift programming language for past couple of months. While studying the language I cam across many features of the programming. So I thought to compile all those features with some brief introduction so that if some one just want to have a sneak peak at the features he/she can just go though this blog.

So this is the part -1 of the series I am thinking to write. Hope to complete it soon and cover the features in its entirety.



Objective C has been the core programming language for Apple software Development. It has been there for 20 years and serving us well. As per Apple they have worked for 4 years to design Swift Programming Language.

So what is it that they wanted to achieve with Swift? As per Apple during the Swift Programming language intro in WWDC 2014 they want “Objective C without the baggage of C”.

Swift is Fast, Safe, Modern and Interactive programming language. Here are the few key points of Swift programming language:

       Adapts safe programming patterns by using the Type Inference and Generics.

       It adopts the readability of Objective-C’s named parameters and the power of Objective-C’s dynamic Object Model.

       Provides seamless access to the existing Cocoa Framework and Objective-c code.

        Develop apps for iOS and Mac OS both.

You might have heard about the playgrounds the new feature in XCode 6 where you can use Swift language and see the output of the programming as you finish typing the code. We can discuss Playground and its features in other blog. Today we will talk about what all features Swift Programming language has come up with and will have brief introduction about each feature for you to kick start the language.


Wednesday, June 25, 2014

Optionals in Swift Programming Language

As we learned in my other blog about Initializers in Swift Programming Language that every variable in Swift should be initiazed before trying to access the value.

So what if you do not want to initialize a variable. That is where Optionals in Swift comes into play.

Before start discussing about Optionals you should know about nil. nil in Swift means nothing, no value at all.

Lets see what optionals provides us:

  • Optionals can store value nil which means no value.
  • Any non optional can not store nil.
  • you can check for options have nil or value by just writing if value no need to add extra code for == nil. because optionals can be used in boolean context.
Reading a value from the Optional is called unwrapping the Optional.


How to unwrap optionals?
  • using the force unwrap operator !.  but if you use this operator without checking for nil you may end up with an error at runtime.
  • using the if let statement you can check for the value and unwrap it once. This is called optional binding.

Optional Binding


Saturday, June 21, 2014

Initializers in Swift Programming Language

As the name says Initialization. Initializers are declared to set the initial values of the type when any object of type gets initialized. Initializers are declared using the the syntax

init() {…}

you can also pass parameters to the initializers. So As the Swift programming enforces one simple rule

“Every value must be initialized before it is used”

Only exception to the above rule is optionals where we default their vale to nil. 

So what the above rule means? Does it mean that I cannot write something like

var someString : String

No, It means before you access any value it must be initialized in every possible branch of the execution of the code. If you don’t do it you will get a compile time error. Initializers have the responsibility to fully initialize an instance.

Initializers in Structure

So if you have a structure like this

struct Person
{
    var firstName : String
    var LastName: String
    init(first: String, last: String)
    {
        firstName = first
        lastName = last
    }
}
  • Say you forgot to initialize the firstName in the initiazer, than compiler will generate a compile time error.
  • Also if you try to call any method before initializing all the variables in the struct, you will get a compile time error.
  • you can write initializers for Structures and Classes both.


Memberwise Initializer

What if you do not specify any Initializer to the struct or class? 

Swift Compiler provide you with a Memberwise initializer. So for the above structure if you do not have the initializer declared you can still initialize the values by saying

Tuesday, June 17, 2014

Swift Playgrounds Introduction

So finally I had some time to explore the swift playgrounds. One thing I would like to say about playgrounds is that It's awesome and cool...

So here is the icon that they have given to the playground document type.

Clearly icon goes with the name. But believe me it does goes with the icon, its a child play to use the playground. You just open up the playground and you are ready to code.

Saturday, June 7, 2014

Swift programming Tutorials - Functions and Closures

This is the part 1 of the series of the Tutorials of Swift programming. You can take a quick look at the Introduction to Swift.

In this Tutorials we will learn about

Functions

Use func to declare a function. Call a function by following its name with a list of arguments in parentheses. Use -> to separate the parameter names and types from the function’s return type.


Few Points of Functions:
  • Functions can return multiple values using Tuples
  • Functions can accept variable number of parameters and collect them into an array.
  • Nested functions
  • Functions can accept other functions as parameters.
  • Functions can have function as its return value. Because functions are first-class type.
  • Functions are special cases of closures

Thursday, June 5, 2014

Swift programming language Introduction

I was on my way to learn the all mighty Objective-C, and suddenly Apple has come up with the super cool programming language "Swift"....

We will discuss few things about Swift and you will see more Tutorials coming on the way here regarding this.

Here are few of the highlights of the Swift.

  • Adapts Safe Programming Patterns
  • Future of the Apple Software Development
  • Provides access to the existing Foundation and Cocoa Framework.
  • Support both iOS and Mac Apps development.
Best thing that comes with Swift is...

Playground

Playground is an innovative feature that lets you play with the programming language and you can see the results of the program on the fly without even building and running the code. What it does:

Saturday, May 31, 2014

Multipeer Connectivity in iOS 7 Part 2

In the Part 1 of this series we discussed how we can do multipeer connectivity using the BrowserViewController. 

In this blog we will discuss how we can achieve the same programatically, you can also call it programmatic discovery. Doing this Programatically gives us:

  1. Flexibility
  2. Sending and Accepting Invitations Programmatically.
  3. Build a custom UI for discovery.
So if we are going to things manually, than we should know the classes involved in the process. All the classes which are related to the Multipeer Connectivity are available in the "MultipeerConnectivity.framework". 

Add the framework in the project and you can see the list of classes available in the framework. Out of all the classes which will interest you to start doing things are:
  • MCNearbyServiceAdvertiser
  • MCNearbyServiceBrowser
  • MCPeerID
  • MCSession

Sunday, February 16, 2014

Multipeer Connectivity in iOS 7 Part 1

In this blog we will discuss about how to achieve multi peer connectivity using iOS 7 new Muti peer connectivity Framework. We will do it in multiple parts. In this part we will discuss how to discover the near by devices and connect them using the BrowserViewController.


In the first part we will discuss how can we use the view controller provided by the MultipeerConnectivity.framework. Classes in the Framework are prefixed with MC so from now we will use MC for mentioning the Multipeer Connectivity.

So What are the advantages of using the MC framework? Here are few mentioned in the WWDC sessions.

Sunday, January 5, 2014

Objective C Runtime

We will discuss how Objective C runtime system works and how we can find information about the objects at the runtime. The language always behave differently compile time and runtime. 


Objective C Runtimes

Objective C have two versions of the runtime "modern" and "legacy". The modern version comes with version 2.0 of the language. 

Difference among both the versions is that with the modern runtime if you change the layout of a class than you do not have to recompile the classes that inherit from it.



Sunday, November 24, 2013

Messaging in Objective C

In Objective C we know that objects send messages. If you do not know about it you can refer to the one of the previous blogs Object Model of Objective C

Now the messages are not bound to the method implementation until runtime. So how does this binding happens at runtime? There is no magic here is the messaging function which does this at runtime "objc_msgSend". This function takes the receiver and the name of the method - this is the method selector name as argument,

Tuesday, October 29, 2013

ViewController LifeCycle

We had previously discussed ViewController in the topic Introduction to the ViewControllers in iOS and in that topic we had given an overview of the ViewController LifeCycle.

Today we are going to discuss only the ViewController LifeCycle and How we should use each of the methods provided in the lifecycle event.

What is LifeCycle?

A lifecycle is an event which has certain steps from the point of creation to deletion. So how do we know about the steps during this period? A Sequence of methods is called as they progress through the LifeCycle. 

Now we may need to perform a different kind of actions at different steps of the life cycle and thus we commonly override these methods and perform these actions.

Thursday, October 24, 2013

Introduction to Introspection in Objective C

This article is intended for understanding of the beginners. You will not see any advance stuff here. I will be giving some basic introduction to Introspection and what are the syntaxes to perform the Introspection.

We may have an array of objects of different kind of classes. But we might need to be sure of the type of object before sending a message to the object. So How do we do this? We use introspection.

Saturday, October 19, 2013

Introduction to NSAttributedString and NSMutableAttributedString Class

NSAttributedString

This is new in iOS 6. It is really powerful and really useful. Think of NSAttributedString as an NString where each character has dictionary of attributes. The attributes attached to the character can be its font, the color, is it underline etc etc. Thats how you can think of NSAttributedString as conceptually.

However its not like that It is very efficient and it handles the attributes very efficiently. You will know as we progress through the article.

Syntax

How to we get the attributes from the NSAttributed string. here is the syntax.

-(NSDictionary *)attributesAtIndex : (NSUInteger) index effectiveRange : (NSRangePointer) range;