PDFView in Swift


Hi Friends,

PDFKit framework is available in iOS 11.0* and macOS 10.4*
Implement few lines of code to view your pdf document in you ViewController.

import PDFKit

Implement in UIViewController.viewDidLoad()

        let pdfView = PDFView(frame: view.bounds)
        pdfView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        view.addSubview(pdfView)
        
        pdfView.autoScales = true
        
        let filePath = Bundle.main.url(forResource: "Sample", withExtension: "pdf")
        pdfView.document = PDFDocument(url: filePath!)
Simulator Screen Shot - iPhone Xʀ - 2020-01-23 at 15.15.07
Sample PDFView snapshot

– How to make an iOS App
Kathiresan Murugan

Internal Browser in Swift 4.2


Hi Friends,

When ever load a browser inside of application. Apple is preferred SafariServices.
This class will help to load a url from anywhere in your project. like from ViewController or any NSObject class.

So, that I have created a class to call a SafariViewController.

import UIKit
import SafariServices

/// Internal browser - Safari service view controller
class Browser: NSObject {
    
    /// SafariViewController
    fileprivate var safariVC: SFSafariViewController!
    
    weak var delegate: BrowserDelegate!
    
    /// Config
    fileprivate func config(_ loadUrl: URL) {
        
        if #available(iOS 11.0, *) {
            let config = SFSafariViewController.Configuration()
            config.barCollapsingEnabled = true
            config.entersReaderIfAvailable = true
            safariVC = SFSafariViewController(url: loadUrl, configuration: config)
        } else {
            // Fallback on earlier versions
            safariVC = SFSafariViewController(url: loadUrl)
        }
    }
    
    /// Initialize Browser
    ///
    /// - Parameter loadUrl: url
    init(loadUrl: URL) {
        super.init()
        config(loadUrl)
    }
    
    /// Start loading url on browser
    func startLoading() {
        
        DispatchQueue.global().sync {
            self.safariVC.delegate = self
        }
        
        if let delegate = delegate { delegate.browserWillAppear(self) }
        UIApplication.shared.keyWindow?.rootViewController?.present(safariVC, animated: true, completion: nil)
    }
}

SFSafariViewControllerDelegate

// MARK: - SFSafariViewControllerDelegate
extension Browser: SFSafariViewControllerDelegate {
    
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        if let delegate = delegate { delegate.browserWillDisappear(self) }
    }
    
}

BrowserDelegate

/// Browser Delegate
protocol BrowserDelegate: NSObjectProtocol {
    
    /// Browser will appeared
    ///
    /// - Parameter browser: browser
    func browserWillAppear(_ browser: Browser)
    
    /// Browser will disappear
    ///
    /// - Parameter browser: browser
    func browserWillDisappear(_ browser: Browser)
}

You can use this class in your ViewController as like below

/// Browser for internal
    fileprivate var browser: Browser!
 browser = Browser(loadUrl: url)
 browser.delegate = self
 browser.startLoading()
// MARK: - BrowserDelegate
extension ViewController: BrowserDelegate {
    
    func browserWillAppear(_ browser: Browser) {
        // Do something here
    }
    
    func browserWillDisappear(_ browser: Browser) {
       // Do something here
    }
}

– How to make an iOS App
ktrkathir

Swift: Implement UserNotifications (Local Notification & Remote Notification)


import UserNotifications

/// Register user notification
func registerUserNotification() {
  UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (permitted, error) in
    if (error != nil) {
      debugPrint("User notification allow status:\(String(describing: error?.localizedDescription))")
    }
  debugPrint("User notification allow status:\(permitted)")
  }
 UIApplication.shared.registerForRemoteNotifications()
}
/// Get UserNotification Permission
func userNotificationAuthorized() {
  UNUserNotificationCenter.current().getNotificationSettings() { (access) in

  switch access.authorizationStatus {
  case .authorized:
   self.println("authorized")
  case .denied:
   self.println("get Permission")
  case .notDetermined:
   self.println("something vital went wrong here")
  }
 }
}

/// Fire local Notification with message string
func requestRichNotification(category categoryName: String, notification identifier: String, from service: String, body message: String, userInfo: [String: Any]!) {

  UNUserNotificationCenter.current().getNotificationSettings { (settings) in
  if settings.authorizationStatus == .authorized {

    // Create Notification Content
    let notificationContent = UNMutableNotificationContent()

    // Configure Notification Content
    notificationContent.title = "" //appName
    notificationContent.subtitle = service
    notificationContent.body = message
    notificationContent.categoryIdentifier = categoryName
    notificationContent.sound = UNNotificationSound.default()

/*
// If you want to attach any image to show in local notification
let url = Bundle.main.url(forResource: "notificationImage", withExtension: ".jpg")
do {
let attachment = try? UNNotificationAttachment(identifier: requestIdentifier, url: url!, options: nil)
content.attachments = [attachment!]
}
*/

    let triggerAfter = UNTimeIntervalNotificationTrigger(timeInterval: 0.5, repeats: false) // Add Trigger schudled notification

    // Create Notification Request
    let request = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: triggerAfter)

    // Add Request to User Notification Center
    UNUserNotificationCenter.current().add(request) { (error) in
     if let error = error {
       debugPrint("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
     } else {
       debugPrint("Local notification updated.")
     }
   }
  } else {
   // Do nothing.
  }

 }
}

In appDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

   UNUserNotificationCenter.current().delegate = self
   return true
}

// MARK: - UserNotificationCenter Delegates
extension AppDelegate: UNUserNotificationCenterDelegate {

 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
   // UserNotification failed to register
   println("I am not available in simulator: \(error.localizedDescription)")
 }

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

   #if (arch(i386) || arch(x86_64)) && os(iOS)
    // FIXME: - Static devicetoken for simulator
    AppInfo.shared.deviceToken = "Simulator-\(AppInfo.shared.deviceName)"
   #else
    //Get Remote notification device token here.
    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

    //Saving push notification Device token
   #endif

   // println("deviceToken: \(deviceTokenString)")
 }

 /// Push notification.
 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
   /// Handle push notification. here
 }
// For handling tap and user actions
 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

  if response.notification.request.content.categoryIdentifier == "NotificationServiceCategory" {

    if response.notification.request.identifier == "localNotification" {
      // let _ = response.notification.request.content.userInfo
    } else {
   // Do something.
   }
  } else {
   // Do something.
  }

 }
 //for displaying notification when app is in foreground
 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

  //If you don't want to show notification when app is open, do something here else and make a return here.
  //Even you you don't implement this delegate method, you will not see the notification on the specified controller. So, you have to implement this delegate and make sure the below line execute. i.e. completionHandler.

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

– How to make an iOS App
ktrkathir