5 Top App Development Mistakes to Avoid in 2022

Investing in mobile app development will help your brand get a competitive edge over your rival. Mobile apps can help you build your brand awareness, boost your company’s revenue and provide better support and services to your customers. Also, it lets you forge brand loyalty and increase customer engagement and satisfaction.

So, it comes as no surprise that apps have massively inundated businesses. Just check out these interesting stats to see how apps have effortlessly weaved into the fabric of our lives:

The point is that developing a mobile app for your brand will be one of the best decisions for your company. Although, people make many mistakes when building one, which leads to failure of their application.

We don’t want that to happen to you. So, through this post, I will be sharing what mistakes you should avoid when building your mobile app. Let’s get started.



Mistake #1. Failing To Understand Your Customer’s Requirements

People often assume that everyone will love their mobile app. They don’t conduct any research regarding their customer’s requirements and needs. Such endeavors always end up as a disaster. Always determine your target audience before you start working on the project.

User research is essential. Conduct a thorough understanding of your customer’s motivations, personas, behavior patterns, and demographics.

Ask yourself the following questions before commencing the app development:

  • Is your mobile app’s solution valuable and sustainable?
  • Is the app designed as per the latest market trends?
  • Are the features well-executed and user-friendly?
  • Is the app idea original? Are the markets oversaturated with similar ones?

Both marketing and the development of a mobile app depend on user research. Hence, you cannot rely on assumptions regarding consumers’ behavior and needs.

Also, determine what your competitors are doing and how you can be different from them.

Good research will save you lots of time and energy in the long run.



Mistake #2. Underestimating the Total Budget

You have to consider the resources required to develop the mobile app. It’s not like you have a dream of owning an application one fine day and immediately start building it the next day.

Every resource will require an investment. Hence, creating a budget is essential before starting the mobile app development.

There are multiple online calculators to determine the mobile app development cost upfront. We will share with you the best one.

We will share with you the GoodFirms survey report. It will help you determine the cost of developing a mobile app.



Mistake #3. Poor User Interface

First impressions matter! Pay close attention to the user interface of your mobile app. There are abundant applications at the app stores. People don’t hesitate to remove apps from their devices if they don’t find them interesting. The point is: User retention is more important than ever now. So, if you want your app to be downloaded in the first place make sure it’s UI is user-friendly. Hence, prioritize the mobile design process to build an application that users will love to use.

Keep the following points in mind when designing the application UI:

  • Design an app flowchart first before you start working on the application
  • Focus on resolution. Avoid designing for low resolution.
  • Don’t add animation in the intro. People are impatient, and an unskippable one will lead to the uninstallation of the app.
  • Ensure that the animation used in indicating the loading time keeps customers engaged.
  • Add a gesture-based interface to your UI.
  • Allow users to navigate easily via shortcuts and also reverse their actions quickly.
  • The UI design should be consistent.
  • Provide informative feedback
  • Design dialog to allow closure
  • Prevent errors as much as possible



Mistake #4. Adding Too Many Features

Adding too many features won’t make the user appreciate your mobile app more. Nowadays, the word “feature-rich” gets frequently used by marketers, developers, and companies. They believe it to be a positive quality of their application, but it’s a common mistake.

Having too many features can make a mobile app cumbersome. Adding those extra features means you will have to spend more time, resources, and effort during mobile app development.

Hence, go for the main feature and add only those side ones that support the application’s purpose.

If you check out the Zomato app, here are all its features:
Adding food to the cart

  • Location detection for address
  • Payment portal
  • Order tracking
  • Help and support

All these side features fulfill the essential purpose of the app. None of them feels extra. That’s how your mobile app should be too.



Mistake #5. Focus on Downloads Instead of Retention

One major blunder most app entrepreneurs make is focusing on the total no of downloads instead of retention. They consider it as proof of their app’s success.

It is not always the case that high download rates mean that the application is a hit. Nonetheless, the app’s true strength and quality depend on the user retention rate.

Regardless of this reality, People spend thousands of dollars on user acquisition and completely ignore user retention. But then that’s not how it should be, as existing app users can bring in massive ROI (return of investment) if they are correctly engaged.

Loyal consumers not only repeat purchases but also give quality feedback and word-of-mouth advertising.

Here I will share some tips for improving user engagement and app retention:

  • Create a pleasant onboarding experience.
  • Add push notifications in the right way.
  • Use branded in-app messages.
  • Attract people with different offers, discounts, and loyalty programs.
  • Encourage and reward feedback from your customers.

User retention will save you a lot of money that you are spending on marketing. A truly successful app will generate both high downloads and retention rates.



Avoid the above Mistakes to give your App a Strong Start and a Long Lease of Life

A mobile app will aid you in promoting your business products and services to customers from anywhere and at any time. To ensure its success, keep the following points in mind:

  • Have a thorough understanding of your customer’s requirements.
  • Properly plan your budget.
  • Add only those features that are relevant to your application’s core purpose.
  • Focus on retention rate.
  • Make the UI of your mobile app user-friendly.

If you are ready to start working on your mobile app, head over to Goodfirm’s mobile app development service companies, and from there, you can choose which of the companies is ideal for transforming your app idea into a reality.

I hope this blog helps you in launching a successful product in the market. Keep these five points in mind, and your app’s success will be inevitable.


Source link

Which language is used for iOS app development?

Swift programming language used for Ios app development, swift programming language is very powerful and easy to learn. Swift also powerful programming language for IOS, Ipad OS, MacOS, tvOS and watch OS. Swift code is safe by UI design productive software that is running in smoothly and fast. Swift is the result of the latest research on the programming language.
In this article, I’ll clarify precisely what programming language choices you have for coding iOS applications. We’ll check out the promising and less promising times of programming in those dialects, and assets for learning them.
At long last, we’ll cover methodologies you can use to soar your learning speed and get your application to showcase in record time.
Contemplate your application costs. On the whole, we want to think about an essential inquiry. The “best” iOS programming language to learn relies completely upon the objectives you’ve gone ahead for your application.
Modern: Swift is the consequence of the most recent exploration on programming dialects, joined with many years of involvement building Apple stages. Named boundaries are communicated in a perfect linguistic structure that makes APIs in Swift much simpler to peruse and keep up with. Stunningly better, you don’t have to type semi-colons. Surmised types make code cleaner and less inclined to botches, while modules kill headers and give namespaces. To best help worldwide dialects and emoticon, Strings are Unicode-right and utilize an UTF-8 based encoding to enhance execution for a wide-assortment of utilization cases. Memory is overseen consequently utilizing tight, deterministic reference counting, downplaying memory utilization without the overhead of trash assortment.
UI Designing Safely: Swift takes out whole classes of perilous code. Factors are constantly introduced before use, exhibits and numbers are checked for flood, memory is consequently made due, and requirement of select admittance to memory prepares for some programming botches. Punctuation is tuned to make it simple to characterize your aim — for instance, straightforward three-character watchwords characterize a variable ( var ) or consistent ( let ). Also Swift vigorously use esteem types, particularly for generally utilized sorts like Arrays and Dictionaries. This implies that when you make a duplicate of something with that kind, you realize it will not be changed somewhere else.
Another wellbeing highlight is that naturally Swift items can never be anything. Indeed, the Swift compiler will prevent you from attempting to make or utilize a nothing object with an aggregate time mistake. This makes composing code a lot of cleaner and more secure, and forestalls an immense classification of runtime crashes in your applications. In any case, there are situations where nothing is legitimate and proper. For these circumstances Swift has a creative element known as optional. A discretionary may contain nothing, however Swift sentence structure constrains you to securely manage it utilizing the? Grammar to show to the compiler you comprehend the conduct and will deal with it securely.


Source link

Steps to Improve the UX of Your iOS Application to Increase Traffic

What would you use to measure the success of your mobile app? Clearly, each app developer works hard to create and launch an app that achieves the same level of success as WhatsApp, Amazon, and many more. One aspect of the picture is selecting the suitable platform and packing it with the best features. Another crucial feature of the coin is the User Experience (UX), which will influence whether it stays on the user’s phone screen for a long time or churn out. Once the user interface is upgraded to a more appealing design, an iPhone application will strike more ease of use.

In order to match the accuracy, speed, and better user interface design and iPhone app development, your business’s Smartphone app need routine information. According to statistics, more than 60% of the users have a favorable opinion of organizations that provide an excellent mobile experience. On the contrary, 52 percent of users are less likely to engage with a brand that provides a poor mobile experience.

The User Experience is one of the most vital design tools since it makes app navigation easy and user-friendly. With a unique UI, you can easily promote your brand among people. So, here we will discuss the tips with which one can improve the user interface design of the iPhone application.



Tips to enhance the UI design of your iPhone application for development

There are many possible ways to increase sales on your mobile application. The premium rationale is to have an adequate design and robust functionality, which further matches the interface of the app. we have mentioned below a few tips through which you can improvise the User interface.

dev1



1. Maintain a beneficial content-to-user interface ratio

Mobile app designs that are visually appealing will not be enough to connect users. There are other factors to consider to balance the appearance and content of the entire application. The consumer will be forced to avoid using the mobile app due to its indiscipline design. With the precise alignment of each screen and the customization of background color and typography, it helps to draw users’ attention to the mobile app.



2. Add Excellent features to the design

Users’ general meddling causes some things to be changed that are not accepted. Something in the iPhone app that isn’t appealing draws them away to look at another app with similar functionality. If your app hasn’t satisfied users, it seems distrustful.

A user interface design must adore the graphics of an application that has previously condensed the undesirable error that has occurred in the past. So, you have only one option available, hire iPhone app developer who has wider experience in developing a mobile application. Therefore, during the development of an iPhone app, the developer will use a reference strategy for iOS programming.

Alt Text



3. Login access has been refused

The user will feel more at ease going through the whole app visit if the login process is simple and easy. Online shopping apps have undergone significant improvements. For example, a user can now add products to their cart without logging in to the app.

When you visit the mobile application to explore the appearance of the eCommerce store, you will notice that the UI design will display more skills. The most important component is to allow the consumer to look at each product and add it to their cart. Finally, you may request registration in order to continue purchasing things.



4. Select the Correct Colors

Understanding the color technique of your mobile app design is essential since it is the basis and most paramount facet of a well-designed app. Choose colors for your iPhone app that reflect your brand. Each hue has a different meaning and evokes distinct emotions. Moreover, if you have a hue that is similar to your company’s present color, it would be a plus point to develop your mobile application to showcase it as your extension of the website. Also, make sure you select the color contrast that is engaging and enables a better reading experience for the users. Further, it should create a quality and interactive user experience. Let’s take the help of the iPhone app development company that can help you in getting a unique iPhone mobile app for your business.

dev2



5. Think twice about having an ‘Exit’ option in your iPhone app

An experienced and skilled iPhone developer should know that iOS apps do not have a page that quits when the user switches to another application. It should be crystal clear during the iPhone app development.

When a user switches to another app, the app’s performance may suffer. If a wallet app, such as Paytm, or a banking app, requires personal information from users, it should be avoided. In fact, before the application quits automatically, a fixed second of the session is adequate.



6. Keep your eye on the goal

For every entrepreneur, it is a delightful moment when the users are satisfied with the superior user interface design developed by the iPhone specialists for their app. Moreover, the UI keeps them on hold till the goal is achieved.

So, when the iOS developer has created an iPhone application, they should focus on specific regions. Moreover, they should know that the mobile application is going to be used by thousands of people. Therefore, an app’s interface should capture the attention of users according to their preferences.



To Encapsulate

We hope this article has helped you in gathering all the information required to enhance the user interface for the development of the iPhone app. However, there are several more tips to keep in mind during the development of a precise User Interface for your iPhone mobile application. Apple has several iOS development guidelines which every iPhone app developer has to follow to drive the code for the iOS mobile application.


Source link

Best Online Food Ordering System in 2022

If you plan to open a restaurant or might be a grocery store in the next couple of years, or are already running a business, your first concern should be ensuring that your customers can conveniently place an order.

Online food ordering systems have significantly changed the way people eat out, and this trend is not going to slow down anytime soon. As indicated by a new report distributed by Statista, online food delivery experienced the biggest development among all areas in the business, with over $58 million in market volume in 2019. In comparison, traditional restaurants saw only $8 million growth.

The online food ordering systems industry is expected to grow from USD 111. The industry has already reached a market value of $58M in 2019. In 2021 an annual growth rate of 4.3% that is USD 28.48 billion, was seen.

Txtng Inc., an online food ordering system development company, announced that they had received $20M in funding in order to expand their services and hire more employees. According to an article published on techcrunch.com, Daniel May, CEO of Txtng Inc, stated that “the recent funding will be used to develop new features and applications.”

The company’s current roster includes clients such as McDonald’s and Chipotle Mexican Grill. They have developed 300 apps across multiple industries, including food, entertainment and travel.
Here are the Best 3 Online Ordering Systems for Restaurants

1 MenuDrive

MenuDrive is the first online POS and online ordering system that allows restaurants to customise their ordering experience by creating a branded online ordering system. This can be done by sending custom content to the system, such as product photos, menu items, and more. Moreover, your restaurant staff will no longer have to worry about taking time out of their day to take orders for customers; instead, they can focus on other tasks in the restaurant. Instead of just receiving orders on paper from customers, now all orders are transmitted online so that you can view records in real-time.

Some of our customers love this because it streamlines their business workflow. This is especially beneficial if your staff is busy with other duties like running the front of house or kitchen.
MenuDrive’s sister company MenuDash also offers a similar service.

2 Toast POS

Toast POS is an ideal restaurant point-of-sale system for growing businesses. The program was designed to be easy for all types of restaurateurs, from chain restaurants to local eateries. Toast POS comes with features such as an easy-to-use interface that makes it simple for staff members to learn how to use the system and take orders, a Web dashboard that allows owners to see real-time data on their business and make adjustments, and a mobile app that enables servers to take orders away from the point of sale so they can focus on delivering food and drinks.

Toast can integrate with existing restaurant equipment and connect to payment processors or cash drawers through either wired or wireless connections. The system is compatible with iOS and Android devices, making it possible for customers to place orders on their smartphones. Moreover, Toast POS Software is an integrated restaurant management system that operates as a point of sale system. The program also allows for online ordering, gift card and rewards programs and inventory management.

3 Upserve

Upserve renders an end-to-end restaurant management system. The respective system includes options for bars, coffee shops, wineries, and bakeries. Moreover, the Upserve system goes well with its own POS system, mobile app, as well as the payment system. Upserve is convenient and accessible, also 24X7 U.S.-based assistance is rendered.

Upserve is a kind of food ordering system that allows the restaurant’s customers to pay the bill from their tables. Besides, it also offers detailed analytical reports and data-driven reports about the restaurant’s performance.

Besides, the Upserve POS system has successfully set itself distinguished from other generic POS systems. Likewise, the restaurants, cafes, bars, bakeries, or wineries can opt to see the information on sales, customer discounts, labour costs, expenditures, and many more. Besides, the respective software is a cloud-based one and works well on iOS, Android, as well as the Hybrid devices.

Grocery Delivery Software

In the past few years, there has been a lot of hype around “software as a service,” or SaaS. It’s hard to go to a tech conference these days without hearing about the triumph of this business model over the old-fashioned way of selling software: shrink-wrap CDs and upgrades every few years. It seems almost like a done deal; if you’re not in SaaS, then you’re living in the past. We started out with this model, but pretty quickly realised that it wasn’t right for us. We still think there are huge advantages to running your own software, and we’re proud to be part of a movement that’s bringing more self-hosted software into the world. We hope that by setting down some of our experiences and observations from this transition, we can help other people who are thinking about doing something similar.

Top 10 Grocery Delivery App Builder APIs

Let us discuss the top 10 grocery delivery app builder
APIs

1 SHOP.COM API
2 Spoonacular Food API
3 Kroger API
4 BigOven Recipe API
5 Paprika API
6 Grocery Bear API
7 Whisk Graph API
8 Information Machine API
9 midíadía API
10 Preisente Merchant MyShop API
11 Edamam Food and Grocery Database
12 Recipes to Grocery Store
13 Routific
14 Super App
15 Search Grocery Product Reviews by Barcode
16 Tasty API
17 Nutrionix API
18 Halla
19 Fotex App
20 Bilka App
21 BaglQ
22 Netto Mobile App
23 Pushpins

The above-mentioned pointers are the list of APIs but just having access to API isn’t enough; youneed to hire a professional app builder in order to develop a grocery delivery app. Either hire an in-house team, a local agency, freelancers or opt to outsource the developing team, the choice is yours.

Things to Consider While Planning for Food Ordering App Development

The requirements for android and iOS food ordering app development are as follows:

  • The app must be able to accept and store orders from customers through the mobile interface.

  • The app must have a feature that allows the customer to see what the menu is and what items are available.

  • There must be a way for customers to view pictures of the food on offer.

  • Customers should be able to place an order, make changes to an order, and then check out, paying for their order via credit card or Paypal.

  • Deliveries should be able to be made using whichever delivery service is most convenient, including the customer’s own vehicle.
    There are some differences between ordering food and ordering a car, though.

A big one is that if your customer uses the food ordering app, then he or she won’t need directions to the restaurant. That’s because the restaurants will come to them. The only exception would be for people who live in high-rises or other places that don’t allow vehicles to pick up customers at their doorsteps.
The other difference is that customers might not need cash or credit cards to pay for their food. Many restaurants accept payment through the app, so there would be no need to dig into a customer’s pocket for a wallet if they don’t want to.

The menu items available through the food ordering app will vary from city to city and even from restaurant to restaurant. But it will probably be easier to find something on the menu than it is when you order a car through the vehicle rental site because the cab driver doesn’t have much control over what kind of fare he’ll get or what kind of passengers he’ll pick up.

How to Plan Building a Food Delivery App

Follow the below-mentioned steps if you are planning to build a food delivery app:

1 Before starting to frame your strategies, conduct an in-depth market analysis to check on the revenues generated and the ROI.

2 Check on the latest marketing trends- Social media integration, virtual assistant, and link with smartwatch

3 Select the food delivery model- aggregator model or logistic/delivery service model.

4 Think upon the revenue model- delivery charges, surge pricing, revenue sharing, promotional and advertising services, and daily deals.

5 Select the features- registrations, payment gateway, profile management, analytics, storage, direction-finding, user location, easy search options, ratings and reviews, rewards, and push notifications.

6 Decide the versions- admin app, customers app, delivery valets app.

7 Select the technological stack- Autho, Google Places API, Braintree, Stripe, and Routific

Software Builder, A Great Career Prospect

If you want to get rich as a software builder, almost certainly the best way is to start or join a startup company. The reason is that big company are great for making money, but not so good for making wealth. You can get rich by joining a big company, but it is unlikely that you will ever be among the top few per cent of the wealth holders. For example, suppose you got hired today at Apple Computer. You will probably do well there. Your salary will be high and will probably go up over time. But it is unlikely that your stock options will turn out to be worth anything to speak of.
Is Opting Restaurant App Builder Really Worth of it?

When it comes to your restaurant delivery builder, you have a lot of choices. What can be confusing is deciding which one of the restaurant app builders is best for you and your business. However, the key to making the right decision lies in understanding what your overall purpose is in adopting this type of technology.

Truly, the goal of creating an online ordering system for your restaurant is to create an enjoyable online experience for your customers so they will continue to purchase and be loyal to your brand. The reason for doing this should always be about improving customer satisfaction and not just about saving money on labour or other expenses.

As a suggestion, before making a final decision on any particular ordering system, it is important to consider how these systems are typically rated by customers. Many times customers will complain about poor service even when a company has done everything possible to ensure that their customers are getting exactly what they order. If you have time, visit some websites that rate interactive ordering systems to get an idea of what customers are saying.


Source link

How to add Lottie animations to SwiftUI

Using Lottie animations is an easy and popular way to add animations to your app to have that modern look and feel. All sorts of companies use Lottie animations, from startups all the way to the big boys, such as Google, Microsoft, Spotify, and Netflix to name the few.

Using LottieFiles you have a choice to make your own animations using Lottie Editor, buying animations from creators on Lottie Marketplace or using Free Animations to get LottieFile(s) completely free of charge to add them into you project.



UIKit and SwiftUI interoperability

Unfortunately, Lottie animations cannot be added directly to SwiftUI view without some work prior to that. In order to add Lottie animation to SwiftUI, you need to implement UIViewRepresentable protocol which is a wrapper for a UIKit view that you use to integrate Lottie view into your SwiftUI view hierarchy.



Show me the code

Let’s get straight to the point, just make sure you previously installed lottie-ios library using your preferred package manager, whether it is CocoaPods, Carthage or Swift Package Manager.

Add new file name LottieView and add following contents:

import Lottie
import SwiftUI

struct LottieView: UIViewRepresentable 

    let fileName: String

    private let animationView = AnimationView()

    func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView 
        let view = UIView(frame: .zero)

        animationView.animation = Animation.named(fileName)
        animationView.contentMode = .scaleAspectFill
        animationView.loopMode = .loop

        animationView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(animationView)

        NSLayoutConstraint.activate([
            animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
            animationView.widthAnchor.constraint(equalTo: view.widthAnchor)
        ])

        return view
    

    func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<LottieView>)  

All you need to do know is add following code to your SwiftUI view: LottieView(fileName: "your-file-name") and that’s it, you have fully functioning Lottie animation inside SwiftUI view.



How do I make it to play or pause

In order to make animation play or pause, a bit more coding is required. It is required to provider Coordinator to your LottieView.

What is Coordinator? Let’s see what Apple says:

The system doesn’t automatically communicate changes occurring within your view to other parts of your SwiftUI interface. When you want your view to coordinate with other SwiftUI views, you must provide a Coordinator instance to facilitate those interactions. For example, you use a coordinator to forward target-action and delegate messages from your view to any SwiftUI views.

Let’s see updated code:

import Lottie
import SwiftUI

struct LottieView: UIViewRepresentable 

    let fileName: String
    let isEnabled: Bool

    private let animationView = AnimationView()

    func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView 
        let view = UIView(frame: .zero)

        animationView.animation = Animation.named(fileName)
        animationView.contentMode = .scaleAspectFill
        animationView.loopMode = .loop

        animationView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(animationView)

        NSLayoutConstraint.activate([
            animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
            animationView.widthAnchor.constraint(equalTo: view.widthAnchor)
        ])

        return view
    

    func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<LottieView>) 
        if isEnabled 
            context.coordinator.parent.animationView.play()
         else 
            context.coordinator.parent.animationView.stop()
        
    

    class Coordinator: NSObject 
        var parent: LottieView

        init(_ parent: LottieView) 
            self.parent = parent
        
    

    func makeCoordinator() -> Coordinator 
        Coordinator(self)
    

And this is it! You can now pass isEnabled Bool value to LottieView to make it play or pause.



One final gotcha

If you are using TabView withing your SwiftUI application and you are switching between tabs you will notice that animations won’t start playing automatically when you switch back to view with animations.

All you must do is add animationView.backgroundBehavior = .pauseAndRestore to makeUIView(context:) method. Now animations will pause and restore as the code itself suggests.



Conclusion

Thank you for reading and I hope this article was useful to you! In conclusion, this article went over how to add Lottie animation(s) to SwiftUI view, make it reactive if needed and how to use Lottie animations with TabView.

If you like my content and find it useful, please consider following me here on DEV Community. If you are feeling extra generous, please consider buying me a coffee.

Connect with me on LinkedIn.


Source link

Integrate Firebase Authentication with Google Sign-In to SwiftUI app

SwiftUI framework is already in its third iteration and with that, it is well and truly on its way to production-ready applications. Such applications are certainly going to need some sort of authentication. Since authenticating users can be tricky, you may want to rely on third-party solutions for that, such as Firebase. Question is then, how does one integrate Firebase and Google Sign-In to SwiftUI application?

This article will show you how to create iOS application using SwiftUI, create Firebase project and then use Firebase Authentication to integrate Google Sign-In SDK to your SwiftUI application.

Within this article we will cover following topics:

  • Creation of Firebase project

  • Creation of SwiftUI Lifecycle application

  • Handling dependencies with CocoaPods

  • Handling authentication within our code

  • Designing UI elements



Creation of Firebase project

In order to use Firebase in our SwiftUI app, we need to create new Firebase project in

Firebase console. Create new project by clicking on Add project.

Once Create a project page opens, enter project name.
Screenshot 2021-11-25 at 15.30.35.png

Next step is either enabling or disabling Google Analytics. It is not necessary for this demo, so it’s up to you to enable it.

When project’s Dashboard opens, click on iOS icon.
Screenshot 2021-11-25 at 15.37.28.png

Next, fill out form for registering the app. Apple Bundle ID is important since it needs to be the same as bundle identifier, we will use later in Xcode project. Other two fields are optional. App Store ID is only needed if app will be uploaded to the App Store which we are not doing in this tutorial.

Screenshot 2021-11-28 at 09.40.27.png

Click on Register app.
Next, we need to download GoogleService-Info.plist file which will be added to Xcode project later.

Screenshot 2021-11-25 at 15.45.33.png

In steps 3 and 4 just click Next since we will cover them in more detail later in the tutorial. To finish registering the app, click Continue to console.

Almost finished with setting up Firebase project. Lastly, we need to enable Authentication.

Click on Authentication, and then on Get started.
Screenshot 2021-11-25 at 15.50.15.png

Now choose Google as Sign-in method provider.

Screenshot 2021-11-25 at 15.52.26.png

Finally, enable it by toggling Enable button, add Project public-facing name and Project support email. Save this changes by clicking on Save button.

Screenshot 2021-11-25 at 15.53.33.png

We are done with Firebase settings and now we are moving to actual coding!



Creation of SwiftUI Lifecycle application

Next step is to actually create Xcode project. Open Xcode, select option Create a new Xcode project. Once new window opens, make sure that iOS is selected in header and then select App. Click Next.

Now we need enter some details about project.

  • Product Name: demo
  • Organization Identifier: com.firebase
  • Interface: SwiftUI
  • Language: Swift

Core Data and Tests are not needed for this tutorial, so it is up to you to include them into the project.

Screenshot 2021-11-28 at 09.38.27.png

Click Next and then choose folder where you want to save Xcode project.

Great! We are ready for next section, handling dependencies with CocoaPods.



Handling dependencies with CocoaPods

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. It has over 86 thousand libraries and is used in over 3 million apps. CocoaPods can help you scale your projects elegantly.

To handle project dependencies, this tutorial will use CocoaPods. If CocoaPods is not installed on your development machine, follow this Getting Started guide on official CocoaPods page.

Using Terminal, navigate to your project. Use command similar to this one: cd your/project/path.

Once in your project path, initialize empty pod file by executing pod init command. Open newly created Podfile to add dependencies needed for this project.

Add following content:

target 'swiftui' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for swiftui
  pod 'Firebase/Core'
  pod 'Firebase/Auth'
  pod 'GoogleSignIn'

end

To install these dependencies, execute pod install command.

Awesome! Project setup is done, and its dependencies are successfully installed.



Handling authentication within our code

First step is to take GoogleService-Info.plist file we downloaded it in Creation of Firebase project section and drag&drop it into Xcode project. Once file is added to the project, we need to add REVERSED_CLIENT_ID key to project configuration.



Handling REVERSED_CLIENT_ID key

Do the following:

  1. Open your project configuration: double-click the project name in the left tree view. Select your app from the TARGETS section, then select the Info tab, and expand the URL Types section.

  2. Click the + button, and add a URL scheme for your reversed client ID. To find this value, open the GoogleService-Info.plist configuration file, and look for the REVERSED_CLIENT_ID key. Copy the value of that key and paste it into the URL Schemes box on the configuration page. Leave the other fields blank.
    When completed, your config should look something similar to the following (but with your application-specific values):
    Screenshot 2021-11-27 at 21.45.09.png

Now we can move on to some coding!



Adding AppDelegate

Since iOS 14 and SwiftUI 2.0, Apple added ability to include AppDelegate to SwiftUI Lifecycle app which we will need to add to our project.

Right click on project in Xcode left tree view and then select New file…. Add new Swift file named AppDelegate. Once create, add following contents to the file:

import Firebase
import GoogleSignIn

class AppDelegate: NSObject, UIApplicationDelegate 

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
    ) -> Bool 
        FirebaseApp.configure()
        return true
    

    func application(
      _ app: UIApplication,
      open url: URL,
      options: [UIApplication.OpenURLOptionsKey : Any] = [:]
    ) -> Bool 
        return GIDSignIn.sharedInstance.handle(url)
    



Adding helper functions

For signInWithConfiguration:presentingViewController:callback: method we will use later, we need to provide presenting ViewController and GIDConfiguration configuration thus we need to implement two helper functions.

GIDConfigurationExtensions.swift:

import Firebase
import GoogleSignIn

extension GIDConfiguration 

    /// Get GIDConfiguration instance by providing clientID from GoogleService-Info.plist file
    /// - Returns: GIDConfiguration instance
    static func getGIDConfigurationInstance() -> GIDConfiguration 
        GIDConfiguration(clientID: FirebaseApp.app()?.options.clientID ?? "")
    

UIApplicationExtensions.swift

import UIKit

extension UIApplication 

    /// Get root UIViewController of application. If for whatever reason, UIViewController can not be accessed,
    /// invoke fatalError() since UIViewController instance is crucial for application for work properly.
    /// - Returns: root UIViewController
    static func getRootViewController() throws -> UIViewController 
        let scenes = UIApplication.shared.connectedScenes
        let windowScene = scenes.first as? UIWindowScene
        let window = windowScene?.windows.first

        guard let uiViewController = window?.rootViewController else  fatalError() 
        return uiViewController
    

With this finished, we can move start implementing ViewModel.



Implementing LoginViewModel

Create new Swift file named LoginViewModel.

LoginViewModel:

import Firebase
import GoogleSignIn

final class LoginViewModel: ObservableObject {

    @Published var isUserLoggedIn = false

    func signIn() 
        do 
            let config = GIDConfiguration.getGIDConfigurationInstance()
            let uiViewController = try UIApplication.getRootViewController()

            GIDSignIn.sharedInstance.signIn(with: config, presenting: uiViewController)  user, error in
                guard error == nil else  return 
                guard user != nil else  return 
                self.isUserLoggedIn = true
          
         catch 
            print(error.localizedDescription)
        
    

    func signOut() 
        GIDSignIn.sharedInstance.signOut()
        isUserLoggedIn = false
    
}



Designing UI elements

Now comes last piece of the puzzle. Designing UI elements using SwiftUI framework and connecting UI with business logic we implemented earlier.



LoginView

Create new SwiftUI View file named LoginView.

LoginView:

import SwiftUI

struct LoginView: View {

    @EnvironmentObject var viewModel: LoginViewModel

    var body: some View 
        VStack 
            Spacer()

            Button(action: 
                withAnimation 
                    viewModel.signIn()
                
            ) 
                HStack 
                    Text("Sign in with google")
                        .fontWeight(.bold)
                
            
            .foregroundColor(.white)
            .padding()
            .frame(maxWidth: .infinity)
            .background(.black)
            .cornerRadius(12)
            .padding()

            Spacer()
        
    
}

struct LoginView_Previews: PreviewProvider 
    static var previews: some View 
        LoginView()
    

LoginView will look something like this:

Simulator Screen Shot - iPhone 12 - 2021-11-28 at 10.41.25.png



HomeView

Create new SwiftUI View file named HomeView.

HomeView:

import GoogleSignIn
import SwiftUI
import SDWebImageSwiftUI

struct UserDetailView: View 

    let user: GIDGoogleUser?

    var body: some View 
        VStack 
            HStack 
                Text(user?.profile?.name ?? "")
                    .bold()
                    .font(.title2)

                Spacer()

                WebImage(url: user?.profile?.imageURL(withDimension: 75))
                    .resizable()
                    .placeholder(
                        Image(systemName: "person.fill")
                    )
                    .indicator(.activity)
                    .transition(.fade(duration: 0.5))
                    .frame(width: 75, height: 75, alignment: .center)
                    .scaledToFit()
                    .clipShape(Circle())
            
            HStack 
                Text(user?.profile?.email ?? "")
                    .bold()
                    .font(.subheadline)
                Spacer()
            

            Spacer()
        
        .padding()
        .frame(height: 150, alignment: .center)
        .background(.thickMaterial)
        .cornerRadius(12)
    


struct HomeView: View {

    @EnvironmentObject var viewModel: LoginViewModel
    private let user = GIDSignIn.sharedInstance.currentUser

    var body: some View 
        VStack 
            UserDetailView(user: user)

            Spacer()

            Button(action: 
                withAnimation 
                    viewModel.signOut()
                
            ) 
                HStack 
                    Text("Sign out")
                        .fontWeight(.bold)
                
            
            .foregroundColor(.white)
            .padding()
            .frame(maxWidth: .infinity)
            .background(.black)
            .cornerRadius(12)
            .padding()
        
        .padding()
    
}

struct HomeView_Previews: PreviewProvider 
    static var previews: some View 
        HomeView()
    

HomeView will look something like this:

Simulator Screen Shot - iPhone 12 - 2021-11-28 at 10.41.52.png



Connecting all together

All that is left to do is to connect it all together in DemoApp and ContentView.

DemoApp:

import SwiftUI

@main
struct DemoApp: App 

    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    @StateObject var viewModel = LoginViewModel()

    var body: some Scene 
        WindowGroup 
            ContentView()
                .environmentObject(viewModel)
        
    

ContentView:

import SwiftUI

struct ContentView: View 

    @EnvironmentObject var viewModel: LoginViewModel

    var body: some View 
        if viewModel.isUserLoggedIn 
            HomeView()
         else 
            LoginView()
        
    


struct ContentView_Previews: PreviewProvider 
    static var previews: some View 
        ContentView()
    

This is it! Integration of Firebase Authentication with Google Sign-In to SwiftUI application is done and our project is ready to be run on emulator or physical device!



Conclusion

Thank you for reading and and I hope this article was useful for you since integrating Firebase Authentication with SwiftUI Lifecycle application is not exactly straightforward.

If you like my content and find it useful, please consider following me here on Hashnode. If you are feeling extra generous, please consider buying me a coffee.

Connect with me on LinkedIn.


Source link

Fetch and display the latest git commit hash in your iOS apps

If you want to know from what exact commit your app is built you can include the latest git commit hash to the place where you display the app version. I like to call that generated hash “revision” or in short “rev”.

Displaying this can be useful when you are distributing internal versions of your apps to QA engineers and you want to know on what app version they are testing. While the changes are coming in on development branches we don’t increase version or build numbers, we follow the revision value and always know what version is in use.

In this article I will explain how to fetch the latest git commit hash in Xcode and display it in the iOS app.



Fetching the latest git commit hash

The procedure I will describe adds a new row to your Info.plist file with specified key and sets the value to the short git commit hash.

The first step is to go to your target’s Build phases setting and add a new run script phase. The “Run script” action will be on the bottom and you need to move it above the “Copy bundle resources” action.

When you move it, you can paste this code for the script:

GIT=`xcrun -find git`
GIT_REV=`$GIT rev-parse --short HEAD`
/usr/libexec/PlistBuddy -c "Set :REVISION $GIT_REV" "$SRCROOT/path-to-your-info.plist-file"

In the script above we rely on PlistBuddy to set the key REVISION and the value of the latest git commit hash to the app’s Info.plist file. PlistBuddy is a macOS utility that helps us to manage plist files. You can read more about it here or you can type /usr/libexec/PlistBuddy -h in your terminal to find out more of what it can do.

Now, when you have run the build process, the script that we added should’ve inserted a new entry in your Info.plist file and we can proceed to displaying it.



Displaying the revision

To display the revision we just need to fetch our Info.plist and provide a key to read the value from it:

let revision = Bundle.main.object(forInfoDictionaryKey: "REVISION") as? String 

In Objective-C we would do it like this:

NSString *revision = [NSBundle.mainBundle objectForInfoDictionaryKey:@"REVISION"];

Source link

SOLID Principles in iOS Development



SOLID Principles in iOS Development



😩 Ok, you probably already hear this term, but in practice, what’s mean? When uses? How uses? Keep reading for FINALLY LEARN

Alt Text



First of all, SOLID is a s a mnemonic acronym for five design principles intended to make software design more understandable, flexible, and maintainable



In all tutorial, i will show SOLID Principles in action and codes that don’t follow SOLID



So, let’s go 😁



S – Single Responsibility Principle



A classe should have one reason to change ( to exists )



Tips to apply

  • Ask yourself for every entity ( classes / functions ) : this entity, does more than one thing?

  • You shouldn’t have use the word and when have to talk the responsibility to entity



💢 NOT Single Responsibility Principle apply

class Handler_NOT_SOLID 

    func handle()  

        let data = requestDataToAPI()
        guard let dataReceive = data else  return 
        let array = parse(data: dataReceive)
        saveToDB(array: array)

    

    private func requestDataToAPI() -> Data?
        // send API request and wait the response
        return nil
    

    private func parse(data:Data)->[String]?
        // parse the data and create an array
        return nil
    

    private func saveToDB(array:[String]?)
        // save array in a database
    

Can you see?



Handler_NOT_SOLID class have several responsibilities

  1. Send request to API
  2. Create an array with data receive
  3. Save array in a database



👍 Single Responsibility Principle apply

class Handler_SOLID 

    let apiHandler: APIHandler
    let parseHandler: ParseHandler
    let dbHandler: DBHandler

    init(apiHandler: APIHandler, parseHandler: ParseHandler, dbHandler: DBHandler) 
        self.apiHandler = apiHandler
        self.parseHandler = parseHandler
        self.dbHandler = dbHandler
    



class APIHandler 

    func requestDataToAPI() -> Data?
        // send API request and wait the response
        return nil
    


class ParseHandler 
    func parse(data:Data) -> [String]?
        // parse the data and create an array
        return nil
    


class DBHandler 
    func saveToDB(array:[String]?)
        // save array in a database
    


Now, each entity have just one responsibility



O – Open/Closed Principle



A software entity should be open to extension, but closed for modification.



Tips to apply

  1. If you want to modify a class every time a new behavior is added, something isn’t quite right
  2. If/else/switch statements don’t be used to modify a behavior



💢 NOT Open/Closed Principle apply

class Vehicles_NOT_SOLID 

    func printData() 
        let cars = [
            Car_NOT_SOLID(name: "Batmobile", color: "Black"),
            Car_NOT_SOLID(name: "SuperCar", color: "Gold"),
            Car_NOT_SOLID(name: "FamilyCar", color: "Grey")
        ]

        cars.forEach  car in
            print(car.printDetails())
        

        let buses = [
            Bus_NOT_SOLID(type: "School bus"),
            Bus_NOT_SOLID(type: "Minibus"),
            Bus_NOT_SOLID(type: "Minicoach")
        ]

        buses.forEach  bus in
            print(bus.printDetails())
        
    



class  Car_NOT_SOLID 
    let name:String
    let color:String

    init(name: String, color: String) 
        self.name = name
        self.color = color
    

    func printDetails() -> String 
        return "name : (name) color :(color)"
    




class Bus_NOT_SOLID 
    let type:String

    init(type: String) 
        self.type = type
    

    func printDetails() -> String  
        return "bus type : (type)"
    


Can you see?



When printData receive other type of object, we have to add more rules to work

If you want to add the possibility to print also the details of a new class, we should change the implementation of printData every time we want to log a new class



👍 Open/Closed Principle apply

protocol Printable 
    func printDetails() -> String


class Vehicles_SOLID 

    func printData() 
        let cars:[Printable] = [
            Car_SOLID(name: "Batmobile", color: "Black"),
            Car_SOLID(name: "SuperCar", color: "Gold"),
            Car_SOLID(name: "FamilyCar", color: "Grey"),

            Bus_SOLID(type: "School bus"),
            Bus_SOLID(type: "Minibus"),
            Bus_SOLID(type: "Minicoach")
        ]

        cars.forEach  car in
            print(car.printDetails())
        
    


class Car_SOLID:Printable 
    let name: String
    let color: String

    init(name: String, color: String) 
        self.name = name
        self.color = color
    
    func printDetails() -> String 
        return "name : (name) color :(color)"
    



class Bus_SOLID: Printable 
    let type: String

    init(type: String) 
        self.type = type
    

    func printDetails() -> String 
        return "bus type : (type)"
    

We don’t need change behavior of printData, just make a layer between printData and the class



L – Liskov Substitution Principle



Objects should be replaceable with instances of their subtypes without altering the correctness of that program.



Tips to apply

  1. Instead of one monolithic interface, break an interface up based on what implementers should be doing
  2. Keeps consumers from having to much power



💢 NOT Liskov Substitution Principle apply

class Rectangle_NOT_SOLID 
    var width: Double = 0
    var height: Double = 0

    var area: Double 
        return width * height
    




class Square_NOT_SOLID: Rectangle_NOT_SOLID 
    override var width: Double 
        didSet 
            height = width
        
    


// MARK: - Implementations 
 func printArea(of rectangle: Rectangle_NOT_SOLID) 
     rectangle.width = 10
     rectangle.height = 4

     print(rectangle.area)
 

 let rect = Rectangle_NOT_SOLID()
 printArea(of: rect) // 40
 let square = Square_NOT_SOLID()
 printArea(of: square ) // 40

See that printArea(of rectangle:Rectangle_NOT_SOLID) return the same result with different types instead return specific value of each class



👍 Liskov Substitution Principle apply

protocol Polygon 
    var area :Double  get 


class Rectangle_SOLID: Polygon 

    let width:Double
    let height:Double

    init(width: Double, height: Double) 
        self.width = width
        self.height = height
    

    var area: Double 
        return width * height
    



class Square_SOLID: Polygon 
    let side:Double

    init(side: Double) 
        self.side = side
    

    var area: Double 
        return pow(side, 2)
    


/// MARK: - Implementations  

 func printArea(of polygon:Polygon)
     print(polygon.area)
 

 let rect = Rectangle_SOLID(width: 10, height: 40)
 printArea(of: rect) // 400.0
 let square = Square_SOLID(side: 10)
 printArea(of: square) // 100.0



I – Interface Segregation Principle



(M)any client-specific interfaces are better than one general-purpose interface



Tips to apply

  1. Instead of one monolithic interface, break an interface up based on what implementers should be doing
  2. Keeps consumers from having to much power



💢 NOT Interface Segregation Principle apply

//MARK:- Fat Interface (Protocol)
protocol GestureProtocol 
    func didTap()
    func didLongPress()
    func didSwipe()


class RichButton_NOT_SOLID: GestureProtocol 

    func didTap() 
        print("tap button")
    

    func didLongPress() 
        print("long press")
    

    func didSwipe() 
        print("swipe")
    



class PoorButton_NOT_SOLID: GestureProtocol 
    func didTap() 
        print("tap")
    

    func didLongPress() 

    func didSwipe() 


See that PoorButton_NOT_SOLID class have methods that not are usable



👍 Interface Segregation Principle apply

protocol TapGesture 
    func didTap()


protocol LongPressGesture 
    func didLongPress()


protocol SwipeGesture 
    func didSwipe()


class RichButton_SOLID: TapGesture, LongPressGesture, SwipeGesture

    func didTap() 
        print("tap button")
    

    func didLongPress() 
        print("long press")
    

    func didSwipe() 
        print("swipe")
    





class PoorButton_SOLID: TapGesture 
    func didTap() 
          print("tap button")
      


Now we remove all unnecessary methods



D – Dependency Inversion Principle



High-level modules should not depend on low-level modules. Both should depend on abstractions.



Tips to apply

  1. We’re used to this : High level -> (uses) Low level
  2. High level -> (expects) interface <- ( fulfills ) low level



💢 NOT Dependency Inversion Principle apply

class SaveData_NOT_SOLID 

    let filesSystemManager = FilesSystemManager_NOT_SOLID()

    func handle(data:String)
        filesSystemManager.save(data: data)
    


class FilesSystemManager_NOT_SOLID 

    func save(data:String)
        // save data
    

With this, we have just a way to save Data. If we want use any DataBase?



👍 Dependency Inversion Principle apply


protocol Storage 
    func save(data:Any)


class SaveData_SOLID 
    let storage:Storage

    init(storage: Storage) 
        self.storage = storage
    

    func handle(data: Any)
        self.storage.save(data: data)
    


class FilesSystemManager_SOLID: Storage 
    func save(data: Any) 


class MySQLDataBase: Storage 
    func save(data: Any) 

Now, we can use any storage method

👊 Thanks for read!! I hope that you have understand all principles about SOLID and how apply in your day by day for build a better software. In doubt, please put your comment below and i will try to help.

Github Project


Source link

The Holy Grail of UIKit: Delegate Pattern

When I started learning to develop apps for iOS I stumbled upon the delegate pattern for the first time. Adopting UITableViewDataSource and UITableViewDelegate protocols felt very strange and confusing.

Why am I doing this? Is this really how to do these things? I asked myself.

After a couple of weeks of learning and reading materials, I clicked and really started to enjoy using this pattern.



What is it?

According to Apple:

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases, it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.

This is a very good definition. But let’s take it step by step by following the illustration below.

  1. Someone creates a Worker. A Worker is someone who does the work and then notifies us when the work is completed or when something is needed to continue the work.
  2. We tell the worker: “This is your delegate. Ask it for something or notify it when you are done.”. That depends on the language that is known between the worker and its delegate. This is always known upfront.
  3. The Worker starts to work.
  4. While the Worker is working it needs some data to continue its work. The worker asks its delegate “How should I do this or that?” and the delegate knowing what the worker needs provides it. When the Worker finishes the work it can tell its delegate “I finished the work and here are the results!”.

This is how the delegate pattern works. The communication flow is always 1-to-1 between the delegate and the worker.

The worker is always doing the same job, but by providing different data and reacting differently on work completions we can reuse the worker in a lot of places where we need to handle the different cases.

Delegation works great when there is a clear relationship between the owner and the “Worker”. For other cases, you will want to resort to other patterns.

I would also like to repeat that the worker knows what to send or request from the delegate.



Translating this into code

After we’ve covered the basics with the theory we will try to translate this into code. I will be using Swift to implement this pattern.



Define the protocol

We should always start with the delegate protocol, the interface or the language that will the delegate adopt and that the worker will know in advance.

protocol WorkerDelegate: AnyObject 
    func didFinishWork()

I declared WorkerDelegate protocol that has one method for this example and that is didFinishWork(). When the worker completes the work it will use the delegate that has conformance to WorkerDelegate protocol and will call the didFinishWork() method on it.



AnyObject

You can notice that the WorkerDelegate protocol conforms to another one and that is AnyObject. We use AnyObject to limit that only class types can inherit our delegate protocol. Only class objects can be weak because they are passed by reference and we want weak delegates so that we don’t create retain cycles while using delegates.



Define the worker

class Worker 
    weak var delegate: WorkerDelegate?

    func startWork() 
        // Start some work..
        //
        //
        // .. and when it is completed, notify the delegate:
        delegate?.didFinishWork()
    

The Worker class has a property delegate that is of type WorkerDelegate. It has a weak reference to something that will be stored in this variable and that is, as I mentioned above to avoid creating potential retain cycles. The delegate is also optional so by default it is nil. This is useful in some cases where setting the delegate is not mandatory.

The Worker has a startWork() method that will start some work and when the work is completed it will notify its delegate by invoking the didFinishWork() method if the delegate is set.



Create the worker and adopt the WorkerDelegate

class ViewController: UIViewController 

    private let worker = Worker()

    override func viewDidLoad() 
        super.viewDidLoad()

        // It is always important to set the delegate before we invoke the worker to start doing something.
        // Better alternative could be to pass the delegate in the initializer of the Worker.
        worker.delegate = self

        worker.startWork()
    


extension ViewController: WorkerDelegate 

    func didFinishWork() 
        // Worker finished the work. Now we can react to it by fetching some data or updating the UI.
    

The ViewController has a worker property. In the viewDidLoad() lifecycle method of the ViewController, we set the delegate of the worker to self, so that when the worker is done it will notify the ViewController instance. After setting the delegate, we invoke the startWork() method of the worker and we wait for it to complete to notify us via the didFinishWork() method that we conformed to via WorkerDelegate.

I always like to conform to different protocols in the extensions of the classes because it improves the organisation and the readability of the code.



Examples from UIKit

While working with UIKit we use delegates on daily basis so this is why it is very important to understand this pattern. A good tip for you is when you need to conform to some delegate protocol is to open the protocol definition and see what it has to offer.

Here are a couple of examples:



UITableViewDataSource

We use UITableViewDataSource to provide the UITableView with data. A data source object responds to data-related requests from the table. The minimum for every UITableView that we need to do is to provide it with the numbers of rows per section and to provide UITableViewCell for every row. We do that by implementing methods from the UITableViewDataSource protocol:

// Return the number of rows for the table. We'll assume that the table has only one section.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
   return items.count


// Provide a cell object for each row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
   // Fetch a cell of the appropriate type
   let cell = tableView.dequeueReusableCell(withIdentifier: "cellTypeIdentifier", for: indexPath)

   // Configure the cell using items[indexPath.row]

   return cell

In this example we can see how the UITableView asks us (the data source delegate) for data that it will display.



UITableViewDelegate

With UITableViewDelegate we can react to some interactions with the UITableView. In the example below we can override the didSelectRowAt delegate method so that we get notified when user presses the UITableView row.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
    // React to the selection of the cell at the indexPath

UITableViewDelegate can also be used for more advanced UITableView customization.



MFMailComposeViewControllerDelegate

If we want to use native system UI and configuration to send an email we can use MFMailComposeViewController. We will create the instance of MFMailComposeViewController, configure it, adopts its delegate and send the email. The email completion will be delegated to us in the delegate method below that we implemented by overriding MFMailComposeViewControllerDelegate:

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) 
  // React to mail sending completion

From here we can see if the email sending was successful or not and react according to that information.



UIImagePickerControllerDelegate

If you want to use some images or videos from the Photos app you possibly implemented UIImagePickerController and conformed to its protocol so that you know when the user picked the media files.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) 
  // Use picked images or videos



Conclusion

The delegate pattern is very popular in the iOS world and it is very present in UIKit. I like this pattern and I use it in my work but it has some limitations. The communication is always 1-to-1 and that is not practical in some cases so we need to resort to something like an Observer pattern. The amount of code that needs to be added is not small if we are developing something trivial and the testing is harder.

Alternative to using delegates can be passing functions to “Workers” and invoking them when we need something or when we want to notify someone. This can result in fewer lines of code but can complicate things if we overuse it. We would also need to be careful not to create retain cycles with this approach.

I hope that this article helped you to understand or to strengthen your knowledge with this pattern.


Source link

Learn With Me:Apple's Swift Literals

Hello guys and Welcome to Learn With Me: Apple’s Swift.In previous tutorial you learned about Variables and Constants and today we are going to learn about Literals .So without wasting time let’s start.



Literals

Literals are representations of fixed values in a program. They can be numbers, characters, or strings, etc. For example, “Hello, World!”, 12, 23.0, “C”, etc.
Swift supports 4 types of
literals,that are:
Integer Literals
Floating-point Literals
Boolean Literals
String and Character Literals.
So let’s study about them in brief.



Integer Literals

Integer literals are those that do not have a fractional or an exponential part.

There are four types of integer literals in Swift:
•A decimal number, with no prefix.
•A binary number, with a 0b prefix.
•An octal number, with a 0o prefix.
•A hexadecimal number, with a 0x prefix.



Floating-Point Literals

Floating-point literals are numeric literals that have floating decimal points or they are in fraction. For example,

let radius:Float=7.008

Here,7.008 is a floating-point literal assigned to the radius constant.



Boolean Literals

There are only two Boolean Literals:true and false.
For example,

let pass:Bool=true



Character Literals

Character literals are Unicode characters enclosed in double quotes.For example,

let char:Character="S"



String Literals

String literals are sequences of characters enclosed in double quotes.For example,

let name:String="Jonathan"



Conclusion

Thanks for reading.I hope you will enjoy learning it.If you have any issues then let me know in the discussions.And in next part we are going to learn about Data Types in Swift.


Source link