Powered By Blogger

Friday, August 4, 2023

Mobile/Cross Platform App Development with Flutter

Hello everyone,

Once again, after a long long time, I thought to write this article on my new journey with Flutter development. I have just recently started to work as Flutter developer and for that, currently, I'm deep diving with some fresh materials & courses.


Just to give a little bit overview on Flutter for mobile & Mac & web app development, please kindly have a look at below important links which I found during my recent researches.

Dart:

- The most important thing of Flutter app development is DART language which is designed by Lars Bak and Kasper Lund and developed by Google. The programming language can be used to develop web and mobile apps as well as server and desktop applications. It is an object-oriented, class-based, garbage-collected language with C-style syntax.


Flutter:

- Flutter is an open-source UI software development kit created by Google. It is used to develop cross platform applications from a single codebase for any web browser, Fuchsia, Android, iOS, Linux, macOS, and Windows. First described in 2015, Flutter was released in May 2017.

Development Tools:

1. Android Studio
2. Visual Studio Code
3. IntelliJ IDEA
4. XCode (If you're planning to create app for Mac/iOS/iPad devices):
5. Homebrew (for Mac)
6. GiT
7. Cocoapods

Open source libraries:
1. Dart/Flutter Packages
2. Google fonts
3. Google Material Design


Note:
- You can use any of the first 3 IDEs for Flutter development.
- Please have a look at the following link for Flutter's Step by Step guide.


I hope, my this article will help to you to start your journey for Mobile App Development. 
Please keep visiting my blog for my upcoming articles regarding SwiftUI & Flutter development. 


Regards,

Friday, May 3, 2019

how to record/capture screen in iOS with the help of Swift programming?

Hello everyone,

- Nowadays, I'm working for screen recording operation in my one of the projects and it's really an interesting one which I want to share with my blog's followers.

- Please check below code lines for detailed information about implementation with Swift.


import Foundation
import ReplayKit
import AVKit

/// A customised class for Video & Audio recording functionality
class ScreenRecorder {
    var assetWriter: AVAssetWriter?
    var videoInput: AVAssetWriterInput?
    var audioInput: AVAssetWriterInput?
    var recorder = RPScreenRecorder.shared()
    var fileURL: URL?
    var timer: Timer?
    
    // MARK: ====================================
    // MARK: ScreenRecorder with Capture Screen event
    // MARK: ====================================
    
    func startRecording(withFilepath fileURL: URL, recordingHandler:@escaping (Error?) -> Void) {
        do {
            assetWriter = try AVAssetWriter(outputURL: fileURL, fileType:
                AVFileType.mp4)
            //-- Video Input
            let videoOutputSettings: [String: Any] = [
                AVVideoCodecKey: AVVideoCodecType.h264,
                AVVideoWidthKey: UIScreen.main.bounds.size.width,
                AVVideoHeightKey: UIScreen.main.bounds.size.height,
                AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey: 2300000,
                                                  AVVideoProfileLevelKey: AVVideoProfileLevelH264High40]
            ]
            //-- Audio Input
            var channelLayout = AudioChannelLayout()
            channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_1_D
            let audioOutputSettings: [String: Any] = [
                AVNumberOfChannelsKey: 6,
                AVFormatIDKey: kAudioFormatMPEG4AAC_HE,
                AVSampleRateKey: 44100,
                AVEncoderBitRateKey: 128000,
                AVChannelLayoutKey: NSData(bytes: &channelLayout, length: MemoryLayout.size(ofValue: channelLayout))
            ]
            
            audioInput = AVAssetWriterInput(mediaType: .audio, outputSettings: audioOutputSettings)
            videoInput = AVAssetWriterInput (mediaType: .video, outputSettings: videoOutputSettings)
            
            audioInput?.expectsMediaDataInRealTime = true
            videoInput?.expectsMediaDataInRealTime = true
            
            assetWriter?.add(audioInput!)
            assetWriter?.add(videoInput!)
            
            recorder.isMicrophoneEnabled = true
            recorder.startCapture(handler: { (sample, bufferType, error) in
                recordingHandler(error)
                if CMSampleBufferDataIsReady(sample) {
                    if self.assetWriter?.status == AVAssetWriter.Status.unknown {
                        self.assetWriter?.startWriting()
                        self.assetWriter?.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sample))
                    }
                    if self.assetWriter?.status == AVAssetWriter.Status.failed {
                        print("Error occured, status = \(String(describing: self.assetWriter?.status.rawValue)), \(String(describing: self.assetWriter?.error?.localizedDescription)) \(String(describing: self.assetWriter?.error))")
                        self.assetWriter?.cancelWriting()
                        self.assetWriter?.endSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sample))
                        recordingHandler(error)
                        return
                    }
                    //-- Video Data
                    if (bufferType == .video), let isReadyForMoreMediaData = self.videoInput?.isReadyForMoreMediaData, isReadyForMoreMediaData == true {
                        self.videoInput?.append(sample)
                    }
                    //-- Audio Data
                    if (bufferType == .audioApp || bufferType == .audioMic), let isReadyForMoreMediaData = self.audioInput?.isReadyForMoreMediaData, isReadyForMoreMediaData == true {
                        self.audioInput?.append(sample)
                    }
                }
            }, completionHandler: { (error) in
                recordingHandler(error)
            })
        } catch {
            recordingHandler(error)
        }
    }
    
    func stopRecording(handler: @escaping (Error?) -> Void) {
        recorder.stopCapture { (error) in
            handler(error)
            if self.assetWriter?.status == AVAssetWriter.Status.failed || self.assetWriter?.status == AVAssetWriter.Status.cancelled || self.assetWriter?.status == AVAssetWriter.Status.unknown || self.assetWriter?.status == AVAssetWriter.Status.completed {
                return
            } else {
                self.audioInput?.markAsFinished()
                self.videoInput?.markAsFinished()
                self.assetWriter?.finishWriting(completionHandler: {
                })
            }
        }
    }
    
   class func createReplaysFolder() {
        // path to documents directory
        let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        if let documentDirectoryPath = documentDirectoryPath {
            // create the custom folder path
            let replayDirectoryPath = documentDirectoryPath.appending("/Replays")
            let fileManager = FileManager.default
            if !fileManager.fileExists(atPath: replayDirectoryPath) {
                do {
                    try fileManager.createDirectory(atPath: replayDirectoryPath,
                                                    withIntermediateDirectories: false,
                                                    attributes: nil)
                } catch {
                    print("Error creating Replays folder in documents dir: \(error)")
                }
            }
        }
    }
    
   class func filePath(_ fileName: String) -> String {
        createReplaysFolder()
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0] as String
        let filePath: String = "\(documentsDirectory)/Replays/\(fileName).mp4"
        return filePath
    }
}

// MARK: ====================================
// MARK: ScreenRecorder with Recording Event
// MARK: ====================================

extension ScreenRecorder {
    //-- Start screen recording event
    func startRecording(recordingHandler: @escaping(String?) -> Void) {
        guard recorder.isAvailable else {
            recordingHandler("Recording is not available at this time.")
            return
        }
        //recorder.delegate = self
        recorder.isMicrophoneEnabled = true
        recorder.startRecording{ (error) in
            if error == nil {
                #if DEBUG
                print("Started Recording Successfully")
                #endif
                recordingHandler(nil)
            } else {
                recordingHandler(error?.localizedDescription)
            }
        }
    }
    
    //-- Stop screen recording event
    func stopRecording(recordingHandler: @escaping(RPPreviewViewController?, Error?) -> Void) {
        recorder.stopRecording { (preview, error) in
            recordingHandler(preview, error)
        }
    }
}

- Please create one ScreenRecorder.swift file and add the above contents to that file. After this, please import this to another class where you want to implement this functionality. 



For example :


/// Video button click event

@IBAction func btnVideoClicked(_ sender: UIButton) {
    
    sender.isSelected = !sender.isSelected
    
    if sender.isSelected {
        
        startScreenRecording()
        
    } else {
        
        stopScreenRecording()
        
    }
    
}

// MARK: ====================================
// MARK: Start Capturing Part
// MARK: ====================================

/// Start event for Screen Recording
func startScreenRecording() {
    let fileURL = URL(fileURLWithPath: filePath("Recording_\(Date().convertToStringWith(Constants.DateFormates.filedateformat)!)"))
    screenRecorder. startRecording(withFilepath: fileURL!) { (error) in
        if error == nil {
            
        } else {
            #if DEBUG
            print(error ?? "")
            #endif
            sender.isSelected = !sender.isSelected
        }
    }
}

// MARK: ====================================
// MARK: Stop Capturing Part
// MARK: ====================================

/// stop event for Screen Recording
func stopScreenRecording() {
    screenRecorder.stopRecording{ (error) in
        if error == nil {
            sender.isSelected = !sender.isSelected
            // An alert will be displayed to save or delete recorded video
            displayAlertToSaveOrDeleteVideo()
        } else {
            #if DEBUG
            print(error ?? "")
            #endif
        }
    }
}

/// A function to display an alert to save or delete the recorded video
func displayAlertToSaveOrDeleteVideo() {
    DispatchQueue.main.async(execute: {
        let alert = UIAlertController(title: "Recording Finished", message: "Do you want to save or delete recording?", preferredStyle: .alert)
        let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { (action: UIAlertAction) in
            DispatchQueue.main.async(execute: {
                //-- Share annoted image's local path to upload it on server.
                if let savedAnnotedFilePath = screenRecorder.assetWriter?.outputURL.path, FileManager.shared.fileExists(atPath: savedAnnotedFilePath) {
                    do {
                        try AppInfo.shared.fileManager.removeItem(atPath: savedAnnotedFilePath)

                    // recording deleted successfully

                        
                    } catch {
                        self.view?.makeToast(error.localizedDescription)
                    }
                } else {
                    // recorded_file_not_found
                }
            })
        })
        let editAction = UIAlertAction(title: "Save", style: .default, handler: { (action: UIAlertAction) -> Void in
            DispatchQueue.main.async(execute: {
                //-- Share annoted image's local path to upload it on server.
                if let savedAnnotedFilePath = self.assetWriter?.outputURL.path, AppInfo.shared.fileManager.fileExists(atPath: savedAnnotedFilePath) {
                    // MOVE OR UPLOAD FILE TO DESNTINATION
                } else {
                    // recorded_file_not_found
                }
            })
        })
        alert.addAction(editAction)
        alert.addAction(deleteAction)
        self.present(alert, animated: true, completion: nil)
    })
}


- Try this in your project, you will definitely get success and in case of any issue, post your comment. I will try to respond to it with an appropriate solution.


Regards,

Thursday, March 16, 2017

How to integrate "SwiftLint" library into XCode project ?


Hi everyone,

Now a days, I was looking for a tool which can assist the developers to write code with good quality by following some basic standards. A tool which can throws warnings/errors if developer is not following the code writing rules. I have found multiple tools for multiple platforms. But I have chosen "SwiftLint" for "SWIFT" language, which is the same as its prior version "OCLint" for "Objective C".

A) Steps to integrate :



Please read this article's contents carefully to integrate it successfully and below are the steps :

Step 1 : Install ‘Homebrew’ into your Mac using the below command :

a. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Step 2 : Install ‘SwiftLint’ package with the help of below command :

a. brew install swiftlint

Step 3 : To Integrate SwiftLint into current Xcode Project, add a new “Run Script” in Build phase with below contents :

if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

Note 1 : Above code will throw a warning if SwiftLint is not installed on the system. But if you want that all your team member will install it, you can make build failed using following script :

if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
exit 1
fi

Note 2 : Now build your project (⌘B). SwiftLint will automatically identify warnings and errors in your code that does not comply with the default style guide line. Finally we have successfully integrated SwiftLint in our current project. But, If you will compile your project, you ended up with lots of warnings and errors. Even Xcode’s “Single View” project template doesn’t pass SwiftLint’s default validation.


B) Auto correct:


Some of the basic issues (such as whitespace at the end of a line) can be automatically fixed by SwiftLint. Just open the terminal and type the following command in your project root directory.

$ cd path/to/project/root/directory
$ swiftlint autocorrect
$ swiftlint autocorrect --path your_file.swift #For SwiftLint's auto correct on single file


C) To configure the behaviour of SwiftLint :


Now we have to fix all other issues that SwiftLint’s autocorrect was not able to do. But fixing all the issues one time it’s too much complex and time consuming. Fortunately, it provides configuration options to ‘enable/disable’ its pre defined rules. So, Initially I will disable all the rules and enable one by one to break down the bigger task into smaller chunks.


To get started, just create '.swiftlint.yml' in your project’s root directory and paste following contents in it.

disabled_rules:
- trailing_newline
- opening_brace
- empty_count
- comma
- colon
- force_cast
- type_name
- variable_name_min_length
- trailing_semicolon
- force_try
- function_body_length
- nesting
- variable_name
- conditional_binding_cascade
- variable_name_max_length
- operator_whitespace
- control_statement
- legacy_constant
- line_length
- return_arrow_whitespace
- trailing_whitespace
- closing_brace
- statement_position
- type_body_length
- todo
- legacy_constructor
- valid_docs
- missing_docs
- file_length
- leading_whitespace

- Some rules have parameters that you can configure, for example the Type Body Length, how many lines of code the body of a type is allowed to be, can be configured like this:

type_body_length:
- 300 # warning
- 400 # error

D) Summary points :

- To list all available SwiftLint’s rules type following command : ‘$ swiftlint rules’

a) All available rules which you can use are here.

b) You can download the example configuration file from here.

c) Followings are the valid rule identifiers, you can use any of them :
(empty_count , redundant_optional_initialization , trailing_semicolon , statement_position , type_name , unused_enumerated , todo , legacy_constant , force_cast , unused_closure_parameter , nimble_operator , number_separator , comma , sorted_imports , implicit_getter , legacy_cggeometry_functions , force_unwrapping , leading_whitespace , cyclomatic_complexity , control_statement , function_body_length , empty_parentheses_with_trailing_closure , dynamic_inline , type_body_length , unused_optional_binding , operator_whitespace , closure_spacing , prohibited_super_call , object_literal , valid_docs , vertical_whitespace , redundant_void_return , large_tuple , trailing_whitespace , mark , empty_parameters , legacy_nsgeometry_functions , shorthand_operator , closing_brace , class_delegate_protocol , colon , closure_parameter_position , nesting , switch_case_on_newline , file_header , conditional_returns_on_newline , trailing_newline , missing_docs , variable_name , redundant_nil_coalescing , private_unit_test , compiler_protocol_init , return_arrow_whitespace , operator_usage_whitespace , attributes , overridden_super_call , vertical_parameter_alignment , first_where , private_outlet , generic_type_name , explicit_init , legacy_constructor , closure_end_indentation , custom_rules , function_parameter_count , syntactic_sugar , trailing_comma , void_return , valid_ibinspectable , opening_brace , line_length , weak_delegate , force_try , redundant_string_enum_value , file_length)


Regards,
Nilesh

Thursday, January 19, 2017

Core data implementation in Swift 3.0 for iOS 8.0 and later versions.

Hi Everyone,

After a long long time, I'm back along with some creative things not just in Objective C but from now onwards, I'll start to post the articles and queries for Swift language too. Here, I would like to share core data implementation for Swift Language by just creating a singleton.

I've shared some examples for "Add, Update, Delete, Count" operations from my own experience and this will definitely help you to create your own. Just check the below contents :


 - ================================================================

class DBManager: NSObject
{
    //-- singleton declaration
    static let sharedDBManager = DBManager()
    
    override init() {
    }
    
    //MARK: - ================================
    //MARK: Core Data Delegate Methods
    //MARK: ================================
    
    //-- Application Document directory ...
    public lazy var applicationDocumentsDirectory: URL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named in the application's documents Application Support directory.
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return urls[urls.count - 1]
    }()
    
    //-- ManagedObjectModel ...
    private lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = Bundle.main.url(forResource: "mydatabase", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()
    
    //-- Persistent Store Coordinator ...
    private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
        // Create the coordinator and store
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.appendingPathComponent("mydatabase.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            // Configure automatic migration.
            let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ]
            try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
            
            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }
        
        return coordinator
    }()
    
    //-- ManagedObjectContext Creation
    lazy var managedObjectContext: NSManagedObjectContext = {
        var managedObjectContext: NSManagedObjectContext?
        if #available(iOS 10.0, *){
            managedObjectContext = self.persistentContainer.viewContext
        }
        else{
            // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
            let coordinator = self.persistentStoreCoordinator
            managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
            managedObjectContext?.persistentStoreCoordinator = coordinator
        }
        return managedObjectContext!
    }()
    
    //-- iOS - 10 : NSPersistentContainer
    @available(iOS 10.0, *)
    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "mydatabase")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        print("\(self.applicationDocumentsDirectory)")
        return container
    }()
    
    //-- Core Data Saving support
    func saveContext () {
        if self.managedObjectContext.hasChanges {
            do {
                try self.managedObjectContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }
    
    //MARK: - ================================
    //MARK: Below is the example to get user based on cust_id
    //MARK: ================================
    
   
    func getUserWith(_ cust_id : String, completionHandler : @escaping(_ result : User?, _ error : NSError?) -> Swift.Void)
    {
        let context = self.managedObjectContext
        let request: NSFetchRequest<User>
        if #available(iOS 10.0, *) {
            request = User.fetchRequest()
        } else {
            request = NSFetchRequest(entityName: "User")
        }
        request.predicate = NSPredicate(format: "cust_id = %@", cust_id)
        do {
           let arrUser = try context.fetch(request)
            if arrUser.count > 0 {
                completionHandler(arrUser[0], nil)
            }
            else {
                completionHandler(nil, nil)
            }
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
            completionHandler(nil, error)
        }
    }
      
    //MARK: - ================================
    //MARK: Below is the function to delete the records from the core-data table which are not available in Array fetched from backend server.
    //MARK: ================================
        
    func deleteVehicleInfoUsing(_ arrVehicle : Array<Any>)
    {
        print("Vehicle : \(arrVehicle)")
        let context = self.managedObjectContext
        let request: NSFetchRequest<Vehicle>
        if #available(iOS 10.0, *) {
            request = Vehicle.fetchRequest()
        } else {
            request = NSFetchRequest(entityName: "Vehicle")
        }
        request.predicate = NSPredicate(format: "NOT(vehicle_id IN %@)", arrVehicle)
        do {
            let arrVeh = try context.fetch(request)
            for obj_veh in arrVeh {
                context.delete(obj_veh)
            }
            do {
                try context.save()
            } catch let error as NSError {
                print("Could not delete vehicle. \(error), \(error.userInfo)")
            }
        } catch let error as NSError {
            print("Could not delete vehicle. \(error), \(error.userInfo)")
        }
    }
    
    //MARK: - ================================
    //MARK: To “Add” reservation record into the core data table. Likewise you can add your own record to the table.
    //MARK: ================================
    
    func saveReservation(_ obj_addreservation : AddReservation, completionHandler : @escaping(_ result : Bool,_ obj_reservation : Reservation?, _ error : NSError?) -> Swift.Void)
    {
        let context = self.managedObjectContext
        let entity = NSEntityDescription.entity(forEntityName: "Reservation", in: context)
        let obj_reservation = (NSManagedObject(entity: entity!,  insertInto: context) as! Reservation)
        
        obj_reservation.phoneID = obj_addreservation.phoneID
        obj_reservation.locationID = (obj_addreservation.locationID != nil) ? Int64(obj_addreservation.locationID!):0
        obj_reservation.licensePlate = obj_addreservation.licensePlate
        obj_reservation.provinceID = (obj_addreservation.provinceID != nil) ? Int64(obj_addreservation.provinceID!):0
        obj_reservation.vehicleMakeID = (obj_addreservation.vehicleMakeID != nil) ? Int64(obj_addreservation.vehicleMakeID!):0
        obj_reservation.vehicleTypeID = (obj_addreservation.vehicleTypeID != nil) ? Int64(obj_addreservation.vehicleTypeID!):0
        obj_reservation.vehicleColourID = (obj_addreservation.vehicleColourID != nil) ? Int64(obj_addreservation.vehicleColourID!):0
        obj_reservation.openDate = obj_addreservation.openDate
        obj_reservation.closeDate = obj_addreservation.closeDate
        obj_reservation.airlineCode = obj_addreservation.airlineCode
        obj_reservation.flightNum = (obj_addreservation.flightNum != nil) ? Int64(obj_addreservation.flightNum!):0
        obj_reservation.associationNumber = obj_addreservation.associationNumber
        obj_reservation.rewardRedemptionCoupon = obj_addreservation.rewardRedemptionCoupon
        obj_reservation.aeroplanNumber = obj_addreservation.aeroplanNumber
        obj_reservation.ticket_id = obj_addreservation.ticket_id
        
        do {
            try context.save()
            completionHandler(true,obj_reservation,nil)
        } catch let error as NSError {
            print("Could not save reservation. \(error), \(error.userInfo)")
            completionHandler(true, nil, error)
        }
    }
    
    //MARK: - ================================
    //MARK: To fetch all the records from the table in core data instead of specific one
    //MARK: ================================

    func fetchAllReservations(completionHandler : @escaping(_ result : [Reservation]?, _ error : String?) -> Swift.Void)
    {
        let context = self.managedObjectContext
        let request: NSFetchRequest<Reservation>
        if #available(iOS 10.0, *) {
            request = Reservation.fetchRequest()
        } else {
            request = NSFetchRequest(entityName: "Reservation")
        }
        do {
            let arrReservation = try context.fetch(request)
            if arrReservation.count > 0 {
                completionHandler(arrReservation, nil)
            }
            else {
                completionHandler([], "No reservation found.")
            }
        } catch let error as NSError {
            print("Could not fetch reservation. \(error), \(error.userInfo)")
            completionHandler([], error.localizedDescription)
        }
    }
    
    //MARK: - ================================
    //MARK: To fetch the count of records from the table in core data
    //MARK: ================================

    func getTotalReservation() -> Int
    {
        let context = self.managedObjectContext
        let request: NSFetchRequest<Reservation>
        if #available(iOS 10.0, *) {
            request = Reservation.fetchRequest()
        } else {
            request = NSFetchRequest(entityName: "Reservation")
        }
        request.includesPropertyValues = false
        
        do {
            let count = try context.count(for: request)
            return count
        } catch let error as NSError {
            print("Error: \(error.localizedDescription)")
            return 0
        }
    }
}

- ================================================================

Regards,
Nileshkumar M. Prajapati