Showing posts with label iPad. Show all posts
Showing posts with label iPad. Show all posts

Thursday, May 24, 2018

Typical iOS practical test - interview

In this tutorial we will learn how to make an App quickly in practical interview test and stand out of crowd by doing some extra good code. Here is a list of things you could learn from this code base.

  • use of closures
  • lazy loading of images using OperationQueue
  • lazy variable use
  • unit test case writing
  • protocol use in swift
  • DispatchQueue  async use
  • class extension
  • Custom UITableViewCell
  • operationQueue handling
  • use of generics
  • subclass use of Operation
  • decodable and decoder use- Easy way to parse JSON
  • use of Url session
  • overriding of methods and variables
  • enum creation and use.


Here is the final output of this tutorial.



Lets start coding.
Here is a link which we are going to parse. It has list of top free apps from the iTunes app store. So here you can see the data which we need is in array called "Results" and that is under dictonary with key "Feed". we are going to parse and build the array of result array.



So we have a view-controller with Tableview and custom cell to show the image and text details of the app. we take UINavigationController and set our viewcontroller as root viewcontroller. In viewcontroller we have tableview and custom cell which has two labels, UIImageView and one activity indicator.


Now we need one ViewModel as middle to communicate with our model and update ourUI. ViewModel is requesting for the data to model and will be holding the result along with model object. Here you see ViewModel is actually cleaver than view-controller and our vc is dumb, but filled with all the equipments it requires. here you see viewmodel is actual  mind of our viewcontroller and control every aspect of data.


Now its time to create a model it actually holds the actual business logic and understanding what and how to call the web service, using which class too. after that it parse the result using jsonparse class which is leveraging two new swift features. one is generics and other is decodable.





Now to create request we have one class as RederRequest and it has actual url path where we need to connect at this point of time we do not require to send any data, if we need that that we can add that in the same class under url content function.


Decodable is useful to convert the response to data-class. Here AppList is a data class or entity and there is no need to map using 'valueForKey:'


We get the response and in response we have url of app image instead of actual image so we will implement lazy loading using operation to download the image. First we will ask for the images which are currently visible on the UI. And as user moves to new list we will ask for that images.
Here is a code of image downloader to download the image asynchronous. We will call this code from model to download.


This is the implementation of ImageDownloader class it download images and save as data in the AppInfo object and update the status of image.



Now Lets move to XCTest cases.
Here we will write some test cases. There are two functions written to cover the code and once we run it we can see how much code is actually covers.


Check the code coverage image where you can see some number highlighted in right side it shows how many times this code ran last time. 'appdescription' function has been called 19 time last time the code executed.


This is the find consolidated coverage of our app it is actually around 74%. An app should have at least 80% of coverage to cover all major scenarios. we are short to 6%.

Download full code from Github https://github.com/it-sam/iOS-practical

Thursday, July 13, 2017

VIPER- Class binding using Protocol

In last post we have seen how to bind all classes together. In this post we would see app flows from view controller to interactor and to view controller.To make it more decoupled we would generate some protocols and implement it in classes.

Step:1 list-ViewController
Architecting iOS Apps with VIPER - App event flow in VIPER
override func viewDidLoad() {
        super.viewDidLoad()
        DispatchQueue.global().async {
            self.eventHandler?.updateView()
        }
    }

Step:2 list-Presenter
Architecting iOS Apps with VIPER - App event flow in VIPER

func updateView() {
        listInteractor?.findListData()
    }

Step:3 list-Interactor
Architecting iOS Apps with VIPER - App event flow in VIPER


func findListData() {
        //Find data
        //output?.foundListData(aList: nil);
        let reader = FileReader()
        if let data = reader.readJsonFile(name: "company") {
            let myArr:NSArray? = ParseData(aObject: data)
            if myArr != nil {
                output?.foundList(aList: myArr);
            }
        }
    }

Step:4 list-Presenter
Architecting iOS Apps with VIPER - App event flow in VIPER

func foundList(aList:NSArray?) {
        let sortedArray:NSArray? = self.SortCompanyList(aList: aList)
        if(sortedArray != nil) {
            userInterface?.reloadList(alist: sortedArray)
        }
        else {
            userInterface?.showNoContenctView()
        }
    }

Protocols:
1) ViewController Interface:
Implemented   by ViewController
Object owned by Presenter
Architecting iOS Apps with VIPER - Protocol binding in VIPER

protocol listViewInterface {
    func showNoContenctView()
    func reloadList(alist:NSArray?)
}
*********************************************************
class ViewController: UIViewController,listViewInterface
 {
  //MARK: listViewInterface methods implementation
    func reloadList(alist:NSArray?) {
        //reload table view
    }
    func showNoContenctView() {
     //Show alert code
    }
 }
*********************************************************
class listPresenter: NSObject {
    var userInterface:listViewInterface?
}

2) Presenter Interface:
Implemented by Presenter
Object owned by ViewController
Architecting iOS Apps with VIPER - Protocol binding in VIPER

protocol listPresenterInterface {
    func updateView();
}
*********************************************************
class listPresenter: NSObject,listPresenterInterface {
    var userInterface:listViewInterface?
    func updateView() {
        //Call for data adjustment and interactor calling
    }
}
*********************************************************
class ViewController: UIViewController,listViewInterface {
   var eventHandler:listPresenterInterface?
   override func viewDidLoad() {
     super.viewDidLoad()
     self.eventHandler?.updateView();
   }

   //MARK: listViewInterface implementation
    func reloadList(alist:NSArray?) {
        //reload table view
    }
    func showNoContenctView(){
        //Show alert code
        }
 }


3) Interactor Input Interface:
Implemented   by interactor
Object owned  by presenter
Architecting iOS Apps with VIPER - Protocol binding in VIPER

protocol listInteractorInput {
    func findListData()
}
*********************************************************
class listInteractor: NSObject,listInteractorInput {
    func findListData() {
        //Find data
    }
*********************************************************
class listPresenter: NSObject,listPresenterInterface {
    var listInteractor:listInteractorInput?
    func updateView() {
     //Code for data adjustment and interactor calling
     listInteractor?.findListData();
    }
}

4) Interactor output Interface:
Implemented   by presenter
Object owned  by interactor
Architecting iOS Apps with VIPER - Protocol binding in VIPER

protocol listInteractorOutput {
    func foundList(aList:NSArray?)
}
*********************************************************
class listPresenter: NSObject,listPresenterInterface,listInteractorOutput {
    var listInteractor:listInteractorInput?
    var userInterface:listViewInterface?
    
    func updateView() {
        listInteractor?.findListData();
    }
    func foundList(aList:NSArray?) {
       userInterface?.reloadList(alist: sortedArray);
    }
}
*********************************************************
class listInteractor: NSObject,listInteractorInput {
    var output:listInteractorOutput?
    func findListData() {
        //Find data
    }
}

Note:Presenter is implementing two protocols.
This is the end of the post. In next post we will see how VIPER is useful for testing and coverage.

Thursday, July 6, 2017

VIPER: Router and wireframe - Class binding

We will see binding of all classes.Let us bind for list view.

Here is a list of classes with whom we are going to interact.
AppDelegate – Standard UIApplicationMain default class.
AppDependencies – A class which has methods to bind all classes.
Root-wireframe - A class which has all possible kind of transition code. (like push, pop, present etc.) List-wireframe - A class knows how to show its UI and all possible forward flow.

And other all classes that we have seen previous are presenter, interactor, view controller and entity. Here is a step by step process to bind all the classes.

Step:1 class name: AppDelegate We create object of dependency class.
Architecting iOS Apps with VIPER

let appDependencies = AppDependencies()

Step:2 class name: AppDelegate, With dependency class we call its method.
Architecting iOS Apps with VIPER


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let wireframe = appDependencies.configureDependencies()
        return true
    }

Step:3 class name: AppDependencies  In dependency class we can put all shared instance object and other objects we put it in a method.
Architecting iOS Apps with VIPER

class AppDependencies {
    let rootWireFrame = RootWireframe()
    //this is the root object so we need to create here, others go to their own function
    //return value could be replaced with wireframe object

    func configureDependencies() -> listWireFrame {
        let listWireframe = listWireFrame()

        listWireframe.rootWireframe = rootWireFrame
        return listWireframe
    }
}

Step:4 class name: AppDependencies
Architecting iOS Apps with VIPER

func configureDependencies() -> listWireFrame {
        let listWireframe = listWireFrame()
 let Presenter = listPresenter()

 listWireframe.rootWireframe = rootWireFrame
 listWireframe.listPresenter = Presenter
 return listWireframe
}

Step:5 class name: AppDependencies
Architecting iOS Apps with VIPER

func configureDependencies() -> listWireFrame {
        let listWireframe = listWireFrame()
        let Presenter = listPresenter()
        let Interactor = listInteractor()
        
        listWireframe.listPresenter = Presenter
        Presenter.listInteractor = Interactor
        return listWireframe
    }

Step:6 AppDependencies
Architecting iOS Apps with VIPER

func configureDependencies() -> listWireFrame {
        let listWireframe = listWireFrame()
        let Presenter = listPresenter()
        let Interactor = listInteractor()
        
        listWireframe.listPresenter = Presenter
        Presenter.listInteractor = Interactor
        Interactor.output = Presenter
        listWireframe.rootWireframe = rootWireFrame
        return listWireframe
    }

Step:7 class name: AppDelegate
Architecting iOS Apps with VIPER

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let wireframe = appDependencies.configureDependencies()
        wireframe.presentListInterfaceFromWindow(window: window!)
        return true
    }

class name: list-wireframe
func presentListInterfaceFromWindow(window: UIWindow) {
        let viewController = listViewControllerFromStoryboard()
        viewController.eventHandler = listPresenter
        listVC = viewController
        listPresenter!.userInterface = viewController
        rootWireframe?.showRootViewController(viewController: viewController, inWindow: window)
    }

Step:8 class name: list-wireframe
Architecting iOS Apps with VIPER

func presentListInterfaceFromWindow(window: UIWindow) {
        let viewController = listViewControllerFromStoryboard()
        viewController.eventHandler = listPresenter
        listVC = viewController
        listPresenter!.userInterface = viewController
        rootWireframe?.showRootViewController(viewController: viewController, inWindow: window)
    }

Here is a full flow of binding of all classes.
Architecting iOS Apps with VIPER



Tuesday, February 23, 2016

An open-sourced iOS imgur api example - GitHub

Imgur is the best place to share and enjoy the most awesome images on the Internet. Every day, millions of people use Imgur to be entertained.


Here is all the information for its API and to start all you need is API key.

Here are the required thing to learn to use Imgur API.









You can Download Full code From GitHUB

Sunday, November 1, 2015

Colour-Memory 4*4 grid project

The goal of this work sample is to construct a sample memory game called ”Colour Memory”. The game board consists of a 4x4 grid with 8 pairs of color cards.

 Here is a list of things I used to create this sample.

1) Use of sqlite database  and interaction class 
2) subclassing of UITableViewCell
3) subclassing of UIButton
4) Use of Auto Layout in iOS


UIButton subclassing is used to store the state of that button
and used to store the image name that we need to set as a image when user taps on that button.
It also contain animation code of flip view from left to right and right to left.
Here is a code to flip the UIButton and show image.

You can find this code in below given link.
Name of the file is ColorUIButton
 -(void)showButtton  
 {  
 self.userInteractionEnabled = false;  
 [UIView transitionWithView:self duration:0.3 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{  
 //code to change the image of UIButton  
 } completion:^(BOOL finished) {  
 self.userInteractionEnabled = true;  
 }];  
 }  







UITableViewCell is used to handle the row of 4 UIButtons
 It handle all the interaction done on UIButton.

You can find this code in below given link.
Name of the file is ColorCell


















Download full code from GitHub

Saturday, October 31, 2015

Twitter Integration in iOS

Twitter Integration using SLRequest 

 1) Ask user to access its twitter account

  ACAccountStore *accountStore = [[ACAccountStore alloc] init];  
   ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];  
   [accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {  
     if(granted) {  
            //User allowed to access account  
     }}];  

2) Get all twitter accounts from list

 ACAccountStore *store = [[ACAccountStore alloc] init];  
   ACAccountType *AccountType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];  
  NSArray *accountsArray = [store accountsWithAccountType:AccountType];  

3)get particular Account from Accounts array.

 -(ACAccount *)getTwitterAccount:(NSString *)aStrUserName  
 {  
   ACAccountStore *store = [[ACAccountStore alloc] init];  
   ACAccountType *AccountType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];  
   __weak ACAccount *selAccount = nil;  
   NSArray *accountsArray = [store accountsWithAccountType:AccountType];  
   for (ACAccount *myaccount in accountsArray) {  
     if([myaccount.username.lowercaseString isEqualToString:aStrUserName.lowercaseString])  
     {  
       selAccount = myaccount;  
       break;  
     }  
   }  
   return selAccount;  
 }  

Thursday, October 29, 2015

How to add image in UINavigationBar in iPhone app

How to add image in UINavigationBar in iPhone app

 +(void)setNavigationBarAppearance{  
   [[UINavigationBar appearance]setBackgroundImage:[UIImage imageNamed:@"image name.png"] forBarMetrics:UIBarMetricsDefault];  
   [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:  
                              [UIColor whiteColor], NSForegroundColorAttributeName,  
                              [UIFont fontWithName:@"Font name" size:17.0], NSFontAttributeName,nil]];  
 }  

To set title view of UINavigationBar use below code

 viewController.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage.png"]];  


How to disable back swipe gesture in UINavigationController on iOS
From iOS 7 Apple added a new default navigation behavior. You can swipe from the left border of the screen to go back on the navigation stack.
So, It is possible to disable this new gesture in UINavigationController.
Just add this online code and thats it.

  if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])  
     [self.navigationController.view removeGestureRecognizer:self.navigationController.interactivePopGestureRecognizer];  

OR

  if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])  
   self.navigationController.interactivePopGestureRecognizer.enabled = false;  


The edgesForExtendedLayout property, together with the extendedLayoutIncludesOpaqueBars property, determines whether or not view controllers' views underlap top and bottom bars (navigation bar, toolbar)
Extenedges- iOS
This is useful when you are using Storyboard and UINavigationBar & you want to start counting frame after UINavigationBar ends with autolayout.
so just select checkbox of Extenedges - Under top bars and thats it.