Browse Category: iOS

Decodable in Swift 4

According to Apple Codable is “A type that can convert itself into and out of an external representation.”

  1. Encodable — for encoding
  2. Decodable — for decoding
  3. Codable — for both encoding as well as decoding

Let suppose we need to decode json response of type as below,

          [
            {
               "name": "India",
               "dial_code": "+91",
               "code": "IN"
            }
          ]

For Parsing purpose  we generally create model class or struct or enum for now lets create struct for country name , dial code and country code as below,.

           struct Country: Decodable {
                  let name: String!
                  let dial_code: String!
                  let code: String!
           }//struct

 

Here if you observer🧐 we have confirm Decodable protocol to struct. Let move to next step as 🤞🏻🤞🏻PARSING Phase  🤞🏻🤞🏻 as below,.

        do {
            countryArray = try JSONDecoder().decode(Country.self, from: data)
        } catch let err {
            print(err.localizedDescription)
        }

🤩 🌟 👏🏻   PARSING is successful…….💐💐💐💐💐😅

Now lets parse array😱 of country 🤨. No worry it is so easy to do. You have to make Country as a array.

        do {
            countryArray = try JSONDecoder().decode([Country].self, from: data)
        } catch let err {
            print(err.localizedDescription)
        }
where,
        let data : Data = try! Data.init(contentsOf: fileUrl)
        var countryArray = [Country]()


Thank You !!!

Higher Order Function in Swift PART 2

Let’s start with FlatMap where few point need to cover. So lets begin,

Flatmap

Flatmap is used to flatten a collection of collections.

        let temp_Dictionary = [["k1":"v1","k2":"v2"],["k3":"v3","k4":"v4"]]
        let flatMap_1 = temp_Dictionary.flatMap { $0 }
        //[(key: "k2", value: "v2"), (key: "k1", value: "v1"), (key: "k3", value: "v3"), (key: "k4", value: "v4")]

It returns an array of tuples after flatmapping. We have to convert it to an array

        var flatMap_dictionary = [String: String]()
        flatMap_1.forEach {
            flatMap_dictionary[$0.0] = $0.1
        }
        //["k2": "v2", "k4": "v4", "k3": "v3", "k1": "v1"]

Sort

Sort an array simply by describing how you want the sort to work. You can do this simply by indicating the direction of the sort with a > or <.

So let’s try to sort simple name array as:

        let names = ["Sagar", "Savita", "Trupti", "Shravan", "Abdul", "Pragati", "amrita"]
        //["Abdul", "Pragati", "Sagar", "Savita", "Shravan", "Trupti", "amrita"]

Great, but what about “amrita” starts with a lower case letter?🤔🙄😟.

To ignore case, compare the lower case versions of the names:

        sortedNames = []
        sortedNames = names.sorted(by: {
            $0.lowercased() < $1.lowercased() 
        } 
        //["Abdul", "amrita", "Pragati", "Sagar", "Savita", "Shravan", "Trupti"]

That WORKS!!!!!!!!😀😃😃😄

Now let’s try out something more complex like below:,😮😯😧

For user-visible sorted lists, we should always use localized comparisons.

Fortunately, strings have another property called localizedLowercase.

        let sortedAcc_lastName = people.sorted(by: {
        $0.lastName.localizedLowercase < $1.lastName.localizedLowercase } )
        //[HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Shravan", lastName: "Gundawar"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Savita", lastName: "Kakade"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Trupti", lastName: "Karale"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Sager", lastName: "Rode"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "paragati", lastName: "Rode"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Adul", lastName: "Shaikh")]

This will sort according to lastName only.Obviously the first names need to be compared as well. You can achieve this by putting the two comparisons into a tuple.

       let sortedComplete = people.sorted(by: {
       ($0.firstName.localizedLowercase,$0.lastName.localizedLowercase) <
       ($1.firstName.localizedLowercase,$1.lastName.localizedLowercase)
        } )
       //[HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Adul", lastName: "Shaikh"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "paragati", lastName: "Rode"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Sager", lastName: "Rode"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Savita", lastName: "Kakade"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Shravan", lastName: "Gundawar"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Trupti", lastName: "Karale")]

 

Contains

Generate a true/false by checking if any element in your array satisfies a condition. Related to filter, but returns a Bool, rather than an array.

eg. Let’s say we need to know if our fruits array contains a seven letter name.

         let sevenCharWord = names.contains { $0.characters.count == 7 }
         //true

Drop

Drops elements from your array while a condition is true, stops checking when it encounters an element that shouldn’t be dropped.

Let’s say we want to drop all elements at the beginning of the array that doesn’t contain the letter ‘s’.

           let name = names.drop { $0.contains("s") }
           //[ "Trupti",  "Abdul", "Pragati", "amrita"]
 

 

First

You’re probably familiar with the first property that retrieves the first element of an array, but did you know you can pass in a condition to get only the first element that meets that condition?

Let’s say we want the first element of the array that contains the letter ‘r’.

        let nameWithR = names.first { $0.contains("r") }
        //"Trupti"

ForEach

The forEach higher order function is a cool tool for your programming arsenal – basically short-hand for the for-inloop.

Let’s say we want print the lowercase version of every name in our Names array.

      names.forEach { print($0.lowercased(), terminator: " ") }
      //sagar savita trupti shravan abdul pragati amrita

Partition

The partition method partitions the elements of your array based on a condition. Elements that meet the condition are placed last in the array.

      names.partition(by: { $0.contains("i") })
      //["Sagar", "Abdul", "Shravan", "Trupti", "Savita", "Pragati", "amrita"]

Split

You may be familiar with the components method on String, used to split a String based on a separator.
To use the split method on a String, you would use it on the String.characters property, which is a String.CharacterType, which adopts the Collection protocol, giving characters access to many of the same cool higher order functions that Array has access to. Once you’ve separated String characters with split, you’ll have an array of something called a SubSequence, that you can pass in when initialising a String – you can do this on each element of your new array using the map higher order function to end up with an array of Strings.

For Example,

        let str = "I can't believe it! These higher order functions are like magic. Don't you think? Well, maybe not magic, but pretty useful all the same."
        let  sen1  =str.characters.spilt { $0 == "."  || $0 == "!"  || $0 == "?"  }
        let sen = sen1.map{ String($0) }
        //["I can\'t believe it", " These higher order functions are like magic", " Don\'t you think", " Well, maybe not magic, but pretty useful all the same"]

 

So here we have seen most of Higher Order Function. Hope you like this.
Thanks For Reading 😁🤪

Move View/ScrollView to keep TextField visible when keyboard appears!

There is a very common but tricky part comes while handling textfields position when keyboard appears. Its sometimes become headache for developers to handle such small but tricky issue. When keyboard appears then some textfields get covered and user can’t see while editing it.

There are some solutions to handle this but many of them works only for the first time. And then doesn’t work.
I have found one best solution and it works great always and I have modified this code to work on Swift 4. I have used XCode 9.1 for this tutorial code.

Lets do it.

You will have to create new project to try this. Design your storyboard like the image from below link.

https://drive.google.com/a/nanostuffs.com/file/d/1KXJV49BP07T2q8nca4vKlz3eMU7xtkNG/view?usp=sharing

And set delegate of all textFields to ViewController.


Now in your ViewController class you can use it like below


 

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

     @IBOutlet weak var myScrollView: UIScrollView!

     @IBOutlet weak var constraintContentHeight: NSLayoutConstraint!

     override func viewDidLoad() {

          super.viewDidLoad()

}

override func viewWillAppear(_ animated:Bool) {

     super.viewWillAppear(animated)

//1  Add this observers to observe keyboard shown and hidden events
      NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(aNotification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

     NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(aNotification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

}

override func viewWillDisappear(_ animated: Bool) {

     super.viewWillDisappear(animated)

//2  Remove the observers added for keyboard from your ViewController

     NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)

     NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)

}

var activeField: UITextField?

// MARK: – UITextField Delegates

//3  ViewController activeField is an object of UITextField which will be used to manage and resign current active textField 

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

     textField.resignFirstResponder()

     return true

}

func textFieldDidBeginEditing(_ textField: UITextField) {

     activeField = textField

}

func textFieldDidEndEditing(_ textField: UITextField) {

     activeField = nil

}

// Called when the UIKeyboardWillHide is sent

//4  This method is called from selector. So it requires @objc keyword and this method will adjust your scrollView (here myScrollView  😉)  and textFields to show as original.

@objc func keyboardWillBeHidden(aNotification: NSNotification) {

     let contentInsets: UIEdgeInsets = .zero

     self.myScrollView.contentInset = contentInsets

     self.myScrollView.scrollIndicatorInsets = contentInsets

}

// Called when the UIKeyboardWillShow is sent

//5
This method will adjust your scrollView
and will show textFields above the keyboard.
@objc
func
keyboardWillShow(aNotification: NSNotification) {

     var info = aNotification.userInfo!

     let kbSize: CGSize = ((info[“UIKeyboardFrameEndUserInfoKey”] as? CGRect)?.size)!

     print(“kbSize = \(kbSize)”)

     let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0)

     myScrollView.contentInset = contentInsets

     myScrollView.scrollIndicatorInsets = contentInsets

     var aRect: CGRect = self.view.frame

     aRect.size.height -= kbSize.height

     if !aRect.contains(activeField!.frame.origin) {

          self.myScrollView.scrollRectToVisible(activeField!.frame, animated: true)

     }

  }

} // Class End

Integration of Chat Library and Firebase in iOS Project

Group chat is a very easy and good approach for having the communication in any mobile application. Today we are going to dive into an implementation of “Group Chat Using Firebase”.

While implementing this functionality in mobile application the very important and challenging task is creating an UserInterface for chatting screen, so for designing this screen we will go with the “JSQMessageViewController” it is an open source library for chatting.

Let’s see the procedure for implementing  “JSQMessageViewController”  to design chat screen. For more info you can take help from this link https://github.com/jessesquires/JSQMessagesViewController 

First of all create a new swift project, Now open terminal window and enter the command : cd (your project path).

After this command we will enter into our project folder, for using JSQMessageViewController we need to install pods into our project.

 

Procedure to install PODS : 

  1. Run “pod init” command on terminal. (It will create a Podfile into our project folder)
  2. open that created Podfile and enter pods for JSQMessageViewController (ie.pod JSQMessagesViewController)
  3. Now Save the file and close it.
  4. Again go to terminal window and run “pod install” command. (It will install all the dependencies of JSQMessagesViewController to our project and also create a new project file with .xcworkspace extension).
  5. Now open projectName.xcworkspace file in xcode.

We are done with all prerequisites for chat screen design,  JSQMessagesViewController have used collectionView for showing message bubble, so to display the message bubble into our project we need to implement all DataSource & Delegates for CollectionView created by JSQMessagesViewController.

 

It is very important to display all chat messages taken place in chat group so that need to be pushed/dump somewhere and retrieve  from somewhere. So for achieving this we are going to use “FIREBASE“.

Firebase is a mobile and web application development platform. It also provides a realtime database, so to achieve the above mentioned scenario we will use the firebase as a database.To create an environment for using firebase into our app we need to follow some steps to setup some prerequisites, please take a reference from this link https://firebase.google.com/ for more info.

Steps to integrate firebase into our project :

  1. Go to this link https://firebase.google.com/  
  2. Login with your gmail credentials.
  3. click on “Go To Console” on top right corner.
  4. Now need to create a new app space, on firebase for our app. To create app space on firebase click on “Add Project”
  5. Fill up all the required information on the given popup and click on “CreateProject”.
  6. Now go to “Authentication” tab on left hand side, click on sign-in methods and enable “Email/Password” by clicking that field.
  7. Go to “Project Setting” -> “General” -> “Add firebase to your app” and fill all the information and complete the procedure. At the end it will create a .plist file that you need to add into our project.
  8. After importing .plist file to our project it’s time to install PODS for firebase.
  • Open existing Podfile from project.
  • Add pod ‘Firebase/Core’ to Podfile, save and close the file.
  • Follow all the steps whichever we done for installing JSQMessagesViewController pods.

 

Now you are perfectly ready with environment to implement chatting app in iOS using firebase as a realtime database.

 

 

 

Implement a drawing app in Swift

Implement smooth drawing in iOS using swift.

A drawing app allows the user to draw on the screen with their finger. There are many companies  ask customers to sign on apple device when making purchases. 

Steps

1> create a custom class line for initializing values of start and end point of line

import UIKit

class Line{

  var start : CGPoint

  var end : CGPoint

  init(start _start : CGPoint , end _end : CGPoint) {

    start = _start

    end = _end

  }

}

2> We will create a custom drawview UIView class.  for drawing line from start and end point using draw function,   So that it can act like a canvas for our drawing app.  

import UIKit

class DrawView: UIView {

  var lines : [Line] = []

  var lastPoint : CGPoint!

  required init(coder aDecoder : NSCoder) {

    super.init(coder: aDecoder)!

  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    lastPoint = touches.first?.location(in: self)

  }  

  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    let newPoint = touches.first?.location(in: self)

    lines.append(Line(start: lastPoint, end: newPoint!))

    lastPoint = newPoint

    self.setNeedsDisplay()

  }

  

  override func draw(_ rect: CGRect) {

    var context = UIGraphicsGetCurrentContext()

    context?.beginPath()

    for line in lines

    {

      let aPath = UIBezierPath()

      aPath.lineWidth = 5.0

      aPath.lineJoinStyle = .round

      aPath.move(to: CGPoint(x:line.start.x,y:line.start.y))

      aPath.addLine(to: CGPoint(x:line.end.x,y:line.end.y))

       aPath.stroke()

      aPath.lineCapStyle = .round

      //cgcontextSetLineCap()

    }

 }

}

3> write controller class in which we are using the draw view class for drawing line

import UIKit

class ViewController: UIViewController {

  @IBOutlet var drawView : AnyObject!

  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

  }

  override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

  }

@IBAction func clearbutton()

{

  let theDrawView : DrawView = drawView as! DrawView

  theDrawView.lines = []

  theDrawView.setNeedsDisplay()

  }

}

Happy Drawing

Higher order functions in swift

As far as I understood, higher order functions are functions that takes another function/closure as argument and/or returns it.

Higher order functions are simply functions that operate on other functions by either taking a function as an argument, or returning a function. Swift’s Array type has a few methods that are higher order functions: sorted, map, filter, and reduce. These methods use closures to allow us to pass in functionality that can then determine how we want the method to sort, map, filter, or reduce an array of objects.
If you look around the internets the most commonly mentioned higher order functions in Swift are generally mapfilter, reduce and sort (or sorted). But there are so many more to play with!

Just take a look at Array – you will also find containsdropfirstflatMapforEachpartition  and split.

Map

Use map to loop over a collection and apply the same operation to each element in the collection.

Map on array:

Let’s assume we need to multiply each item by 10 in an array called numberArray

          let numberArray = [2,3,4,5,6,7,8]
          let emptyArray:[Int] = []
          //MARK:-Traditional Way
         for number in numberArray{
                    emptyArray.append(number*10)
         }
        //MARK:-
Higher Order Functions that is map

There are few form’s: long-form vs shorthand closure syntax preference.
        //1) Way
        emptyArray = []

        emptyArray = numberArray.map ( { (value:Int) -> Int in
               return value*10
})
        //2) Way
        emptyArray = []
        emptyArray = numberArray.map( { (value:Int) in
               return value*10
        })
//3) Way
        emptyArray = []
        emptyArray = numberArray.map {value in value*10}
//4) Way
        emptyArray = []
        emptyArray = numberArray.map {$0 * 10}

The map function has a single argument which is a closure (a function) that it calls as it loops over the collection. This closure takes the element from the collection as an argument and returns a result. The map function returns these results in an array.

Map on Dictionary:

        let reviews = [“likes”:50, “comments”:52]

Here, for the above dictionary, as we iterate over the collection our closure has arguments that are a String and a Int from the types of the key and value that make up each element of the dictionary. The return type can be an array of values (i.e., 50), values array with discounts or even an array of tuples. It’s all upto you.

         let reviewsCount = reviews.map { (key, value) in
                 return value
         }
         print(reviewsCount)
         //[50, 52]

Map on Custom Object:

    struct Person{
       let name:String
       let id:Int
           init(name:String, id:Int){
           self.name = name
           self.id = id
       }
    }
    let personDict = ["Palash":1,"Rahul":2,"Govind":3]
    let persons = personDict.map{ name, id in Person(name: name, id: id)}
    print(persons.first?.name)
    //Palash

Array count  Traditional Way Exe. time    Using Hight Order Function map Exe. time
   6930         0.0645290017127991                         0.00439298152923584

Filter

Use filter to loop over a collection and return an Array containing only those elements that match an include condition.

Filter on array:

Consider the following code to filter even numbers from an array of integers.Now, like map , there is a simple method to do the filtering stuff for collection types.The swift autocomplete shows the following if we try to use filter method for an Int array.
The filter method has a single argument that specifies the include condition. This is a closure that takes as an argument the element from the collection and must return a Bool indicating if the item should be included in the result. I have given the shorthand closure syntax example below.,

         //MARK:-Traditional Way
         emptyArray = []
         for no in numberArray{
             if no % 2 == 0{
                 emptyArray.append(no)
             }
         }

         //MARK:-Higher Order Functions
         emptyArray = []
         emptyArray = numberArray.filter{$0 % 2 == 0}

Filter on dictionary:

 The filter functions will call a closure called isIncluded by passing each key-value pair and do the condition check (here, it accepts a String and Doubleas arguments). Finally, based on the bool value returned, the filter function will decide whether or not to add the key-value pair in the returned array.
Filter function on dictionary returns an array of Tuples .

          let reviewsFilter = reviews.filter { (key, value) in
                  return value > 50
}
          print(reviewsFilter)

         //52

This can be further simplified as:

         let reviewsFilter1 = reviews.filter { $1 > 50}

       Note: $0 is the key, $1 is the value

Array count  Traditional Way Exe. time    Using Hight Order Function map Exe. time
 3300           0.000292956829071045                    0.00520197877883911

Reduce

Combines all items in a collection to create a single value.

The most versatile function reviewed here is reduce. Reducing a sequence means transforming many items into a single item. For example, an array of integers could be reduced to the sum of every integer in the array. In this case, a sequence of integers is reduced to a single integer.

        //MARK:-Traditional Way
        var sum = 0
        for no in numberArray{
sum += no
        }

The two parameters in reduce function are a starting value and a function respectively. The function takes a running total and an element of the array as parameters, and returns a new running total.

        //MARK:-Higher Order Functions
        //1 Way 
        var  sum = numberArray.reduce(0, {$0 + $1})
        //2 Way 
        var sum = numberArray.reduce(0,+)

In above scenario, instead of the closure, we could also pass basic operator functions like +, -, *, / . So we can say reduce is used to combine all items in a collection to create a single new value.

Reduce on dictionary

        let totalReviews = reviews.reduce(0) { (result, tupleOfKeyAndValue) in
                   return result + tupleOfKeyAndValue.value
}

Flatmap

When implemented on sequences : Flattens a collection of collections.

There are two versions of this function: one that supports mapping optional values and another that supports mapping a sequence of sequences, such as [[Int]] (i.e. an array of array of integers)

let tempArray = _flatMap([“Hi”,” “,“there”,” “, nil,“😁!!!!”]) { $0 }
print(tempArray)

//Hi there 😁!!!!

This function is like a mixture of map and filter. It creates a sequence of mapped values, but a mapped value is not added to the output sequence when the closure returns nil. In that sense, returning nil is similar to returning false from a closure passed to the filter function.

 

Happy Coding… 🙂📱😁
I will show the usage of remaining higher order function in my next post.

Virtual Assistant

A virtual assistant is a software agent that can perform tasks or services for an individual. Sometimes the term “chatbot” is used to refer to virtual assistants generally or specifically those accessed by online chat (or in some cases online chat programs that are for entertainment and not useful purposes).

As of 2017, the capabilities and usage of virtual assistants is expanding rapidly, with new products entering the market. An online poll in May 2017 found the most widely used in the US were Apple’s Siri (34%), Google Assistant (19%), Amazon Alexa (6%), and Microsoft Cortana(4%). Facebook’s M is expected to be available to hundreds of millions on Facebook Messenger in 2017.

 

Cortana

Cortana is an operating system-oriented voice assistant available on Windows 10 devices, as well as the Xbox One console. Cortana is closely connected to productivity, but can also help answer more general questions by pulling information from Bing.

The Cortana VA has seen a lot of recent growth, expanding her use throughout Windows 10 and related services. Combined with newer offerings like Surface Studio, its clear Microsoft favors Cortana as an OS-based service to control Windows 10 while one is working.

While user can store specific bits of information with Cortana, Microsoft’s virtual assistant is constantly analyzing user’s interactions to learn more about him/her. This info is stored in something Microsoft calls the “Notebook,” which includes the places user likes to go, people he/she care about, user’s preferred quiet hours, and things he/she might be interested in, among other things. User can even edit it if he like.

Cortana can user’s emails, track user’s location, watch user’s browsing history, check user’s contact list, keep an eye on user’s calendar, and put all this data together to suggest useful info, if user allow it to. Cortana is designed to recognize context, so it should be able to understand follow-up requests, and you can phrase things in different ways and still expect a useful answer. User can also type his/her questions or requests, if you prefer to not speak out loud.

The latest changes from the Windows 10 Creators Update allow Cortana to help in the setup process for new computers, and include a new full screen mode for Cortana that serves as both a screensaver and voice-assistant focused mode when user is away from the computer—or is too far away to type. Cortana can also handle music and reminder commands more effectively, spanning multiple music apps and controlling volume as user desire.

 

Siri

Siri has been an integral part of iOS since the launch of iOS 5 in 2011. It started with the basics such as weather and messaging, but has expanded greatly since then to support more third-party integration with MacOS.

While Siri’s jokes are legendary, the virtual assistant is getting more capable every day. Now, user can ask it to call people, send messages, schedule meetings, launch apps and games, play music, answer questions, set reminders, and provide weather forecasts.

Siri can also integrate with third-party apps and understand follow-up queries. That’s a big change in strategy for Apple, which typically maintains a tight grip on which third-party companies get access to its native functions.

Siri is probably the most familiar of all the voice assistants. It also lags behind the other VAs when it comes to text input, which isn’t supported for most Siri functions. Apple appears to be using Siri for voice controls and Spotlight for similar text-based queries.

The latest news for Siri includes voice compatibility for WhatsApp, expanded payment options for Lyft and Uber, and the ability to look up international cricket scores. These are minor tweaks compared to the changes other VAs are going through, but they also point to Siri’s continued stability—particularly for long-term iOS users who already know the voice assistant well.

 

Google Assistant

Google Assistant (which has incorporated functions from the older Google Now, as Now is being phased out) is different from Cortana and Siri. It has less personality, but more functionality. While it is an integral part of Android, Google Assistant also lives in an iOS app, and can be accessed through the Chrome browser as needed.

Like Cortana and Siri, you can ask Assistant for directions to the closest Chinese restaurant, or what the weather looks like for the next 10 days. If you let it, Google’s software will utilize your search history and customize its responses based on what it knows about your queries.

Google’s integration with its search engine makes Google Assistant one of the most useful virtual assistants out of the box. It already has a treasure trove of data on what you’ve done on the web. It also reacts to questions in a similar way to the Google browser, which makes it great for general information and trivia.

 

Alexa

It is Amazon’s voice assistant and it isn’t focused on mobile or computer purposes, but rather for the standalone Amazon Echo speaker and a limited number of Amazon Fire devices, with a greater concentration on whole-house management and services rather than computer-oriented tasks.

Obviously, this limits Alexa compared to the alternatives. However, there are some advantages to the Amazon approach. Like Assistant, Alexa is highly conversational, and its ability to parse meaning is frequently excellent, whether you’re asking about the weather or listening to the latest news summaries from around the web. Alexa is meant to be used out in the open, away from the computer, while you’re working elsewhere but still need information, entertainment, or purchases.

The customization and management options for Alexa also impress. While other voice assistants hide many of their capabilities away from users, Alexa brings them all out in the form of “skills” and connections. The Alexa app allows you to add various mini-apps in the form of skills, and adjust current services and settings using these skills. It’s a great system, especially for those who like to tinker, but it does require learning a new approach to VA management.

Amazon is also doing a lot of work to bring Alexa into more mobile situations: The Alexa app, for example, brings many of its capabilities to your phone so you can organize lists while driving or control smart home features away from an Echo.

 

 

Bixby

Not to be outdone in the voice assistant game, Samsung has also created a mobile device assistant called Bixby, which now has full voice command compatibility (if you’ve picked up a Galaxy S8, you’ve probably encountered it). In general, Bixby shares a lot in common with Cortana. The VA lingers on the Galaxy phone, ready to access information and manage your data, schedule, events, and more. It doesn’t venture out into the Internet of Things much, but it does have an impressive amount of control over everything you do on your Samsung device.

You can divide Bixby into three basic different categories of abilities—Voice, Home, and Vision. They all work together, but use different Bixby abilities:

Voice includes both questions—”What’s the weather today?”—and commands. Start by saying “Hey Bixby” and you can get general information or facts. However, like Cortana, Bixby also excels at operating software, so you can also use it to control the Galaxy menus, change settings, set reminders, take pictures, edit video, and much, much more. If you’ve ever wanted to operate your smartphone hands free, there’s a lot to explore here. Some functionality goes even deeper – you can ask Bixby to read out your latest emails, or tell it to post your photo to Instagram, and Bixby will do so.

Home is the app face of Bixby, a screen that provides information based on what you have asked Bixby about in the past, as well as the different services that Bixby can control with the right compatibility—Including Facebook, CNN, and Spotify. In the future this area may include smart home capabilities (Samsung says it’s on the way), but for now it’s relegated to basic online services.

Vision is the most unique part of Bixby, as it can analyze what image the camera is picking up and give you a report on it. When this works (say, looking at a recognizable logo) Bixby can help you instantly compare online prices to in-store prices, or give you more information about local landmarks. If this feature takes off, other voice assistants may start getting jealous.

 

 

Alternative for xib in swift3 iOS

Hi all,

Lets see the simplest and best way to replace or avoid use of xib by using UIView on storyboard.

 

  1.  Go on storyboard ,select Viewcontroller Drag UIView and drop it between FirstResponder and exit button on that.
  2.  Add IBOutlet of that UIView on ViewController.swift file.
  3.  set the center, width, height for that UIView
  4.  Refer Following code :

 

——– IBOutlet ——–

@IBOutlet var View_alternativeForXib: UIView!

var view_BGDimmer = UIView()

    

——– Set the center , width, height for that UIView as well as add transperent Background view ———

 

       View_alternativeForXib.center = (UIApplication.shared.keyWindow?.center)!

          view_BGDimmer.frame = (UIApplication.shared.keyWindow?.frame)!

         View_alternativeForXib.frame.size.width = (UIApplication.shared.keyWindow?.frame.width)! – 40

         View_alternativeForXib.frame.origin.x = (UIApplication.shared.keyWindow?.frame.origin.x)! + 20

          view_BGDimmer.backgroundColor =  colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)

          view_BGDimmer.alpha = 0.3

          UIApplication.shared.keyWindow?.addSubview(view_BGDimmer)

          UIApplication.shared.keyWindow?.insertSubview(self.View_alternativeForXib, aboveSubview: self.view_BGDimmer)

          UIView.animate(withDuration: 0.1, animations: {

          }) { (completed) in

          }

 

——-  To dismiss view ——

   func dimissPopUp() {

        UIView.animate(withDuration: 0.2, animations: {

            self.view_BGDimmer.alpha = 0.0

            self.View_alternativeForXib.removeFromSuperview()

            self.view.layoutIfNeeded()

        }) { (completed) in

            self.view_BGDimmer.removeFromSuperview()

        }

    }

 

 

Thanks,

 

 

Save and Load from KeyChain | Swift 4

import Cocoa

import Security

// see https://stackoverflow.com/a/37539998/1694526

// Arguments for the keychain queries

let kSecClassValue = NSString(format: kSecClass)

let kSecAttrAccountValue = NSString(format: kSecAttrAccount)

let kSecValueDataValue = NSString(format: kSecValueData)

let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword)

let kSecAttrServiceValue = NSString(format: kSecAttrService)

let kSecMatchLimitValue = NSString(format: kSecMatchLimit)

let kSecReturnDataValue = NSString(format: kSecReturnData)

let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne)

public class KeychainService: NSObject {

    class func updatePassword(service: String, account:String, data: String) {

        if let dataFromString: Data = data.data(using: String.Encoding.utf8, allowLossyConversion: false) {

            // Instantiate a new default keychain query

            let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

            let status = SecItemUpdate(keychainQuery as CFDictionary, [kSecValueDataValue:dataFromString] as CFDictionary)

            if (status != errSecSuccess) {

                if let err = SecCopyErrorMessageString(status, nil) {

                    print(“Read failed: \(err)”)

                }

            }

        }

    }

    class func removePassword(service: String, account:String) {

        // Instantiate a new default keychain query

        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

        // Delete any existing items

        let status = SecItemDelete(keychainQuery as CFDictionary)

        if (status != errSecSuccess) {

            if let err = SecCopyErrorMessageString(status, nil) {

                print(“Remove failed: \(err)”)

            }

        }

    }

    class func savePassword(service: String, account:String, data: String) {

        if let dataFromString = data.data(using: String.Encoding.utf8, allowLossyConversion: false) {

            // Instantiate a new default keychain query

            let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])

            // Add the new keychain item

            let status = SecItemAdd(keychainQuery as CFDictionary, nil)

            if (status != errSecSuccess) {    // Always check the status

                if let err = SecCopyErrorMessageString(status, nil) {

                    print(“Write failed: \(err)”)

                }

            }

        }

    }

    class func loadPassword(service: String, account:String) -> String? {

        // Instantiate a new default keychain query

        // Tell the query to return a result

        // Limit our results to one item

        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

        var dataTypeRef :AnyObject?

        // Search for the keychain items

        let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)

        var contentsOfKeychain: String?

        if status == errSecSuccess {

            if let retrievedData = dataTypeRef as? Data {

                contentsOfKeychain = String(data: retrievedData, encoding: String.Encoding.utf8)

            }

        } else {

            print(“Nothing was retrieved from the keychain. Status code \(status)”)

        }

        return contentsOfKeychain

    }

}

You need to imagine the following wired up to a text input field and a label, then having four buttons wired up, one for each of the methods.

class ViewController: NSViewController {

    @IBOutlet weak var enterPassword: NSTextField!

    @IBOutlet weak var retrievedPassword: NSTextField!

    let service = “myService”

    let account = “myAccount”

    // will only work after

    @IBAction func updatePassword(_ sender: Any) {

        KeychainService.updatePassword(service: service, account: account, data: enterPassword.stringValue)

    }

    @IBAction func removePassword(_ sender: Any) {

        KeychainService.removePassword(service: service, account: account)

    }

    @IBAction func passwordSet(_ sender: Any) {

        let password = enterPassword.stringValue

        KeychainService.savePassword(service: service, account: account, data: password)

    }

    @IBAction func passwordGet(_ sender: Any) {

        if let str = KeychainService.loadPassword(service: service, account: account) {

            retrievedPassword.stringValue = str

        }

        else {retrievedPassword.stringValue = “Password does not exist” }

    }

}

Quick Actions In Swift

Apple has added quick actions to the app icon so users can deep link into an area of your app quicker. By pressing the app icon of the latest devices, the user obtains a set of quick actions. When the user selects a quick action, your app activates or launches and your app delegate object receives the quick action message.

DEFINE QUICK ACTIONS

In app’s Info.plist file create a UIApplicationShortcutItems array. This is where we define what the actions are, the title, subtitle, and short cut keys for each. Note that you can only have a max of 4 quick actions off the icon in app.

UIApplicationShortcutItemType – A required string delivered to your app when the user invokes the corresponding quick action.

UIApplicationShortcutItemTitle – A required string displayed to the user on the Home screen as the name of the quick action.

UIApplicationShortcutItemSubtitle – An optional string that is displayed to the user on the Home screen, immediately below the corresponding title string.

UIApplicationShortcutItemIconType – An optional string specifying the type of an icon from the system-provided library.

UIApplicationShortcutItemIconFile – An optional string specifying an icon image to use from the app’s bundle, or the name of an image in an asset catalog.

UIApplicationShortcutItemUserInfo – An optional, app-defined dictionary. One use for this dictionary is to provide app version information.

Next you can run your app and test to see if the quick actions are formatted the way you expected them to look.

Note: You must develop on a device that supports 3D Touch. The simulator in Xcode does not support 3D Touch.

HANDLE THE SHORT CUTS

Begin by adding the enum and properties we are going to need in the methods. If you don’t want to use enums, then make sure your names match the UIApplicationShortcutItemType values entered in your Info.plist.

Read in the UIApplicationShortcutItem that is selected by the User in the didFinishLaunchingWithOptions method. Here we are saving that value into launchedShortcutItem so we can handle it next.

The next method to get called is applicationDidBecomeActive, this method gets called after didFinishLaunchingWithOptions during the first launch of your app, or every time the user comes into your app while it’s still open in the background.

When a user chooses one of the quick actions the app launches or resumes the app and calls the performActionForShortcutItem method in your app delegate.

Lastly we need to handle the short cut and deep link the user into the proper view controller within our app.

You can download completed quick action demo project here.


Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at info@nanostuffs.com, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box