Browse Tag: swift3

Push Notification displayed when application in foreground in iOS 10

Introduction: 

The new framework called “UserNotifications” is introduced with iOS 10 SDK. The UserNotifications framework (UserNotifications.framework) supports the delivery and handling of local and remote notifications when application is in foreground

Steps for implement code to handle push notifications in iOS 10

Import UserNotifications.framework in your AppDelegate file :                                                                              import UserNotifications  and Also add UNUserNotificationCenterDelegate.

Register for Notification :

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerForRemoteNotification()
return true
}
func registerForRemoteNotification() {
if #available(iOS 10.0, *) {
let center  = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
UIApplication.shared.registerForRemoteNotifications()
}
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()

}

}

 Handling delegate methods for UserNotifications :
//MARK: UNUserNotificationCenter Delegate  >= iOS 10
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ UNNotificationPresentationOptions) -> Void) {

       //Called when a notification is delivered to a foreground app.

        let userInfo = notification.request.content.userInfo as? NSDictionary

         completionHandler([.alert, .badge, .sound])

        print(\(userInfo)”)

       }

  @available(iOS 10.0, *)

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        // Called to let your app know which action was selected by the user for a given notification.

        let userInfo = response.notification.request.content.userInfo as? NSDictionary
print(“\(userInfo)”)
}

      Add Push Notifications Entitlements :  Go to your project target’s Capabilities tab and add Push Notifications Entitlements. If it’s available in your     certificates then it will enable directly else configure your profile with the certificates and you can enable this capability by that.

For Detail refer the this link :
http://ashishkakkad.com/2016/09/push-notifications-in-ios-10-swift/

Download PDF file using Alamofire in Swift3

Almofire is a very popular library for networking related coding(eg. API call, Downloading Stuffs etc) and totally developed in swift which is replacement of AFNetworking library of ObjectiveC. It has multiple features like Image cacheing, API call integration,File downloading etc. Today we are going to dive into Download PDF file using Alamofire in Swift.

Pods are available for almofire on GitHub for integration of this library into your own project, some steps are explained as follows:- 

  • First create a pod file for implementing the Alamofire and MBProgressHUD

pod ‘Alamofire’ // Download PDF file
pod ‘MBProgressHUD’ //Downloading Progress Bar

  • We have to create Webview Object for open downloaded PDF url.
  • Use following function in view controller and pass the url string to the function.

 

 func downloadPDFFile(urlString:String)

{

    let hud = MBProgressHUD.showAdded(to: self.view, animated: true)

    hud.mode = MBProgressHUDMode.annularDeterminate

    hud.label.text = “Loading…”

    

    let destination: DownloadRequest.DownloadFileDestination = { _, _ in

      let documentsURL:NSURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as    NSURL

      print(“***documentURL: “,documentsURL)

      let PDF_name : String = “Downloded_PDF_Name”

      let fileURL = documentsURL.appendingPathComponent(PDF_name)

      print(“***fileURL: “,fileURL ?? “”)

       return (fileURL!,[.removePreviousFile, .createIntermediateDirectories])

    }

    Alamofire.download(urlString, to: destination).downloadProgress(closure: { (prog) in

      hud.progress = Float(prog.fractionCompleted)

    }).response { response in

      

      hud.hide(animated: true)

      if response.error == nil, let filePath = response.destinationURL?.path    {

        print(“File Path”,filePath)

      

        //Open this filepath in Webview Object

        

        let fileURL = URL(fileURLWithPath: filePath)

        let request = URLRequest(url: fileURL)

        webView.loadRequest(request)

      }

    }

  }

One fantastic way to Load ‘CollectionView’ inside ‘TableViewCell’ using Two ‘Extensions’ in swift3, iOS

As We know we, Often, we assign a collection view’s data source to its view controller. But here the problem is that we have only one view controller and many collection views.

As I have taken number of ‘Sections’ inside table view. so following is the Solution to distinguish between a collection view on the first section , and one on the second , third and fourth…

So here is a way to store which table view cell a collection view is in.

 

  • TableView : I have taken multiple sections And Only One Row.
  • Collection View : I have Only one Section And Multiple Items.

 

In ViewController.swift Use Following –

  • Extension :

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {

     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int   {

          return 3

     }

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell   {

          let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “UploadCell”, for: indexPath) as!                 UploadCollectionViewCell

          //Code

    return cell

     }

     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath  {       

          print(“Collection view at row \(collectionView.tag) selected index path \(indexPath)”)

     }

}

 

 

In TableViewCell.swift Use Following –

  • Extension :

  extension TableViewCell  {

          func setCollectionViewDataSourceDelegate<D: UICollectionViewDataSource & UICollectionViewDelegate>(_ dataSourceDelegate: D, forRow row: Int) {

               collectionView.delegate = dataSourceDelegate

               collectionView.dataSource = dataSourceDelegate

               collectionView.tag = row

               collectionView.setContentOffset(collectionView.contentOffset, animated:false) // Stops collection view if it was scrolling.

               collectionView.reloadData()

          }

          var collectionViewOffset: CGFloat {

               set { collectionView.contentOffset.x = newValue }

               get { return collectionView.contentOffset.x }

          }

     }

 

*******  One IMP addition in ‘willDisplay’ method of tableView in ViewController.swift  *******

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

          guard let tableViewCell = cell  else { return }

          tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.section)

     }

 

 

Thanks.

NSSortDescriptor in swift 3

To sort an json array using NSSortDescriptor in swift3

 

NSSortDescriptor :

A sort descriptor describes a comparison used to sort a collection of objects. You create an instance of NSSortDescriptor that specifies the property key to be sorted, and whether the comparison should be in ascending, or descending order. A sort descriptor can also specify a method to use when comparing the property key values, rather than the default of compare:.

It is important to remember that NSSortDescriptor does not sort objects. It provides the description of how to sort objects. The actual sorting is done by other classes, often NSArray or NSMutableArray.

NSSortDescriptor objects are constructed with the following parameters:

  • key: for a given collection, the key for the corresponding value to be sorted on for each object in the collection.
  • ascending: a boolean specifying whether the collection should be sorted in ascending (YES) or descending (NO) order.

 

// replace the urlname

let task = URLSession.shared.dataTask(with: NSURL(string: “urlname”)! as URL, completionHandler: { (data, response, error) -> Void in

       if (data != nil || error == nil)

                {

                let dict: AnyObject? = try! JSONSerialization.jsonObject(with: data!, options: []) as AnyObject?

                 if (dict is NSArray)

                {

                    let dictArray : NSArray = dict as! NSArray

                    let aArray : NSMutableArray = NSMutableArray(array: dictArray)

                     //replace keyname whatever you want an array should be sort ,for example , json array contain “id” key 

                     //you want array should be sort using that “id” , keyname should be “id”

                   // if you want array ascending then set value  “true” for key ascending, otherwise set to “false”

                    let descriptor: NSSortDescriptor = NSSortDescriptor(key: “keyname”, ascending: true)

                    // sortedResult is an result array which is sorted using key defined in NSSortDescriptor

                     sortedResults = aArray.sortedArray(using: [descriptor]) as NSArray

                   print(sortedResults)

                    }

                   }

        })

        task.resume()


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