URL of screen recording from ReplayKit - swift

I like to get the url of the ReplayKit screen recording instead of saving the video to my camera roll or forwarding it. From a WWDC 2017 video, it was mentioned that to get the url, one can use the following function:
func stopRecording(withOutput url: URL, completionHandler: ((Error?) -> Void)? = nil){}
But I am having a hard time figuring out how to call/implement this line of code. I have a start recording #IBAction button and a stop recording #IBAction button. The screen recording is working fine. However, can someone show me how or/and where to add this stopRecording function so I can get the url for the screen recording? Appreciate any help pointing me to the right direction. I am still learning Xcode. Thank-you!
#IBAction func StartScreenRec( sender: Any) {
screenrecorder.startRecording { (error) in
if let error = error {
print(error)
}
self.ScreenStartRecordBtn.isHidden = true
self.StopScreenRecBtn.isHidden = false
}
}
#IBAction func StopScreenRec( sender: Any) {
screenrecorder.stopRecording { (previewVC, error) in
if let previewVC = previewVC {
previewVC.modalPresentationStyle = .fullScreen
previewVC.previewControllerDelegate = self
self.present(previewVC, animated: true, completion: nil)
}
if let error = error {
print(error)
}
self.ScreenStartRecordBtn.isHidden = false
self.StopScreenRecBtn.isHidden = true
}
}

I hope this helps -
To get the URL of the Video that you've just recorded, you need to specify the URL first, then assign the withOutput Function:
outputURL = tempURL()
recorder.stopRecording(withOutput: outputURL) { (error) in
guard error == nil else{
print("Failed to save ")
return
}
print(self.outputURL)
}
And this is for the tempURL() Function:
func tempURL() -> URL? {
let directory = NSTemporaryDirectory() as NSString
if directory != "" {
let path = directory.appendingPathComponent(NSUUID().uuidString + ".mp4")
return URL(fileURLWithPath: path)
}
return nil
}

Related

How to get the value of searchBar.text of one VC and use it in another file of the project in swift?

I've been looking for the answer everywhere and could't find any.. Is there any way I can access the value of searchBar.text in another file? I have the delegate set in my SearchVC but I also have a custom tableView cell in another file.
I need the value of the SearchBar of my SearchVC to use in FirstDefinitionVC for decoding the word from the searchBar and use it for finding the audio URL.
All works fine while I call the function inside the searchBarSearchButtonClicked method but I can find no way to pass that String into FirstDefintionVC.
The relevant searchVC code :
var word = ""
`
extension SearchVC: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
// { (data: [WordData], [Definitions])
word = searchBar.text!
wordManager.performRequest(word: word) { data in
self.wordData = data
self.searchButtonPressed = true
// print(data)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
fetchAudio(word: word) { data in //this one works fine
DispatchQueue.main.async {
self.wordData = data
}
}
}
func fetchAudio(word: String, comp: #escaping ([WordData])-> Void) {
let wordURL = "https://api.dictionaryapi.dev/api/v2/entries/en/"
let urlString = "\(wordURL)\(word)"
if let url = URL(string: urlString) {
let dataTask = URLSession.shared.dataTask(with: url, completionHandler: {
(data,response,error) in
guard let data = data, error == nil else {
print("Error occured while accessing data with URL")
return
}
do {
let decoded = try JSONDecoder().decode([WordData].self, from: data)
comp(decoded)
if let sound = decoded[0].phonetics[0].audio,
let sound2 = decoded[0].phonetics[1].audio {
print("sound = \(sound)")
let nonEmpty = (sound != "") ? sound : sound2 //write switch cases or another ternary with more urls to choose from if both are empty
self.audioUrl = URL(string: nonEmpty)
// url = URL(string: sound2)
do {
try AVAudioSession.sharedInstance().setMode(.default)
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
self.player = AVPlayer(url: self.audioUrl!)
guard let player = self.player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
//comp(decoded, entries.self)
} catch {
print("Error occured while decoding JSON into Swift structure \(error)")
}
})
dataTask.resume()
}
}
I need to call the searchBar.text value in another file inside this IBAction of class FirstDefinitionVC:
`
#IBAction func pronunciationButton(_ sender: UIButton) {
searchVC.fetchAudio(word: searchVC.word) { data in
self.wordData = data
}
}
This was one of my approaches to this, I tried to create a global model Word with an initializer also and it didn't work. Is there any way around it?

Post Video to Facebook with swift SDK

I have been trying to figure this out all day and yesterday night, but no luck. I can confirm that the LinkShareContent works but when I try to share a video file. It gives me an error code "reserved" but nothing else.
This is the code for the link
var content = LinkShareContent(url: URL(string: "https://google.com")!)
showShareDialog(content)
and this is the code for the video that does not work at all.
let video = Video(url: url)
var content = VideoShareContent(video: video, previewPhoto: Photo(image: inProgressItem.firstImage, userGenerated: true))
showShareDialog(content)
This will show the share Sheet on the controller
Func showShareDialog<C: ContentProtocol>(_ content: C, mode: ShareDialogMode = .shareSheet) {
let dialog = ShareDialog(content: content)
dialog.presentingViewController = self
dialog.mode = mode
do{
try dialog.show()
}
catch (let error){
print(error)
}
}
I have confirmed that the video is on the local path and I'm testing the app on iPhone 8 11.1.2
Had exactly the same issue. It was working for LinkShareContent but didn't work for VideoShareContent.
The solution:
Make sure you are getting the right URL for the video. The right one is the URL for key "UIImagePickerControllerReferenceURL" from info dictionary that comes from UIImagePickerController delegate method.
Working Code:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
picker.dismiss(animated: true)
if let videoURL = info["UIImagePickerControllerReferenceURL"] as? URL {
let video = Video(url: videoURL)
let content = VideoShareContent(video: video)
let dialog = ShareDialog(content: content)
dialog.failsOnInvalidData = true
dialog.mode = .native
dialog.presentingViewController = self
do {
try dialog.show()
} catch {
print(error)
}
}
}
Extra info: initially I did not use this key "UIImagePickerControllerReferenceURL" cuz it's deprecated. Apple advises using UIImagePickerControllerPHAsset instead. But the URL from there also returns reserved error. Another try was to use key "UIImagePickerControllerMediaURL", but it also didn't succeed.
I use PHPickerViewController instead of UIPickerController.
private lazy var videoPickerController: PHPickerViewController = {
let photoLibrary = PHPhotoLibrary.shared()
var configuration = PHPickerConfiguration(photoLibrary: photoLibrary)
configuration.selectionLimit = 1
configuration.filter = .any(of: [.videos])
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = self
return picker
}()
Then using PHAsset for initialisation ShareVideo(videoAsset:).
private func facebookShare(content: Content) {
guard let schemaUrl = URL(string: "fb://") else {
return
}
if UIApplication.shared.canOpenURL(schemaUrl) {
let video = ShareVideo(videoAsset: content)
let content = ShareVideoContent()
content.video = video
let dialog = ShareDialog(
viewController: self,
content: content,
delegate: self
)
do {
try dialog.validate()
} catch let error as NSError {
presentAlert(message: (error.userInfo[ErrorDeveloperMessageKey] as? String) ?? error.localizedDescription)
} catch {
presentAlert(message: error.localizedDescription)
}
if dialog.canShow {
dialog.show()
}
} else {
presentAlert(message: "FB app not installed")
}
}
And PHPickerViewControllerDelegate looks something like this (I always select only 1 asset that's why I use fetchResult.firstObject)
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
let identifiers = results.compactMap(\.assetIdentifier)
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: identifiers, options: nil)
guard let videoAsset = fetchResult.firstObject else { return }
}
This solution works for iOS 14 and higher and if on your device Facebook app installed.
Also before upload video I login via FB.

AVPlayer with downloaded content doesn't work but streaming content does

I am trying to (1) download a piece of audio from a link, (2) add that newly-downloaded audio to an AVPlayer and (3) play it. Something is going wrong at step (3) and I'm looking for any guidance. Here's the code, including my alamofire and download functions, as I fear something may be going wrong at that stage.
import AVFoundation
class SettingAlarmViewController: UIViewController {
var player:AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}
catch {
// report for an error
}
}
func getLatestPodcastURL(completion: #escaping (URL) -> ()) {
let RSSUrl: String = "https://www.npr.org/rss/podcast.php?id=510318"
Alamofire.request(RSSUrl).responseRSS() {response in
if let podcastURL: String = response.result.value?.items[0].enclosure!
{
let audioURL = URL(string: podcastURL)
completion(audioURL!)
}
else {
//error handling
}
}
}
func downloadSongAsynch(audioUrl: URL, completion: #escaping (URL) -> ()) {
let fileManager = FileManager.default
let documentsDirectoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("podcasts/")
do {
try fileManager.createDirectory(atPath: documentsDirectoryURL.path,
withIntermediateDirectories: true, attributes: nil)
} catch {
//error handling
}
let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in
guard let location = location, error == nil else { return }
do {
try FileManager.default.moveItem(at: location, to: destinationUrl)
} catch {
//error handling
}
}).resume()
completion(destinationUrl)
}
#IBAction func SetUpBotton(_ sender: Any) {
getLatestPodcastURL() {response in
//Uses an asynchronous call to Alamofire to get the podcast URL
self.downloadPodcastAsynch(audioUrl: response){response2 in
self.player = AVPlayer(url: response2)
print(self.player.currentItem)
}
#IBAction func PlayButton(_ sender: Any) {
player.play()
print(player.currentItem)
}
The log consistently shows my current item: >
But nothing plays. I have checked that the audio is working by trying to use the URL to stream this content. That works fine. I am getting the following:
BoringSSL errors "[BoringSSL] Function boringssl_session_errorlog: line 2871 [boringssl_session_read] SSL_ERROR_ZERO_RETURN(6): operation failed because the connection was cleanly shut down with a close_notify alert
but from what I've read, this is just a bug in the latest update and shouldn't be impacting the download. Any thoughts on this?

Save Firebase Storage Video and Play with AVPlayerViewController

Building an app that allows users to upload media to Firebase Storage. Upload seems to be working fine, however I can't get video downloads to play.
I saved a file to the app to test the AVPlayer and it works perfect.
func handleGesture() {
print("handle gesture")
if detailMediaType == "Video"{
performSegueWithIdentifier("toVideoView", sender: self)
print("video segue called")
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "toVideoView"){
let path = NSBundle.mainBundle().pathForResource("Apartment Ceiling Collapse- Queens, NY", ofType: "mp4")
var movieUrl = NSURL(fileURLWithPath: path!)
let filename = getDocumentsDirectory().stringByAppendingPathComponent("movie")
let videoData = NSData(contentsOfURL: movieUrl)
videoData!.writeToFile(filename, atomically: true)
self.avPlayer = AVPlayer(URL: movieUrl)
self.avPlayerViewController.player = self.avPlayer
self.presentViewController(self.avPlayerViewController, animated: false) { () -> Void in self.avPlayerViewController.player?.play()
}
}
}
Edit: I am now trying to download using downloadURLWithCompletion
FIRStorage.storage().referenceForURL(detailFullsizeUrl).downloadURLWithCompletion { (URL, error) -> Void in
if (error != nil)
{
print(error!)
}
else
{
self.firebaseUrl = URL!
print("firebaseUrl")
print(self.firebaseUrl)
self.avPlayer = AVPlayer(URL: self.firebaseUrl)
self.avPlayerViewController.player = self.avPlayer
}
}
I get an AVPlayerViewController with a black screen. When I access the "firebaseUrl" from the web, it downloads a text file that looks like gibberish.
Solution:
Changed up my approach. No longer saving to device. Instead I grabbed the "downloadUrl" metadata from the Firebase Storage object and pass it directly to the AVPlayerViewController.
let avPlayerViewController = AVPlayerViewController()
var avPlayer:AVPlayer? = nil
override func viewDidLoad() {
super.viewDidLoad()
FIRStorage.storage().referenceForURL(detailFullsizeUrl).metadataWithCompletion { (metadata, error) in
if error != nil{
print("error getting metadata")
} else {
let downloadUrl = metadata?.downloadURL()
print(downloadUrl)
if downloadUrl != nil{
self.avPlayer = AVPlayer(URL: downloadUrl!)
self.avPlayerViewController.player = self.avPlayer
print("downloadUrl obtained and set")
}
}
}
}
func handleGesture() {
print("handle gesture")
self.presentViewController(self.avPlayerViewController, animated: true) { () -> Void in
self.avPlayerViewController.player?.play()
}
}
Please check question. I updated it with the correct solution found on YouTube here: YouTube

WKWebView Screenshots

I am trying to capture the image that the webview is displaying to the user, so I can some color analysis of the web page. When I try to get the image from it's parent, I am basically getting a white box, even though the page has rendered:
func makeImageSnapshot()-> (NSImage)
{
let imgSize = self.view.bounds.size
let bir = self.viewbitmapImageRepForCachingDisplayInRect(self.webView!.view.bounds)
bir.size = imgSize
self.webView.cacheDisplayInRect(self.view.bounds, toBitmapImageRep:bir)
let image = NSImage(size:imgSize)
image.addRepresentation(bir)
self.image = image
return image
}
func saveSnapshot()
{
let imgRep = self.image!.representations[0]
let data = imgRep.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: nil)
data.writeToFile("/tmp/file.png", atomically: false)
}
It looks to me like I can't get access to the properties of the actual view (in this case the bounds) inside of the webView. When I try to access it, the compiler barfs:
/Users/josh/Canary/MacOsCanary/canary/canary/Modules/Overview/Overview.swift:55:37: '(NSView!, stringForToolTip: NSToolTipTag, point: NSPoint, userData: UnsafePointer<()>) -> String!' does not have a member named 'bounds'
My guess is that this is happening due to the extensions approach used by OS X and iOS. Any ideas, or should I just go back to using the legacy WebView?
I realise the question was for Mac OS X, but I found this page whilst searching for an iOS solution. My answer below doesn't work on Mac OS X as the drawViewHierarchyInRect() API call is currently iOS only, but I put it here for reference for other iOS searchers.
This Stackoverflow answer solved it for me on iOS 8 with a WKWebView. That answer's sample code is in Objective-C but the Swift equivalent to go in a UIView sub-class or extension would be along the lines of the code below. The code ignores the return value of drawViewHierarchyInRect(), but you may want to pay attention to it.
func imageSnapshot() -> UIImage
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0);
self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true);
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshotImage;
}
Swift 3
extension WKWebView {
func screenshot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0);
self.drawHierarchy(in: self.bounds, afterScreenUpdates: true);
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshotImage;
}
}
Note: This solution only works on iOS.
Found myself in the same boat today but found a solution (by using private APIs).
If you're not targeting the App Store and generally are not afraid of using private APIs, here's a way to capture screenshots of WKWebView's on OS X:
https://github.com/lemonmojo/WKWebView-Screenshot
You will need to have access to a target writeable place - the snapshotURL ie.., such as the desktop, so we provide a handler for that:
func registerSnaphotsURL(_ sender: NSMenuItem, handler: #escaping (URL) -> Void) {
var targetURL : URL
// 1st around authenticate and cache sandbox data if needed
if isSandboxed, desktopData == nil {
targetURL =
UserSettings.SnapshotsURL.value.count == 0
? getDesktopDirectory()
: URL.init(fileURLWithPath: UserSettings.SnapshotsURL.value, isDirectory: true)
let openPanel = NSOpenPanel()
openPanel.message = "Authorize access to "
openPanel.prompt = "Authorize"
openPanel.canChooseFiles = false
openPanel.canChooseDirectories = true
openPanel.canCreateDirectories = true
openPanel.directoryURL = targetURL
openPanel.begin() { (result) -> Void in
if (result == .OK) {
targetURL = openPanel.url!
// Since we do not have data, clear any bookmark
if self.storeBookmark(url: targetURL, options: self.rwOptions) {
self.desktopData = self.bookmarks[targetURL]
UserSettings.SnapshotsURL.value = targetURL.absoluteString
if !self.saveBookmarks() {
print("Yoink, unable to save snapshot bookmark")
}
self.desktopData = self.bookmarks[targetURL]
handler(targetURL)
}
}
else
{
return
}
}
}
else
{
targetURL =
UserSettings.SnapshotsURL.value.count == 0
? getDesktopDirectory()
: URL.init(fileURLWithPath: UserSettings.SnapshotsURL.value, isDirectory: true)
handler(targetURL)
}
}
we wanted to allow single (view controller) and all current views (app delegate) so two actions in their respective files, both making use of the register handler.
App Delegate
#objc #IBAction func snapshotAllPress(_ sender: NSMenuItem) {
registerSnaphotsURL(sender) { (snapshotURL) in
// If we have a return object just call them, else notify all
if let wvc : WebViewController = sender.representedObject as? WebViewController {
sender.representedObject = snapshotURL
wvc.snapshot(sender)
}
else
{
sender.representedObject = snapshotURL
let notif = Notification(name: Notification.Name(rawValue: "SnapshotAll"), object: sender)
NotificationCenter.default.post(notif)
}
}
}
View Controller
func viewDidLoad() {
NotificationCenter.default.addObserver(
self,
selector: #selector(WebViewController.snapshotAll(_:)),
name: NSNotification.Name(rawValue: "SnapshotAll"),
object: nil)
}
#objc func snapshotAll(_ note: Notification) {
snapshot(note.object as! NSMenuItem)
}
view singleton action
#objc #IBAction func snapshotPress(_ sender: NSMenuItem) {
guard let url = webView.url, url != webView.homeURL else { return }
guard let snapshotURL = sender.representedObject as? URL else {
// Dispatch to app delegate to handle a singleton
sender.representedObject = self
appDelegate.snapshotAllPress(sender)
return
}
sender.representedObject = snapshotURL
snapshot(sender)
}
the webView interaction to capture an image
#objc func snapshot(_ sender: NSMenuItem) {
guard let url = webView.url, url != webView.homeURL else { return }
guard var snapshotURL = sender.representedObject as? URL else { return }
// URL has only destination, so add name and extension
let filename = String(format: "%# Shapshot at %#",
(url.lastPathComponent as NSString).deletingPathExtension,
String.prettyStamp())
snapshotURL.appendPathComponent(filename)
snapshotURL = snapshotURL.appendingPathExtension("png")
webView.takeSnapshot(with: nil) { image, error in
if let image = image {
self.webImageView.image = image
DispatchQueue.main.async {
self.processSnapshotImage(image, to: snapshotURL)
}
}
else
{
self.userAlertMessage("Failed taking snapshot", info: error?.localizedDescription)
self.webImageView.image = nil
}
}
}
and the capture to the targeted area
func processSnapshotImage(_ image: NSImage, to snapshotURL: URL) {
guard let tiffData = image.tiffRepresentation else { NSSound(named: "Sosumi")?.play(); return }
let bitmapImageRep = NSBitmapImageRep(data: tiffData)
do
{
try bitmapImageRep?.representation(using: .png, properties: [:])?.write(to: snapshotURL)
// https://developer.apple.com/library/archive/qa/qa1913/_index.html
if let asset = NSDataAsset(name:"Grab") {
do {
// Use NSDataAsset's data property to access the audio file stored in Sound.
let player = try AVAudioPlayer(data:asset.data, fileTypeHint:"caf")
// Play the above sound file.
player.play()
} catch {
print("no sound for you")
}
}
if snapshotURL.hideFileExtensionInPath(), let name = snapshotURL.lastPathComponent.removingPercentEncoding {
print("snapshot => \(name)")
}
} catch let error {
appDelegate.userAlertMessage("Snapshot failed", info: error.localizedDescription)
}
}