Powered By Blogger
Showing posts with label iPhone SDK. Show all posts
Showing posts with label iPhone SDK. 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,

Saturday, February 28, 2015

Attributed string for multi-purpose in iPhone SDK.

Hi,
This post is regarding the use of attributed string for multi-purpose. For more, please check below statements.

NSString *mainString = @"iphoneappcode.blogspot.com";
    NSMutableAttributedString * attributedString;
    UILabel *lbl;
    
    //-- Attributed string with Multiple Colour Combinations. - (NSForegroundColorAttributeName)
    
    attributedString = [[NSMutableAttributedString alloc] initWithString: mainString];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,13)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(13,9)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(22,4)];
    
    lbl = (UILabel *)[self.view viewWithTag:1001];
    lbl.attributedText = attributedString;
    
    //-- Attributed string with different size of font. - (NSFontAttributeName)
    
    attributedString = [[NSMutableAttributedString alloc] initWithString:mainString];
    [attributedString addAttribute:NSFontAttributeName
                             value:[UIFont fontWithName:@"Helvetica-Bold" size:16.0f]
                             range:NSMakeRange(5, 8)];
    
    lbl = (UILabel *)[self.view viewWithTag:1002];
    lbl.attributedText = attributedString;
    
    //-- Attributed string with foreground and background colours. -  (NSForegroundColorAttributeName)
    
    UIColor *_blue = [UIColor magentaColor];

    attributedString = [[NSMutableAttributedString alloc] initWithString:mainString];
    [attributedString addAttribute:NSForegroundColorAttributeName value:_blue range:NSMakeRange(0, [mainString length])];
    
    lbl = (UILabel *)[self.view viewWithTag:1003];
    lbl.attributedText = attributedString;
    
    //-- Attributed string with Underlined format. - (NSUnderlineStyleAttributeName)
    
    mainString = @"iphoneappcode.blogspot.com";
    attributedString = [[NSMutableAttributedString alloc] initWithString:mainString];
    [attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, [mainString length])];
    
    lbl = (UILabel *)[self.view viewWithTag:1004];
    lbl.attributedText = attributedString;
    
    //-- Attributed string with Background color. - (NSBackgroundColorAttributeName)
    
    mainString = @"iphoneappcode.blogspot.com";
    attributedString = [[NSMutableAttributedString alloc] initWithString:mainString];
    // Set background color for entire range
    [attributedString addAttribute:NSBackgroundColorAttributeName
                             value:[UIColor cyanColor]
                             range:NSMakeRange(0, [attributedString length])];
    
    lbl = (UILabel *)[self.view viewWithTag:1005];
    lbl.attributedText = attributedString;


Regards,

Nilesh M. Prajapati



Thursday, December 18, 2014

Steps to regenerate libzbar library for 64-bit architecture support.

Hi everyone,
After a long time, I'm back to share some useful things with you. In now a days, I'm busy to make my application 64-bit architecture devices support as per apple's guide line which must be followed before 1st February 2015. So, I have started to make third party libraries compatible to 64-bit architecture. For that, I choose libZbar and steps are as defined below : (iPhone 6 & 6 Plus support)
Step 1 : Download the source code (you must have Mercurial for mac):
Step 2 : Open Terminal and run following commands
        b. To Enter zbar directory command : cd zbar
        c. To checkout command : hg checkout iPhoneSDK-1.3.1
        d. To open project use this command : open iphone/zbar.xcodeproj
Step 3 : In the xcode project edit the "libzbar" scheme and select Release in Build configuration
Step 4 : Go to Build Settings set following Architectures
         a. Architectures - > Standard architectures(armv7,armv72,arm64)
         b. Valid Architectures -> arm64,armv7 armv7s
Step 5 : Compile libzbar for device AND for simulator, here the configuration:
Step 6 : Find the compiled libzbar.a and go in the folder using Teminal.app,
In My Case : /Users/Nell/Library/Developer/Xcode/DerivedData/zbar-gyozyrpbqzvslmfoadhqkwskcesd/Build/Products
Step 7 : In this folder, you should have two sub folders namely "Release-iphoneos" and "Release-iphonesimulator".
Step 8 : using xcode command line tools build your universal lib:
      lipo -create Release-iphoneos/libzbar.a Release-iphonesimulator/libzbar.a -o libzbar.a
Now you can use the libzbar.a created, both in device and simulator.

Regards ,
Nilesh M. Prajapati

Wednesday, May 14, 2014

How to print log for debug mode only in iOS application?

Hi,
Everyone,

Sometimes, we wish to print console in our code for DEBUG mode only. Somehow, We also forget to remove that line from our code too at the time of execution of our product. 


So, I found better solution which helps you to overcome this situation. Please keep below code in your common file and use it anywhere in your code or put it in .pch file of your project.



/******* Start Here ********/

#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...)
#endif

// ALog always displays output regardless of the DEBUG setting

#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

/******* End Here ********/


**** For Example : 

NSString *str = @"https://www.apple.com"
DLog(@"%@",str);

Console : https://www.apple.com



Regards,
Nilesh M. Prajapati

Wednesday, March 26, 2014

how to store event in native calendar of iPhone with EventKit?

Hi,
Here, I'm going to share some lines of code by which you can add an event to native calendar of an iPhone/iPad/iPod touch.  So, please prefer below code to make this functionality visible to your project.

========================================================================

Step 1: Import these framework into your project.
#import <EventKit/EventKit.h>
#import <EventKitUI/EventKitUI.h>

Step 2: Now add below code to your working viewcontroller class. But before doing this make sure that you declare some necessary variables.

-(IBAction)addEventToCalendar:(id)sender
{
    if (!self.defaultCalendar)
    {
        self.eventStore = [[EKEventStore alloc]init];
        self.defaultCalendar = [self.eventStore defaultCalendarForNewEvents];
    }
    // save to iphone calendar
    if([self.eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) // >= iOS 6.0
    {
        // iOS 6 and later
        // This line asks user's permission to access his calendar
        [self.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
         {
             if (granted) // user user is ok with it
             {
                 [self openCalendarEditViewController];
             }
         }
         else // if he does not allow
         {
             [self performSelectorOnMainThread:@selector(callAccessAlert) withObject:nil waitUntilDone:YES];
             return;
         }
         
         }];
    }
    else // < iOS 6.0
    {
        [self openCalendarEditViewController];
    }
}

-(void)openCalendarEditViewController
{
    NSString *address = @“”; // Address of place where the event will be hold
    NSString *businessUrl = @“”; //Url which you want to add with calendar event
    
    NSDate *startdate; //start date and time of event
    NSDate *enddate = //end date and time of event
    NSString *strNotes; //Add notes which you want to share in with Calendar event
    
    EKEventEditViewController  *addController = [[EKEventEditViewController alloc] init];
    // set the addController's event store to the current event store.
    EKEvent *event = [EKEvent eventWithEventStore:self.eventStore];
    event.title = @“”;//title of an event should be unique to display appointments separately
    event.notes = strNotes;
    event.location = address;
    event.URL = [NSURL URLWithString:businessUrl];
    
    event.startDate = startdate;
    event.endDate = enddate;//[startdate dateByAddingTimeInterval:duration];
    
    NSDate *alarmDate = [startdate dateByAddingTimeInterval:-3600];
    NSArray *arrAlarm = [NSArray arrayWithObject:[EKAlarm alarmWithAbsoluteDate:alarmDate]];
    event.alarms= arrAlarm;
    
    [event setCalendar:self.defaultCalendar];
    
    addController.event = event;
    addController.eventStore = self.eventStore;
    addController.modalPresentationStyle = UIModalPresentationPageSheet;
    addController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    addController.editViewDelegate = self;
    addController.navigationBar.tintColor=[UIColor colorWithRed:0.976 green:0.612 blue:0.067 alpha:1];
    // present EventsAddViewController as a modal view controller
    [self presentModalViewController:addController animated:YES];
}

- (void)requestAccessToEntityType:(EKEntityType)entityType completion:(EKEventStoreRequestAccessCompletionHandler)completion
{
}

// Overriding EKEventEditViewDelegate method to update event store according to user actions.
- (void)eventEditViewController:(EKEventEditViewController *)controller
          didCompleteWithAction:(EKEventEditViewAction)action {
    NSError *error = nil;
    EKEvent *thisEvent = controller.event;
    switch (action) {
        case EKEventEditViewActionCanceled:
            // Edit action canceled, do nothing.
            break;
        case EKEventEditViewActionSaved:
            // When user hit "Done" button, save the newly created event to the event store,
            // and reload table view.
            // If the new event is being added to the default calendar, then update its
            // eventsList.
        {
            NSError *err = nil;
            BOOL isSuceess=[controller.eventStore saveEvent:controller.event span:EKSpanThisEvent error:&error];
        }
            break;
        case EKEventEditViewActionDeleted:
            // When deleting an event, remove the event from the event store,
            // and reload table view.
            // If deleting an event from the currenly default calendar, then update its
            // eventsList.
            [controller.eventStore removeEvent:thisEvent span:EKSpanThisEvent error:&error];
            break;
        default:
            break;
    }
    // Dismiss the modal view controller
    [controller dismissModalViewControllerAnimated:YES];
}

// Set the calendar edited by EKEventEditViewController to our chosen calendar - the default calendar.
- (EKCalendar *)eventEditViewControllerDefaultCalendarForNewEvents:(EKEventEditViewController *)controller {
    EKCalendar *calendarForEdit = self.defaultCalendar;
    return calendarForEdit;

}

------------------

Regards,
Nilesh M. Prajapati