Search Your Question

Showing posts with label Reliance General. Show all posts
Showing posts with label Reliance General. Show all posts

If there are two views up and bottom, up-view is 60% of superview and 40% of superview respectively, then what to do with constraint?

Ans : 


Use of multiplier in constraint in iOS
Use of multiplier in constraint


We took 2 views - Orange and Green. 
We set orange view's top, leading, trailing constraint to main view as 0. 
Same, we set green view's bottom, leading, trailing constraint to main views as 0.

Now,
We select height constraint of orange view equal to main view's height. And set multiplier 0.6. It shows ratio of orange view's height to main view's height. We have set 0.6 = 60/100 . So orange view's height become 60% of main view's height.

Set multiplier of height constraint in size inspector
Set multiplier of height constraint in size inspector


Same we have done with green view and set multiplier 0.4 = 40/100 means 40%.

If you have any comment, question, or recommendation, feel free to post them in the comment section below!


Expandable tableview Logic in iOS

Ans : 

Logic  : 

  • Display UITableView containing just the header/section titles for each category.
  • When a section is touched, expand it if it is not already expanded. Otherwise, collapse the section.
  • When a section is touched, expand it and if another section is currently expanded collapse that section so that only one section is expanded at a time.
  • To expand a section, determine the number of items that must be displayed within that section and insert that number of rows in the UITableView; then display the items in the newly inserted rows.
  • To collapse a section, determine the number of items currently displayed within that section and delete that number of rows from the UITableView.

To reload one section only : 

[self.tableView beginUpdates];
 (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation:
[self.tableView endUpdates];

Dynamically set UITableview cell height

Ans : 

For auto cell height in tableview in Swift 3.0

Write following 2 lines of code in viewDidLoad and before reload tableview :

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44

Following steps must to do otherwise label height will not be increase and so UITableiViewCell.

Label height must be auto incremented using numberOfLines = 0

LineBreak should be set according your need word-wrap, char-wrap, etc...

Explain Apple push notification working

Ans : Push notifications allow developers to reach users and perform small tasks even when users aren’t actively using an app.

In iOS 10, User can do following task :

  • Display a short text message
  • Play a notification sound
  • Set a badge number on the app’s icon
  • Provide actions the user can take without opening the app
  • Show a media attachment
  • Be silent, allowing the app to wake up in the background and perform a task
Now following steps to follow to configure push notification :

1. Create app id in developer account with your app bundle id. Push notification entitlement must be enabled for this app id. (or another way for go to App Settings > Capabilities and enable push notification switch). You also have to create CSR(Certificate Signing Request) file from your keychain and assign to this app id push notification feature in developer account.

2. Now in terms of coding, first we need to ask to user for allowing user notification. After allowing, we need to register for remote notification. If all goes good, system provides you 'token' which is address of this app for this device.

3. In code, first import usernotification. Then for registering for remote notification, in didFnishLaunchingWithOptions

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])  {
    (granted, error) in
   
       print("Permission granted: \(granted)")
    
       guard granted else { return }
       self.getNotificationSettings()

  }

 func getNotificationSettings()  {
       UNUserNotificationCenter.current().getNotificationSettings { (settings) in
       print("Notification settings: \(settings)")
       guard settings.authorizationStatus == .authorized else { return }
       UIApplication.shared.registerForRemoteNotifications()
  }


4. If registered for remote notification successfully, then one of the following two method will be called,

func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)  {

       let tokenParts = deviceToken.map { data -> String in
              return String(format: "%02.2hhx", data)
        }

       let token = tokenParts.joined()
       print("Device Token: \(token)")
}

func application(_ application: UIApplication,
                 didFailToRegisterForRemoteNotificationsWithError error: Error)  {
  print("Failed to register: \(error)")
}

5. Device token is provided by APNS and this token will be converted to string. This device token shold be sent to application server or stored to database on server side.

Now lets study about payload or notification message,

Payload looks like :

{
  "aps": {
    "alert": "Breaking News!",
    "sound": "default",
    "link_url": "https://raywenderlich.com"
  }
}

aps is fixed key in payload dictionary json. aps is also dictionary itself.

alert : Display text message
sound : Which sound when notification come
link_url : custom key, we can any such custom key for data
badge : number of count of badge that is displayed on app icon
category : which type of custom action notification have

Payload maximum size is 4096 kb (4 mb).


Now what when notification comes

1. If app is closed didFinishLaunchingWithOptions is called.
2. If open in background or foreground, then didReceiveRemoteNotification is called.

For 1st case,

In didFinishLaunchingWithOptions method
// Check if launched from notification

if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {

  let aps = notification["aps"] as! [String: AnyObject]
  _ = NewsItem.makeNewsItem(aps)

  (window?.rootViewController as? UITabBarController)?.selectedIndex = 1
}

For 2nd case,

In didReceiveRemoteNotification,

let aps = userInfo["aps"] as! [String: AnyObject]
  _ = NewsItem.makeNewsItem(aps)

Actionable Notification

Actionable notifications let you add custom buttons to the notification. You can put reply,retweet,like button as you seen our favourite apps. This type of notification can be defined by Category.

In this type notification, we have to register category like following instead of UIApplication.shared.registerForRemoteNotifications().

func registerForPushNotifications() {
  UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
    (granted, error) in   
    print("Permission granted: \(granted)")
 
    guard granted else { return }
 
    // 1
    let viewAction = UNNotificationAction(identifier: viewActionIdentifier,
                                          title: "View",
                                          options: [.foreground])
 
    // 2
    let newsCategory = UNNotificationCategory(identifier: newsCategoryIdentifier,
                                              actions: [viewAction],
                                              intentIdentifiers: [],
                                              options: [])
    // 3
    UNUserNotificationCenter.current().setNotificationCategories([newsCategory])
 
    self.getNotificationSettings()
  }
}


Above things is not enough for taking action on button. We have to add extension of UNUserNotificationCenterDelegate.

Silent Notification 

If we want to do something task without knowing to user in background, then we can send silent notification to user device. For this background modes of push notification must be checked. For push notification aps, there is key named content-available. That's value should be 1 for silent notification.

For more detail, click here.



What is protocol? Why it is used?

Ans : Protocols are way to specify a set of methods that class has to implement if class want to work with this protocol. Protocol has 2 types of methods like Required type and Optional type methods.

1. If @required are tagged above methods, then these methods must be implemented on class which confirm this protocol.

2. If @optional are tagged above methods, then these methods is not necessary to implement on it.

Why it is used? 

Protocol provide blueprint methods for classes. It has certain methods and parameters that classes have to implement in its body. Its like that classes should have certain characteristic if it confirm protocol. Like if you want to become human(class) you must be sleep, eat, breathe(characteristics).

For more detail,
I have created Delegate and Protocol. See example.

Difference between Delegate and NSNotification

Ans :  A delegate uses protocol and creates a has-a relationship between two classes. Benefit of delegate is that we can return something back to the owning class.
Notification is like point to multi-point communication. Notification is one way  of message transmitting way.

Delegates create relationship between two classes. Notifications are used to send events to one or many classes.

We have to use delegate to specified known object. Notification for all object.

Delegate is like talking over telephone. Notification is like radio station.  

Coding of NSNotificationCenter :

[[NSNotificationCenter defaultCenter] addObjserver:self selector:@selector(useNotificationWithString:)  name:@”TimeOut” object:nil];

For BroadCast,

[[NSNotificationCenter defaultCenter] postNotificationName:@”TimeOut” object:nil userInfo:dict];

-(void) useNotificationWithString:(NSNotification *)notification
{
            dict = [notification userInfo];
}

To Remove observer,
[[NSNotificationCenter defaultCenter] removeObserver];