Showing posts with label objectivec. Show all posts
Showing posts with label objectivec. Show all posts

Monday, November 20, 2017

iOS Checking device is in 24 hour format or not

We need to check the device time format and display time stuff accordingly in the app.

12-hour format

Added to Shopping cart at 01:00 PM

24-hour format 

Added to Shopping cart at 13:00

Objective C



  + (BOOL)isDeviceIn24HoursFormat {

     NSString *dateFormat = [NSDateFormatter 
           dateFormatFromTemplate:@"j" options:0 locale:     
                              [NSLocale currentLocale]];

     if ([dateFormat rangeOfString:@"a"].location == 
                                                           NSNotFound) {
        return YES;
     }

     return NO;

  }




Swift


  func isDeviceIn24HoursFormat() -> Bool {

        let dateFormat: String? = 
                    DateFormatter.dateFormat(fromTemplate: 
                       "j", options: 0, locale: NSLocale.current) 

        if ((dateFormat as NSString?)?.range(of: "a"))?.location 
                                                            == NSNotFound
        {
            return true
        }

        return false
    }
 }



12-hour format    dateFormat  =  "h a"
24-hour format    dateFormat  =  "HH"


Hope this post is useful. Feel free to comment incase of any queries.




Displaying URL loading error in WebView in HTML format

When we are displaying a portal in web view, Sometimes it may fail to load the url.

This could be because of,

  1. No internet connection in the device
  2. Timeout
  3. Server is not reachable/responding

And there could be many other reasons.

Instead of displaying that Error in an alert, we can directly display that error description in the UIWebView in a HTML format.

Whenever UIWebView fails to load a page, UIWebViewDelegate method will get called.

-----------------------------------------------------------------------------------

- (void)webView:(UIWebView *)webView 
                   didFailLoadWithError:(NSError *)error {


 }

-----------------------------------------------------------------------------------

From this we can fetch the error and display the description using the loadHTMLString method of UIWebView.


--------
---------------------------------------------------------------------------

- (void)webView:(UIWebView *)webView 
                     didFailLoadWithError:(NSError *)error {

        if (error) {
                [self displayError: error];
        }

}

- (void)displayError: (NSError*)error {


    NSString *message = [NSString stringWithFormat:@"%@\n\n%@",                                                         error.localizedDescription,    [error.userInfo  objectForKey:@"NSErrorFailingURLStringKey"]];                                  


        NSString *htmlErrorDescription = [NSString 
                                                stringWithFormat:
      @"%@", [UIFont mediumFontName], message];
                                      

    [self.webView loadHTMLString:htmlErrorDescription 
                                                                 baseURL:nil];

}

-----------------------------------------------------------------------------------

Customize your own htmlErrorDescription  by using respective HTML format we want to display the error.

The same logic could be used If you are using WKWebView from WebKit as UIWebView is deprecated now.

Hope this post is useful. Feel free to comment incase of any queries.




Wednesday, November 8, 2017

Swift 4 - Method ‘initailize()’ defines Objective-C class method ‘initialize’, which is not guaranteed to be invoked by Swift and will be disallowed in future versions

In earlier swift versions (3x), We can override initialize() method of a class which gives you a compile time warning like shown below.






In latest Xcode 9 and above, We can set the Swift the version.








It is clearly saying that, The support will be disallowed in future.

So, From Swift 4, We are not suppose to override Objective-C class method initialize(), Which gives build error like shown below.

Method ‘initialize()’ defines Objective-C class method ‘initialize’, which is not permitted by Swift.















Swift 3 versions warning became error in Swift 4. 


In this post let’s see the alternate approach to get rid of this build error.

Like In my earlier Method Swizzling posts, If need something needs to be executed like Method swizzling in Swift, We can write that in method and call that in AppDelegate didFinishLaunchWithOptions


----------------------------------------------------------------------------------------------------------

    static func swizzleViewWillAppear() {
        if self != UIViewController.self {
            return
        }
        let _: () = {
            let originalSelector = #selector(UIViewController.viewWillAppear(_:))
            let swizzledSelector = #selector(UIViewController.newViewWillAppear(_:))
            let originalMethod = class_getInstanceMethod(self, originalSelector)
            let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
            method_exchangeImplementations(originalMethod!, swizzledMethod!);
        }()
    }

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

----------------------------------------------------------------------------------------------------------

The only extra step is we need to call that method explicitly to get it applied, Whereas using initialize() like in earlier versions, we don’t need to as initialize() will get called automatically.

Hope this post is useful. Feel free to comment incase of any queries.



Sunday, November 5, 2017

Swift 4 Method Swizzling (Part 1/2)

Method Swizzling is the process of changing the implementation of methods of a class at runtime.

Let’s see some use cases of Method Swizzling.

I want to do something before all of my ViewController’s ViewWillAppear, 

Like,

  • I need to display an alert to the user If the auth token expires and user has to Re-Login
  • I need to display an offer to the user as a Banner whatever may be the screen that user presently is in.


In these cases, Actually we can go with a Base class and write our logic in the Base class.

But this is not the correct approach. 

Because, We need to write Base classes for not only UIViewController, But also for UITableViewController, UINavigationController, UITabBarController and all which we use in our app.

If we go with Base classes, Our code will be redundant and there will be multiple base classes for the same piece of code.

Let’s see a code example of Base class approach, And then we will see the how Method Swizzling solves that without code redundancy.

I have two View Controllers.

------------------------------------------------------------------------

class ViewController: BaseViewController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
}

class ViewController2: BaseViewController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }    
}

------------------------------------------------------------------------

In my Base class I will just write the log and consider that as my logic I needed to get executed before my ViewWillAppear.

------------------------------------------------------------------------

class BaseViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("UIViewController - Display Notification!")
    }
    
}

------------------------------------------------------------------------

We are good here, As both View Controllers are Inherited from BaseViewController, Our notification will get fired at the time of these controllers viewWillAppear.

Now, There is a TableViewController.

------------------------------------------------------------------------

class TableViewController: UITableViewController {
    
    let users = ["user1", "user2", "user3", "user4"]

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return users.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
        cell.textLabel?.text = users[indexPath.row]
        return cell
    }
    
}

------------------------------------------------------------------------

Obviously, I can not extend it from BaseViewController, Cause, If I do, We will end up with errors like shown below.



















That means, UITableViewController will lose it’s characteristics If we go with BaseViewController as a base class and there is no point in taking a UITableViewController

Same applies to UINavigationController.

------------------------------------------------------------------------

class NavigationController: UINavigationController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
}

------------------------------------------------------------------------

If we take BaseViewController as base class, UINavigationController loses it’s characteristics and your push and pop will not work.

So for UITableViewController and UINavigationControllers also, We need to take Base Classes.

------------------------------------------------------------------------

class BaseTableViewController: UITableViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("UITableViewController - Display Notification")
    }  
}

------------------------------------------------------------------------

Such a bad approach with such a code redundancy.

In the next tutorial, Let’s see how this can be solved using Method Swizzling.

Hope this post is useful. Feel free to comment incase of any queries.




Saturday, October 21, 2017

Interface Segregation Principle in SOLID (Object-Oriented Design)

In this post, Let’s discuss ISP (Interface Segregation Principle) which is one of the SOLID principles of OOP design.

S  - Single Responsibility Principle
O - Open/Closed Principle
L  - Liskov Substitution Principle
I   - Interface Segregation Principle
D  - Dependency Inversion Principle

The Interface-segregation principle states that no client should be forced to depend on methods it does not use. ISP splits interfaces that are very large into smaller and more specific ones so that client will only have to know about the methods that are of interest to them. Such shrunken interfaces are also called as role interfaces.
  • Courtesy wikipedia.org

I am going to use Xcode9 and Swift 4 for the example ion this post.

Let’s take a Vehicle protocol, having necessary methods for vehicles.

  
    protocol VehicleProtocol {

        func numberOfGears() -> Int
        func isGearedOne() -> Bool
        func numberOfTyres() -> Int
    
        func start()
        func stop()    

    }


Let’s take a Car class which confirms to this protocol.

  
  class Car: VehicleProtocol  {

      func numberOfTyres() -> Int {
          return 4
      }
    
      func numberOfGears() -> Int {
          return 5
      }
    
      func isGearedOne() -> Bool {
          return true
      }
    
      func start() {
          print("starting off in first gear")
      }
    
      func stop() {
          print("stopping off in first gear")
      }
    
  }


For car, These all methods looks and fits good.

Whereas, Take a Horse class, 

  
   class Horse: VehicleProtocol  {

      func numberOfTyres() -> Int {
          return 4
      }
    
      func numberOfGears() -> Int {
          return 5
      }
    
      func isGearedOne() -> Bool {
          return true
      }
    
      func start() {
          print("starting off in first gear")
      }
    
      func stop() {
          print("stopping off in first gear")
      }
    
  }



For which below protocol methods looks very odd.

  1. numberOfGears
  2. isGearedOne
  3. numberOfTyres


If we ignore those protocols, You will end up with Build errors as shown below.



Here comes the ISP principle, Let me bring that again,

The Interface-segregation principle states that no client should be forced to depend on methods it does not use. ISP splits interfaces that are very large into smaller and more specific ones so that client will only have to know about the methods that are of interest to them. Such shrunken interfaces are also called as role interfaces.
  • Courtesy wikipedia.org

Let’s solve the above Horse scenario as per this principle.

I will separate VehicleProtocol into 2 different protocols based on their role as per the ISP principle.

  
   protocol VehicleData {

        func numberOfGears() -> Int
        func isGearedOne() -> Bool
        func numberOfTyres() -> Int
    
    }

   protocol VehicleActions {
    
        func start()
        func stop()
    
    }


VehicleData protocol’s role is to get the data of the vehicle
VehicleActions protocol’s role is to take the actions of the vehicle.

That’s how we have split a large interface into 2 small interfaces based on the role.

So now, Car can confirm to both VehicleData and VehicleActions,
Horse can confirm to VehicleActions.


  
  class Car: VehicleData, VehicleActions  {

    func numberOfTyres() -> Int {
        return 4
    }
    
    func numberOfGears() -> Int {
        return 5
    }
    
    func isGearedOne() -> Bool {
        return true
    }
    
    func start() {
        print("starting off in first gear")
    }
    
    func stop() {
        print("stopping off in first gear")
    }
    
  }

  class Horse: VehicleActions {
    
    func start() {
        print("started running")
    }
    
    func stop() {
        print("stopped running")
    }
    
  }


Now, You must have got an idea of why iOS is having two separate UITableView protocols, One for DataSource and one for Delegate :)

UITableViewDataSource
UITableViewDelegate

If you are not worried by the cell selections, You can ignore the UITableViewDelegate.

Hope this post is useful. Feel free to comment incase of any queries.