func shareVideoToInstagram() {
let strURL = "http://mobmp4.org/files/data/2480/Tutak%20Tutak%20Tutiya%20Title%20Song%20-%20Remix%20-%20Drunx%20-%20Mp4.mp4"
let caption = "Some Preloaded Caption"
let captionStr = caption.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! as String
let videoURL = URL(fileURLWithPath: strURL, isDirectory: false)
let library = ALAssetsLibrary()
library.writeVideoAtPath(toSavedPhotosAlbum: videoURL) { (newURL, error) in
if let instagramURL = NSURL(string: "instagram://library?AssetPath=\(videoURL.absoluteString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!)&InstagramCaption=\(captionStr)") {
print(instagramURL)
if UIApplication.shared.canOpenURL(instagramURL as URL) {
UIApplication.shared.openURL(instagramURL as URL)
}
} else {
print("NO")
}
}
}
I got instagramURL like this:
instagram://library?AssetPath=file:%2F%2F%2Fhttp:%2Fmobmp4.org%2Ffiles%2Fdata%2F2480%2FTutak%252520Tutak%252520Tutiya%252520Title%252520Song%252520-%252520Remix%252520-%252520Drunx%252520-%252520Mp4.mp4&InstagramCaption=Some%20Preloaded%20Caption
And I successfully openURL but I can not found my video which I want to share on instagram.
func shareVideoToInstagram() {
let videoFilePath = "http://mobmp4.org/files/data/2480/Tutak%20Tutak%20Tutiya%20Title%20Song%20-%20Remix%20-%20Drunx%20-%20Mp4.mp4"
let instagramURL = NSURL(string: "instagram://app")
if (UIApplication.shared.canOpenURL(instagramURL! as URL)) {
let url = URL(string: ("instagram://library?AssetPath="+videoFilePath))
if UIApplication.shared.canOpenURL(url!) {
UIApplication.shared.open(url!, options: [:], completionHandler:nil)
}
} else {
print(" Instagram isn't installed ")
}
}
First, you need a NSData from video:
guard
let videoPath = "http://mobmp4.org/files/data/2480/Tutak%20Tutak%20Tutiya%20Title%20Song%20-%20Remix%20-%20Drunx%20-%20Mp4.mp4",
let videoUrl = URL(string: videoPath),
let videoData = NSData(contentsOf: videoUrl)
else {
return
}
postVideoToInstagramFeed(videoData: videoData)
and share with the function:
func postVideoToInstagramFeed(videoData: NSData) {
getLibraryPermissionIfNecessary { granted in
guard granted else { return }
}
PHPhotoLibrary.shared().performChanges({
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
let filePath = "\(documentsPath)/\(Date().description).mp4"
videoData.write(toFile: filePath, atomically: true)
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
},
completionHandler: { success, error in
if success {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions)
if let lastAsset = fetchResult.firstObject {
let localIdentifier = lastAsset.localIdentifier
let urlFeed = "instagram://library?LocalIdentifier=" + localIdentifier
guard
let url = URL(string: urlFeed)
else {
print("Could not open url")
return
}
DispatchQueue.main.async {
if UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
print("Sucess")
})
}
else {
UIApplication.shared.openURL(url)
print("Sucess")
}
}
else {
print("Instagram not found")
}
}
}
}
else if let error = error {
print(error.localizedDescription)
}
else {
print("Could not save the video")
}
})
}
func getLibraryPermissionIfNecessary(completionHandler: #escaping (Bool) -> Void) {
guard PHPhotoLibrary.authorizationStatus() != .authorized else {
completionHandler(true)
return
}
PHPhotoLibrary.requestAuthorization { status in
completionHandler(status == .authorized)
}
}
Related
I'm trying to share a post from Instagram with swiftui, but it didn't work, I didn't have any problems while sharing a story, but the post screen doesn't open when sharing a post.
// plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>instagram</string>
<string>instagram-stories</string>
</array>
The below code worked for me.
Button {
if post.post_type != PostType.mp4.rawValue {
let imagedData = NSData(contentsOf: imageURL)!
InstagramManager.instance.postImage(image: UIImage(data: imagedData as Data)!) { success in
print("insgram shared success = \(success)")
}
} else {
let videoData = NSData(contentsOf: videoUrl!)
InstagramManager.instance.postVideoToInstagramFeed(videoData: videoData!)
}
import SwiftUI
import Photos
final class InstagramManager : NSObject {
public static let instance = InstagramManager()
func postImage(image: UIImage, result:((Bool)->Void)? = nil) {
guard let instagramURL = NSURL(string: "instagram://app") else {
if let result = result {
result(false)
}
return
}
// let image = image.scaleImageWithAspectToWidth(640)
do {
try PHPhotoLibrary.shared().performChangesAndWait {
let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetID = request.placeholderForCreatedAsset?.localIdentifier ?? ""
let shareURL = "instagram://library?LocalIdentifier=" + assetID
if UIApplication.shared.canOpenURL(instagramURL as URL) {
if let urlForRedirect = NSURL(string: shareURL) {
UIApplication.shared.open(URL(string: "\(urlForRedirect)")!)
}
}
}
} catch {
if let result = result {
result(false)
}
}
}
func postVideoToInstagramFeed(videoData: NSData) {
getLibraryPermissionIfNecessary { granted in
guard granted else { return }
}
PHPhotoLibrary.shared().performChanges({
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
let filePath = "\(documentsPath)/\(Date().description).mp4"
videoData.write(toFile: filePath, atomically: true)
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
},
completionHandler: { success, error in
if success {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "modificationDate", ascending: false)]
let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions)
if let lastAsset = fetchResult.firstObject {
let localIdentifier = lastAsset.localIdentifier
let urlFeed = "instagram://library?LocalIdentifier=" + localIdentifier
guard
let url = URL(string: urlFeed)
else {
print("Could not open url")
return
}
DispatchQueue.main.async {
if UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
print("Sucess")
})
}
else {
UIApplication.shared.openURL(url)
print("Sucess")
}
}
else {
print("Instagram not found")
}
}
}
}
else if let error = error {
print(error.localizedDescription)
}
else {
print("Could not save the video")
}
})
}
func getLibraryPermissionIfNecessary(completionHandler: #escaping (Bool) -> Void) {
guard PHPhotoLibrary.authorizationStatus() != .authorized else {
completionHandler(true)
return
}
PHPhotoLibrary.requestAuthorization { status in
completionHandler(status == .authorized)
}
}
}
import UIKit
extension UIImage {
// MARK: - UIImage+Resize
func scaleImageWithAspectToWidth(_ toWidth:CGFloat) -> UIImage {
let oldWidth:CGFloat = size.width
let scaleFactor:CGFloat = toWidth / oldWidth
let newHeight = self.size.height * scaleFactor
let newWidth = oldWidth * scaleFactor;
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
I am working on a Video sharing iOS app and using Firebase5 as backend. It allow User can choose video and send it to storage. When I tried the video cannot push to database server. Below is my code:
static func uploadVideoToFirebaseStorage(videoUrl: URL, onSuccess: #escaping (_ videoUrl: String) -> Void) {
let videoIdString = NSUUID().uuidString
//Config.STORAGE_ROOT_REF is var STORAGE_ROOT_REF = "gs://****-cdc3c.appspot.com"
let storageRef = Storage.storage().reference(forURL: Config.STORAGE_ROOT_REF).child("posts").child(videoIdString)
storageRef.putFile(from: videoUrl, metadata: nil) { (metadata, error) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
}
storageRef.downloadURL(completion: { (url, error) in
if let error = error {
return
}else {
let videoUrl = url!.absoluteString
onSuccess(videoUrl)
}
})
}
Call this function to upload the video to firebase storage
func uploadTOFireBaseVideo(url: URL,
success : #escaping (String) -> Void,
failure : #escaping (Error) -> Void) {
let name = "\(Int(Date().timeIntervalSince1970)).mp4"
let path = NSTemporaryDirectory() + name
let dispatchgroup = DispatchGroup()
dispatchgroup.enter()
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let outputurl = documentsURL.appendingPathComponent(name)
var ur = outputurl
self.convertVideo(toMPEG4FormatForVideo: url as URL, outputURL: outputurl) { (session) in
ur = session.outputURL!
dispatchgroup.leave()
}
dispatchgroup.wait()
let data = NSData(contentsOf: ur as URL)
do {
try data?.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch {
print(error)
}
let storageRef = Storage.storage().reference().child("Videos").child(name)
if let uploadData = data as Data? {
storageRef.putData(uploadData, metadata: nil
, completion: { (metadata, error) in
if let error = error {
failure(error)
}else{
let strPic:String = (metadata?.downloadURL()?.absoluteString)!
success(strPic)
}
})
}
}
Following function converts the video to mp4 format so that it can be viewed on any device either it be iOS or android
func convertVideo(toMPEG4FormatForVideo inputURL: URL, outputURL: URL, handler: #escaping (AVAssetExportSession) -> Void) {
try! FileManager.default.removeItem(at: outputURL as URL)
let asset = AVURLAsset(url: inputURL as URL, options: nil)
let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)!
exportSession.outputURL = outputURL
exportSession.outputFileType = .mp4
exportSession.exportAsynchronously(completionHandler: {
handler(exportSession)
})
}
Call this function to upload video the firebase storage. Its working for me incase any confusion you can ask
static func upload(file: URL, completion: #escaping UploadCompletion) {
let name = "\(Int(Date().timeIntervalSince1970)).mp4"
do {
let data = try Data(contentsOf: file)
let storageRef =
Storage.storage().reference().child("Videos").child(name)
if let uploadData = data as Data? {
let metaData = StorageMetadata()
metaData.contentType = "video/mp4"
storageRef.putData(uploadData, metadata: metaData
, completion: { (metadata, error) in
if let error = error {
completion(nil, error.localizedDescription)
}else{
storageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
completion(nil, error?.localizedDescription ?? "")
return
}
completion(downloadURL, nil)
}
}
})
}
}catch let error {
print(error.localizedDescription)
}
}
How To Download PDF file in IOS using Swift 3.0 and Alamofire . i can able to fetch url with nsurlsession. But i am looking for alamofire code.
please see my code.
func downloadPdffile(_ sender : UIButton) {
print(sender.tag)
print("ARRAY VALUES FROM CELL",totalSyllabusArray.object(at: sender.tag))
var localDic :NSDictionary!
localDic = totalSyllabusArray.object(at: sender.tag) as! NSDictionary
let filepath = localDic["filepath"] as! String
print("pressed ")
let strURL1:String = FETCH_InMegh_Image_BaseURL + filepath
print("strURL1 is ",strURL1)
let pathURL = URL(string: strURL1)!
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = try! URLRequest(url: pathURL, method: .get)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Success: \(statusCode)")
print("tempLocalUrl: \(tempLocalUrl)")
} else {
print("Failure: %#", error?.localizedDescription);
}
}
}
}
}
Define your destination something like that:
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("your.pdf")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
And call Alamofire.download with your url and destination:
Alamofire.download(yourUrl), to: destination).response { response in
let parentView = (self.superview?.superview as! UITableView).dataSource as! ProcedureViewController
parentView.hideActivityIndicator()
if response.error == nil, let _ = response.destinationURL?.path {
//open pdf in UIDocumentInteractionController
self.docController = UIDocumentInteractionController.init(url: response.destinationURL!)
self.docController?.delegate = self.delegate!
self.docController?.name = ""
self.docController?.presentOptionsMenu(from: self.parentView!.bounds, in: self.parentView!, animated: true)
}
}
I am trying to complet an an action after the URLSession resumes.
So I am downloading several images from my server with the url, which all works good. But now I am trying to save those images to the disk after I have finished downloading them.
Problem
Now I can save them inside the same query while downloading them but I would prefer not too as it makes my query slower.
So I have added a completion handler to my func with the query, but when I save the images to the disk in that block it works but I cannot do anything with my screen as the query has not resumed yet it is blocked from touches I guess...
Now I would like to be able to call my func to save the images to the disk straight after the query has been resumed.... Anyone have any idea?
If someone needs more explanation or to see code just drop a comment below
Many thanks in advance to anyone that can help!
Code for downloading
func loadPosts(completionHandler: #escaping (Bool) -> ()) {
pageNumber = 1
appDelegate.setNetworkActivityIndicatorVisible(true)
let id = user!["id"] as! String
let url = URL(string: "http://************/Files/Posts.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let body = "id=\(id)&caption=&uuid=&page="
request.httpBody = body.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in
DispatchQueue.global(qos: .background).async {
if error == nil {
let oldImageArray = self.cellContentArray
self.cellContentArray.removeAll(keepingCapacity: false)
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
guard let parseJSON = json else {
print("Error while parsing")
return
}
guard let posts = parseJSON["Posts"] as? [AnyObject] else {
print("Error while parseJSONing")
return
}
for element in posts {
// here I download the stuff and it to my Array, too long and no point to show here
}
let oldImageSet = Set(oldImageArray.map({return $0.uuid}))
let newImageSet = Set(self.cellContentArray.map({return $0.uuid}))
let addedImages = newImageSet.subtracting(oldImageSet)
let addedImageSections = Array(addedImages).map{ self.cellContentArray.map({return $0.uuid}).index(of: $0)! }
let addedImageIndexSet = IndexSet(addedImageSections)
let removedImages = oldImageSet.subtracting(newImageSet)
let removedImageSections = Array(removedImages).map{ oldImageArray.map({return $0.uuid}).index(of: $0)! }
let removedImageIndexSet = IndexSet(removedImageSections)
if !addedImageIndexSet.isEmpty {
if oldImageArray.count >= 5 {
self.lastUUIDImage = oldImageArray[4].uuid
} else {
}
self.coreDataShit()
}
DispatchQueue.main.async{
print(placeholderImage.count)
if placeholderImage.count > 5 {
placeholderImage.removeFirst(placeholderImage.count - 5)
}
print("finished")
self.customView.isHidden = true
if posts.count >= 5 {
self.tableView.addInfiniteScroll { [weak self] (scrollView) -> Void in
self?.loadMore()
}}
self.activityView.stopAnimating()
self.internetView.removeFromSuperview()
self.tableView.beginUpdates()
if !addedImageIndexSet.isEmpty {
self.tableView.insertSections(addedImageIndexSet, with: .top)
}
if !removedImageIndexSet.isEmpty {
self.tableView.deleteSections(removedImageIndexSet, with: .bottom)
}
self.tableView.endUpdates()
self.tableView.finishInfiniteScroll()
self.refresher.endRefreshing()
appDelegate.setNetworkActivityIndicatorVisible(false)
completionHandler(true)
}
} catch {
DispatchQueue.main.async {
self.tableView.removeInfiniteScroll()
self.customView.isHidden = false
self.refresher.endRefreshing()
self.tableView.reloadData()
}
}
} else {
DispatchQueue.main.async(execute: {
let message = error!.localizedDescription
appDelegate.infoView(message: message, color: smoothRedColor)
})
}
}
})
task.resume()
}
Saving Image
self.loadPosts(completionHandler: { (true) in
print("completion")
let sections = self.tableView.numberOfSections
for i in 0..<sections {
self.rows += self.tableView.numberOfRows(inSection: i)
}
print(self.rows)
if self.rows <= 5 {
print("less than 5")
print(self.rows)
var i = 0
for element in self.cellContentArray {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let dirPath = "\(path)/images"
let url = NSURL(fileURLWithPath: dirPath)
let filePath = url.appendingPathComponent("\(element.uuid).jpg")?.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath!) {
print("File exsists")
} else {
print("File doesn't exsist")
DispatchQueue.main.async {
let url = NSURL(string: element.fullImage!)! // convert path str to url
let imageData = NSData(contentsOf: url as URL) // get data via url and assigned imageData
let imageName = element.uuid
let saveImages = FileSaveHelper(fileName: imageName, fileExtension: .JPG, subDirectory: "images", directory: .documentDirectory)
do {
guard let image = UIImage.sd_image(with: imageData as Data!) else {
print("Error getting image")
return
}
try saveImages.saveFile(image: image)
self.saveNewImagePath(imageLink: imageName, uuid: imageName)
self.removeImage(itemName: "file\(i)", fileExtension: "jpg")
self.removeImage(itemName: self.lastUUIDImage, fileExtension: "jpg")
i += 1
} catch {
print(error)
}
}
}
}
}
})
Image in tableView Cell
self.postImage.sd_setImage(with: URL(string: content.fullImage!), placeholderImage: placeHolder, options: .retryFailed) { (image:UIImage?, error:Error?, cached:SDImageCacheType, url:URL?) in
}
In your code of saving image this line of code is blocking you UI
let imageData = NSData(contentsOf: url as URL) // get data via url and assigned imageData
This is not proper way to download image from server, you should download image asynchronously using URLSession
I have read lots of tutorials for video player. But How to start recording when camera open in a custom view with time limit.
Here is the working solution with a swift version
var session: AVCaptureSession?
var userreponsevideoData = NSData()
var userreponsethumbimageData = NSData()
override func viewDidLoad() {
super.viewDidLoad()
createSession()
}
func for stopRecording(){
session?.stopRunning()
}
func createSession() {
var input: AVCaptureDeviceInput?
let movieFileOutput = AVCaptureMovieFileOutput()
videosPreviewLayer?.frame.size = photoPreviewImageView.frame.size
session = AVCaptureSession()
let error: NSError? = nil
do { input = try AVCaptureDeviceInput(device: self.cameraWithPosition(position: .back)!) } catch {return}
if error == nil {
session?.addInput(input!)
} else {
print("camera input error: \(String(describing: error))")
}
videosPreviewLayer = AVCaptureVideoPreviewLayer(session: session!)
videosPreviewLayer?.frame.size = self.photoPreviewImageView.frame.size
videosPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
videosPreviewLayer?.connection?.videoOrientation = .portrait
photoPreviewImageView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
photoPreviewImageView.layer.addSublayer(videosPreviewLayer!)
switchCameraButton.isHidden=true
flashButton.isHidden=true
msgLabel.isHidden=true
galleryCollectionView.isHidden=true
timerLabel.isHidden=false
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
fileURL = URL(string:"\(documentsURL.appendingPathComponent("temp"))" + ".mov")
print("*****fileurl%#",fileURL ?? "00000")
let maxDuration: CMTime = CMTimeMake(600, 10)
movieFileOutput.maxRecordedDuration = maxDuration
movieFileOutput.minFreeDiskSpaceLimit = 1024 * 1024
if self.session!.canAddOutput(movieFileOutput) {
self.session!.addOutput(movieFileOutput)
}
session?.startRunning()
movieFileOutput.startRecording(to: fileURL!, recordingDelegate: self)
}
func cameraWithPosition(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
let devices = AVCaptureDevice.devices(for: AVMediaType.video)
for device in devices {
if device.position == position {
return device
}
}
return nil
}
}
extension SwipeGallerymainViewController: AVCaptureFileOutputRecordingDelegate
{
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
print(outputFileURL)
let filemainurl = outputFileURL
do
{
let asset = AVURLAsset(url:filemainurl as URL, options:nil)
print(asset)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
let uiImage = UIImage(cgImage: cgImage)
previewImage = uiImage
userreponsethumbimageData = NSData(contentsOf: filemainurl as URL)!
print(userreponsethumbimageData.length)
print(uiImage)
}
catch let error as NSError
{
print(error)
return
}
let VideoFilePath = URL(fileURLWithPath:NSTemporaryDirectory()).appendingPathComponent("mergeVideo\(arc4random()%1000)d").appendingPathExtension("mp4").absoluteString
if FileManager.default.fileExists(atPath: VideoFilePath)
{
print("exist")
do
{
try FileManager.default.removeItem(atPath: VideoFilePath)
}
catch { }
}
let tempfilemainurl = NSURL(string: VideoFilePath)!
let sourceAsset = AVURLAsset(url:filemainurl as URL, options:nil)
let assetExport: AVAssetExportSession = AVAssetExportSession(asset: sourceAsset, presetName: AVAssetExportPresetMediumQuality)!
assetExport.outputFileType = AVFileType.mov
assetExport.outputURL = tempfilemainurl as URL
assetExport.exportAsynchronously { () -> Void in
switch assetExport.status
{
case AVAssetExportSessionStatus.completed:
DispatchQueue.main.async {
do
{
self.userreponsevideoData = try NSData(contentsOf: tempfilemainurl as URL, options: NSData.ReadingOptions())
print("MB - \(self.userreponsevideoData.length) byte")
self.isVideoLoad=true
self.performSegue(withIdentifier:"previewSegue", sender:self)
}
catch
{
print(error)
}
}
case AVAssetExportSessionStatus.failed:
print("failed \(String(describing: assetExport.error))")
case AVAssetExportSessionStatus.cancelled:
print("cancelled \(String(describing: assetExport.error))")
default:
print("complete")
}
}
}
func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
print(fileURL)
}
}
I have done same thing in java using Robot class on laptop. Robot class is capable of sending keystrokes and mouse movements automatically. You can try same thing on your platform. Automate the button press event so that recording get started.