Search Your Question

Showing posts with label Drona HQ. Show all posts
Showing posts with label Drona HQ. Show all posts

What is Deep link in iOS?

Ans : 

Deep linking is the idea of not only having a clickable link to open up your app but a smart one that will also navigate to the desired resource.

There are 2 ways of implementing deep linking in IOS: URL scheme and Universal Links.

Comparison :


 Neither of these options will redirect you to the App Store if the app is not installed.

URL Scheme : 

Open Xcode, got to Project Settings -> Info, and add inside ‘The URL Types” section a new URL scheme. Add something of the sort of com.myApp and that’s it. Now install your app, open the app notes and type com.myApp and press enter.



Nothing will happen as IOS do not recognise this as URL. So, type com.myApp://main. Now when we press enter, we can see IOS detected the link and when we click it, a pop up will ask for permission to open MyApp from Notes.

To redirect to specific page or controller : 

Write following AppDelegate method,

  func application(_ app: UIApplication, open url: URL,
                     options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        if let scheme = url.scheme,
            scheme.localizedCaseInsensitiveCompare("com.myApp") == .orderedSame,
            let view = url.host {
            
            var parameters: [String: String] = [:]
            URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.forEach {
                parameters[$0.name] = $0.value
            }
            
            redirect(to: view, with: parameters)
        }
        return true
    }


and open com.myApp://profile?user=”mananshah”  from notes app.
Here,
     url.scheme = “com.myApp”
     url.host = “profile”
     parameters = [ “user” : “mananshah” ]

This URL will not work if app is not installed. If app is not installed, this will open safari and show blank page. For solving, we should implement Universal link.

Universal Link : 

Universal links are a bit more complex. Basically, we want IOS to relate a webpage URL to our app. Hitting URL expect a json in following format to ensure valid apps :

{
        “applinks”: {
            “apps”: [],
            “details”: [
                {
                    “appID”: “T5TQ36Q2SQ.com.myapp.production”,
                    “paths”: [“*”],
                }
            ]
        }

    }

Applinks indicate this is indeed for the Universal Link declaration.
Apps should be left as an empty array. This is most likely because these types of JSON are used for other purposes other than universal links as well.
Details will then contain an array of your apps and the mapping of each subpath to the respective app.
For each app, you should add a field called appID which is obtained concatenating your teamID and your app’s bundleID. For example, if your TeamID is 123456 and your AppID is com.myApp, then the result is 123456.com.myApp.
In the paths field, an array of strings representing with expressions of the paths which correspond to this app. For example, if you want myApp.com/store to open up a different app than myApp.com/maps, here you can declare that is a wildcard for any string, while ? is a wildcard for any character. As we only have one app, any subpath will lead here, hence the *. If you want to exclude a subpath, just add NOT at the beginning.
-----
Once that is done, we now must add the correct metadata to the app. 
First, open Xcode, go to Project settings -> capabilities. Scroll down to Associated Domains and turn it on. Once it is enabled, we shall add any URL that implements our apple-app-site-association resource, preceded by app links. Inside the Domains section, add a applinks:myApp.com. Once this is done, go ahead and try out your app.
To redirect to specific page or controller : 


public func application(_ application: UIApplication,
                               continue userActivity: NSUserActivity,
                               restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
           if let url = userActivity.webpageURL {
               var view = url.lastPathComponent
               var parameters: [String: String] = [:]
               URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.forEach {
                   parameters[$0.name] = $0.value
               }
               
               redirect(to: view, with: parameters)
           }
           return true
      }



Universal links allow us to have a fallback webpage if a user does not have the app installed
if the user has the app, the link will open it, and if not, it will fall under the webpage.

Credit : WOLOX

Can you search your app content In spotlight (search bar)?

Ans : 


Using spotlight search, here we can find loan no 14356 in our application and redirect to view details page of this loan number.

Apple offers us many iOS features that can boost our apps visibility even when the user is not using it. For example, features like Spotlight, Today Widget, iMessage, Push Notifications, Siri and so on...

Spotlight is a super-powerful search feature in iOS that searches through the contents of your installed apps that support it.

If we want our app content to appear in Spotlight, we need to use the CoreSpotlight framework. For creating searchable content we will need to be familiar with:

  • CSSearchableItemAttributeSet - specifies the properties that you want to appear in Spotlight (i.e. title, contentDescription, thumbnail). 
  • CSSearchableItem - this class represents the search item. We can assign a unique identifier for referring the object, a domain to manage the items in groups and attributeSet where we pass the CSSearchableItemAttributeSet that we have created for this object. 
  • CSSearchableIndex - a class that is responsible for indexing the content on Spotlight. It requires an array of CSSearchableItem.
Let's understand through some coding :

We have array of favourite books : 

var favorites = [Int]()   ->   This array contains int id of favourite book.

To enable searching content, we have to add our favourite list in spotlight content like following :

First import ,
import CoreSpotlight 
import MobileCoreServices

When new item added to favourite, it should be also added using following custom function :


func index(item: Int) {
    let book = books[item]

    let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
    attributeSet.title = book[0]
    attributeSet.contentDescription = book[1]

    let item = CSSearchableItem(uniqueIdentifier: "\(item)", domainIdentifier: "com.iosiqabooks", attributeSet: attributeSet)
    CSSearchableIndex.default().indexSearchableItems([item]) { error in
        if let error = error {
            print("Indexing error: \(error.localizedDescription)")
        } else {
            print("Search item successfully indexed!")
        }
    }
}

Understanding above code :

Let's create CSSearchableItemAttributeSet object. This attribute set can store lots of information for search, including a title, description and image, as well as use-specific information such as dates (for events), camera focal length and flash setting (for photos), latitude and longitude (for places), and much more.

Regardless of what you choose, you wrap up the attribute set inside a CSSearchableItem object, which contains a unique identifier and a domain identifier. The former must identify the item absolutely uniquely inside your app, but the latter is a way to group items together. Grouping items is how you get to say "delete all indexed items from group X" if you choose to, but in our case we'll just use "com.iosiqaswift" because we don't need grouping. As for the unique identifier, we can use the project number.

To index an item, you need to call indexSearchableItems() on the default searchable index of CSSearchableIndex, passing in an array of CSSearchableItem objects. This method runs asynchronously, so we're going to use a trailing closure to be told whether the indexing was successful or not.

By default, search item expiry of 1 month. After 1 month, it is deleted from spotlight. We can manually set expiration date like :

item.expirationDate = Date.distantFuture : It will never expire.

If we want to remove content from spotlight or to disable search item for spotlight,

func deindex(item: Int) {
    CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: ["\(item)"]) { error in
        if let error = error {
            print("Deindexing error: \(error.localizedDescription)")
        } else {
            print("Search item successfully removed!")
        }
    }
}

--------

We can now code for tapping on search result interaction in app delegate :

import CoreSpotlight in AppDelegate.swift.

We have to add following AppDelegate method :

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    if userActivity.activityType == CSSearchableItemActionType {
        if let uniqueIdentifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
            if let navigationController = window?.rootViewController as? UINavigationController {
                if let viewController = navigationController.topViewController as? ViewController {
                    viewController.readBook(Int(uniqueIdentifier)!)
                }
            }
        }
    }

    return true
}

Credit : HackingWithSwift




How to call segue programmatic?

Ans : 

For segue first, We have to set identifier in Class Inspector right side in XCode. Through that identifier, we can call like

performSegue(withIdentifier: "identifier", sender: nil) 

What is Content Hugging and Content Compression Resistance Priority?

Ans : 

The priority really come in to play only if two different constraints conflict. The system will give importance to the one with higher priority. So, Priority is the tie-breaker in the autolayout world.

1. Content Hugging Priority : 

Larger the content hugging priority , the views bound will hug to the intrinsic content more tightly preventing the view to grow beyond its intrinsic content size. Setting a larger value to this priority indicates that we don’t want the view to grow larger than its content.


In above example, we set both label leading, trailing, top and bottom but not set width constraint. So here conflicts will occur. You can see red line between two label showing conflict.

Solution : If we have label's content hugging priority higher than there will be no conflicts as hight priority label will not grow its size more than its content size. See below image :

Blue label has more content hugging priority (251) than green label(250). Blue label's width will be set fixed as its content size.

2. Content Compression Resistance : 

Setting a higher value means that we don’t want the view to shrink smaller than the intrinsic content size. It's simple : Higher the priority means larger the resistance to get shrunk.

Example . One button having large name and auto layout is set on button as its width is become 40. So, button's content is not readable. See image :
Button horizontal compression resistance is 750 and width constraint priority is 1000.

For Solution, let's change horizontal compression resistance to 1000 and width constraint priority less than 1000 i.e 999 . Now see effect on below image :
Button horizontal compression resistance is 1000 and width constraint priority is 999.


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