Powered By Blogger
Showing posts with label iOS. Show all posts
Showing posts with label iOS. Show all posts

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, 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