MPMoviePlayerController in Swift - swift

I have this code but it doesn't show anything only a black frame.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var filepath: NSString = NSBundle.mainBundle().pathForResource("Akbar_ipad", ofType: "mp4")
var fileURL: NSURL = NSURL(string: filepath)
let moviePlayerController = MPMoviePlayerController(contentURL: fileURL)
moviePlayerController.shouldAutoplay = true
moviePlayerController.movieSourceType = MPMovieSourceType.File
moviePlayerController.view.frame = CGRect(x: 200, y: 200, width: 500, height: 300)
self.view.addSubview(moviePlayerController.view)
moviePlayerController.prepareToPlay()
moviePlayerController.play()
...
Have you got any idea how can i solve my problem? I am going crazy!
Thanks for your time.

I have a similar problem: How to load MPMoviePlayerController contentUrl asynchronous when loading view?
But here some ideas for you:
Maybe the url is constructed incorrectly/not local. Try using: let fileURL = NSBundle.mainBundle().URLForResource("Akbar_ipad", withExtension: "mp4")
You might need a global variable to hold a reference to the movie player instance (as described in the documentation.

For your problem, you maybe forgot add your resources as "Bundle Resources"
Follow below step to add:
In the Project Navigator select your project root
Select "Build Phases" tab
In "Bundle Resources" section to click "+" to add your resources
After that I think you can use both URLForResource and pathForResource

Related

Can't hide share button in USDZ + QLPreviewController

I got a project that involves a few USDZ files for the augmented reality features embedded in the app. While this works great, and we're really happy with how it performs, the built-in share button of the QLPreviewController is something that we'd like to remove. Subclassing the object doesn't have any effect, and trying to hide the rightBarButtonItem with the controller returned in delegate method still shows the button when a file is selected. The implementation of USDZ + QLPreviewController we're using is pretty basic. Is there a way around this issue?
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
let url = Bundle.main.url(forResource: models[selectedObject], withExtension: "usdz")! controller.navigationItem.rirButtonItems = nil.
// <- no effect return url as QLPreviewItem
}
#IBAction func userDidSelectARExperience(_ sender: Any) {
let previewController = QLPreviewController()
previewController.dataSource = self
previewController.delegate = self
present(previewController, animated: true)
}
This is the official answer from Apple.
Use ARQuickLookPreviewItem instead of QLPreviewItem. And set its canonicalWebPageURL to a URL (can be any URL).
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
guard let path = Bundle.main.path(forResource: "Experience", ofType: "usdz") else { fatalError("Couldn't find the supported input file.") }
let url = URL(fileURLWithPath: path)
if #available(iOS 13.0, *) {
let item = ARQuickLookPreviewItem(fileAt: url)
item.canonicalWebPageURL = URL(string: "http://www.google.com")
return item
} else { }
return url as QLPreviewItem
}
The version check is optional.
My approach is to add the QLPreviewController as an subview.
container is an UIView in storyboard.
let preview = QLPreviewController()
preview.dataSource = self
preview.view.frame = CGRect(origin: CGPoint(x: 0, y: -45), size: CGSize(width: container.frame.size.width, height: container.frame.size.height+45) )
container.addSubview(preview.view)
preview.didMove(toParent: self)
The y offset of the frame's origin and size may vary. This will ensure the AR QuickLook view to be the same size as the UIView, and hide the buttons (unfortunately, all of them) at the same time.
Instead of returning QLPreviewItem, use ARQuickLookPreviewItem which conforms to this protocol.
https://developer.apple.com/documentation/arkit/arquicklookpreviewitem
Then, assign a url that you would want to share (that will appear in share sheet) in canonicalWebPageURL property. By default, this property shares the file url (in this case, the USDZ file url). Doing so would not expose your file URL(s).
TLDR: I don't think you can.
I haven't seen any of the WWDC session even mention this and I can't seem to find any supporting developer documentation. I'm pretty sure the point of the ARKit QLPreviewController is so you don't have to do any actual coding on the AR side. I can see the appeal for this and for customisation in general, however, I'd suggest instead looking at some of the other ARKit projects that Apple has released and attempting to re-create those from the ground up as opposed to stripping this apart.
Please advise if this changes as I'd like to do something similar, especially within Safari.
I couldn't get to the share button at all to hide or disable it. Spent days to overcome this. I did rather unprofessional way of overcoming it. Subview QLPreviewController to a ViewController and subview a button or view on top of image view on top of share button and setting my company logo as image. It will be there all the time, even the top bar hides on full screen in AR mode. Not a clean solution. But works.

Load local web files & resources in WKWebView

Unlike with UIWebView and previous versions of WKWebView (iOS 10 & macOS 10.12), the default load operation for local files has moved from Bundle.main.path to Bundle.main.url. Similarly, loadFileURL has also become the default function to load local resources in WKWebView.
I know that .path and .url are entirely different and have both worked in the past – .path historically being the default-chosen method; however, it seems that the latest versions of Swift have broken most, if not all, .path solutions. The .path solutions seem to now flatten the directory hierarchy, putting all of the CSS, JS, and any other sub-directory contents, into one big directory. This causes loading errors when WKWebView attempts to load index.html, for example, with a linked, sub-folder stylesheet (ie. /css/style.css).
After seeing numerous questions and countless uncertain/broken answers to match, is there a quick and painless solution for implementing a WKWebView that can load local resources (including linked CSS/JS files), without any workarounds?
Updated for Swift 4, Xcode 9.3
This methods allows WKWebView to properly read your hierarchy of directories and sub-directories for linked CSS, JS and most other files. You do NOT need to change your HTML, CSS or JS code.
Solution (Quick)
Add the web folder to your project (File > Add Files to Project)
Copy items if needed
Create folder references *
Add to targets (that are applicable)
Add the following code to the viewDidLoad and personalize it to your needs:
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
Solution (In-Depth)
Step 1
Import the folder of local web files anywhere into your project. Make sure that you:
☑️ Copy items if needed
☑️ Create folder references (not "Create groups")
☑️ Add to targets
Step 2
Go to the View Controller with the WKWebView and add the following code to the viewDidLoad method:
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
index – the name of the file to load (without the .html extension)
website – the name of your web folder (index.html should be at the root of this directory)
Conclusion
The overall code should look something like this:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
webView.navigationDelegate = self
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "Website")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
}
}
If any of you have further questions about this method or the code, I'll do my best to answer!
This work For Me:
WKWebView *wkwebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
wkwebView.navigationDelegate = self;
wkwebView.UIDelegate = self;
[wkwebView.configuration.preferences setValue:#"TRUE" forKey:#"allowFileAccessFromFileURLs"];
NSURL *url = [NSURL fileURLWithPath:YOURFILEPATH];
[wkwebView loadFileURL:url allowingReadAccessToURL:url.URLByDeletingLastPathComponent];
[self.view addSubview:wkwebView];
I was facing the same issue my condition was, I am downloading some
HTML content from the server and save it to the Document directory and
show it inside the application. The same controller uses the LIVE URL
also I have to put the condition with url scheme. Tested on iOS 13 Xcode 11
if Url.scheme == "file" as String {
wkWebView.loadFileURL(Url, allowingReadAccessTo: Url)
}
else {
let request = URLRequest.init(url: Url, cachePolicy:.reloadIgnoringLocalCacheData, timeoutInterval:60)
wkWebView.load(request)
}
it worked perfect for me
1, Open project setting and got to Build Phases tab, open Link Binary with Libraries. Add Webkit framework.
2, Add the html to your project (Copy items if needed)
3, add this to your code:
#IBOutlet weak var webView: WKWebView!
4, viewDidLoad
viewDidLoad
It is possible to use resources from you project and even shared libraries inside html code with WKWebView.
For instance, I show how to load pic.png from bundle that contains ResourceContainingBundleClassNamed class.
NSSTring * htmlCode = #"<img src='pic.png'>";
NSBundle * bundle = [NSBundle bundleForClass:[ResourceContainingBundleClassNamed class]];
NSURL * base = bundle.resourceURL;
WKWebView * represent = [WKWebView new];
[represent loadHtmlString: htmlCode baseURL: base];
The magic is in resourceURL bundle property. If you just get path for desired file, then convert it to URL - no success.

Swift Mac OS - How to play another video/change the URL of the video with AVPlayer upon a button click?

I am new to swift and I am trying to make a Mac OS app that loops a video from the app's resources using AVPlayer as the background of the window once the app has been launched. When the user selects a menu item/clicks a button the background video will instantly change to a different video from the app's resources and start looping that video as the window's background.
I was able to play the first video once the app launches following this tutorial: (https://youtu.be/QgeQc587w70) and I also successfully made the video loop itself seamlessly following this post: (Looping AVPlayer seamlessly).
The problem I am now facing is changing the video to the other one once a menu item was selected/a button was clicked. The approach I was going for is to change the url and create a new AVPlayer using the new URL and affect it to the playerView.player following this post: (Swift How to update url of video in AVPlayer when clicking on a button?). However every time the menu item is selected the app crashes with the error "thread 1 exc_bad_instruction (code=exc_i386_invop subcode=0x0)". This is apparently caused by the value of playerView being nil. I don't really understand the reason for this as playerView is an AVPlayerView object that I created using the xib file and linked to the swift file by control-dragging and I couldn't seem to find another appropriate method of doing the thing I wanted to do. If you know the reason for this and the way of fixing it please provide me some help or if you know a better method of doing what I've mention above please tell me as well. Any help would be much appreciated!
My code is as follow, the line that crashes the app is at the bottom:
import Cocoa
import AppKit
import AVKit
import AVFoundation
struct videoVariables {
static var videoName = "Test_Video" //declaring the video name as a global variable
}
var videoIsPlaying = true
var theURL = Bundle.main.url(forResource:videoVariables.videoName, withExtension: "mp4") //creating the video url
var player = AVPlayer.init(url: theURL!)
class BackgroundWindow: NSWindowController {
#IBOutlet weak var playerView: AVPlayerView! // AVPlayerView Linked using control-drag from xib file
#IBOutlet var mainWindow: NSWindow!
#IBOutlet weak var TempBG: NSImageView!
override var windowNibName : String! {
return "BackgroundWindow"
}
//function used for resizing the temporary background image and the playerView to the window’s size
func resizeBG() {
var scrn: NSScreen = NSScreen.main()!
var rect: NSRect = scrn.frame
var height = rect.size.height
var width = rect.size.width
TempBG.setFrameSize(NSSize(width: Int(width), height: Int(height)))
TempBG.frame.origin = CGPoint(x: 0, y: 0)
playerView!.setFrameSize(NSSize(width: Int(width), height: Int(height)))
playerView!.frame.origin = CGPoint(x: 0, y: 0)
}
override func windowDidLoad() {
super.windowDidLoad()
self.window?.titleVisibility = NSWindowTitleVisibility.hidden //hide window’s title
self.window?.styleMask = NSBorderlessWindowMask //hide window’s border
self.window?.hasShadow = false //hide window’s shadow
self.window?.level = Int(CGWindowLevelForKey(CGWindowLevelKey.desktopWindow)) //set window’s layer as desktopWindow layer
self.window?.center()
self.window?.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
if let screen = NSScreen.main() {
self.window?.setFrame(screen.visibleFrame, display: true, animate: false) //resizing the window to cover the whole screen
}
resizeBG() //resizing the temporary background image and the playerView to the window’s size
startVideo() //start playing and loop the first video as the window’s background
}
//function used for starting the video again once it has been played fully
func playerItemDidReachEnd(notification: NSNotification) {
playerView.player?.seek(to: kCMTimeZero)
playerView.player?.play()
}
//function used for starting and looping the video
func startVideo() {
//set the seeking time to be 2ms ahead to prevent a black screen every time the video loops
let playAhead = CMTimeMake(2, 100);
//loops the video
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object:
playerView.player?.currentItem, queue: nil, using: { (_) in
DispatchQueue.main.async {
self.playerView.player?.seek(to: playAhead)
self.playerView.player?.play()
}
})
var playerLayer: AVPlayerLayer?
playerLayer = AVPlayerLayer(player: player)
playerView?.player = player
print(playerView?.player)
playerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
player.play()
}
//changing the url to the new url and create a new AVPlayer then affect it to the playerView.player once the menu item is being selected
#IBAction func renderBG(_ sender: NSMenuItem) {
videoVariables.videoName = "Test_Video_2"
var theNewURL = Bundle.main.url(forResource:videoVariables.videoName, withExtension: "mp4")
player = AVPlayer.init(url: theNewURL!)
//!!this line crashes the app with the error "thread 1 exc_bad_instruction (code=exc_i386_invop subcode=0x0)" every time the menu item is being selected!!
playerView.player = player
}
}
Additionally, the background video is not supposed to be interactive(E.g. User cannot pause/ fast-forward the video), so any issues that might be caused by user interactivity can be ignored. The purpose of the app is to play a video on the user's desktop creating the exact same effect of running the command:
"/System/Library/Frameworks/ScreenSaver.framework/Resources/
ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background" in terminal.
Any help would be much appreciated!
You don't need to create AVPlayer from url. There is AVPlayerItem class to manipulate player playback queue.
let firstAsset = AVURLAsset(url: firstVideoUrl)
let firstPlayerItem = AVPlayerItem(asset: firstAsset)
let player = AVPlayer(playerItem: firstPlayerItem)
let secondAsset = AVURLAsset(url: secondVideoUrl)
let secondPlayerItem = AVPlayerItem(asset: secondAsset)
player.replaceCurrentItem(with: secondPlayerItem)
Docs about AVPlayerItem

MPMoviePlayerController ignores MPMovieControlStyle.None in Swift

I'm trying to autoplay a video in my app. The video needs to play without the controls.
I've set up the video and the settings, including MPMovieControlStyle.None but the video controls appear for about 2 seconds before disappearing. I have no idea why.
I've used this code (exact code) for another project and it works well, but here for some reason it will not.
override func viewDidLoad() {
super.viewDidLoad()
generateVideo()
}
func generateVideo () {
let movieURL = NSBundle.mainBundle().pathForResource("video", ofType: "mp4")
let videoFilePath = NSURL(fileURLWithPath: movieURL!)
self.view.addSubview(MoviePlayerViewController.moviePlayer.view)
self.view.sendSubviewToBack(MoviePlayerViewController.moviePlayer.view)
MoviePlayerViewController.moviePlayer.contentURL = videoFilePath
MoviePlayerViewController.moviePlayer.shouldAutoplay = true
MoviePlayerViewController.moviePlayer.prepareToPlay()
MoviePlayerViewController.moviePlayer.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
MoviePlayerViewController.moviePlayer.fullscreen = true
MoviePlayerViewController.moviePlayer.controlStyle = MPMovieControlStyle.None
MoviePlayerViewController.moviePlayer.play()
MoviePlayerViewController.moviePlayer.repeatMode = MPMovieRepeatMode.One
MoviePlayerViewController.moviePlayer.scalingMode = MPMovieScalingMode.AspectFit
}
Any idea why this is happening?
After checking how the view is loaded I'm sure the problem is there.
I used a different layout with one Storyboard calling another storyboard and that was the source of the problem.

Play MP4 using MPMoviePlayerController() in Swift

I can't for the life of me figure out a way to play an MP4 that takes up the entire background in a UIViewController.
So far I have the following, which doesn't even play the video at all.
I can confirm that the bokeh.mp4 video exists because if I change the file to something else then it throws an error that it's missing.
override func viewDidAppear(animated: Bool) {
let filePath = NSBundle.mainBundle().pathForResource("bokeh", ofType: "mp4")
self.moviePlayerController.contentURL = NSURL(string: filePath)
self.moviePlayerController.prepareToPlay()
self.moviePlayerController.repeatMode = .One
self.moviePlayerController.controlStyle = .Embedded
self.view.addSubview(self.moviePlayerController.view)
}
I get an error in the console:
2014-06-22 21:22:42.347 MoviePlayer[26655:60b] _itemFailedToPlayToEnd: {
kind = 1;
new = 2;
old = 0;
}
I've also tried adding a UIView that takes up the entire screen and adding the player to that view, but it's the same problem. It doesn't start playing.
I'm trying to achieve the same effect that Vine has when you first load up the application where it has the video playing in the background.
So this was blindly annoying:
All I did was change:
self.moviePlayerController.contentURL = NSURL(string: filePath)
TO:
self.moviePlayerController.contentURL = NSURL.fileURLWithPath(filePath)