I have a little code which allows me to play a local file when I hit a UIButton. But what I want is to play multiple files on 3 different UIButtons because I have 3 video files which I want to attach to my app.
This is the current code:
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
var playerController = AVPlayerViewController()
var player:AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let videoString:String? = Bundle.main.path(forResource: "Video", ofType: ".mp4")
if let url = videoString {
let videoURL = NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
self.playerController.player = self.player
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func PlayVideo(_ sender: AnyObject) {
self.present(self.playerController, animated: true, completion: {
self.playerController.player?.play()
})
}
}
You can create url for different video file in your button click funtions
#IBAction func Button1Click(_ sender: AnyObject) {
let videoString:String? = Bundle.main.path(forResource: "Video1", ofType: ".mp4")
if let url = videoString {
let videoURL = NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
self.playerController.player = self.player
}
self.present(self.playerController, animated: true, completion: {
self.playerController.player?.play()
})
}
#IBAction func Button2Click(_ sender: AnyObject) {
let videoString:String? = Bundle.main.path(forResource: "Video2", ofType: ".mp4")
if let url = videoString {
let videoURL = NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
self.playerController.player = self.player
}
self.present(self.playerController, animated: true, completion: {
self.playerController.player?.play()
})
}
#IBAction func Button3Click(_ sender: AnyObject) {
let videoString:String? = Bundle.main.path(forResource: "Video3", ofType: ".mp4")
if let url = videoString {
let videoURL = NSURL(fileURLWithPath: url)
self.player = AVPlayer(url: videoURL as URL)
self.playerController.player = self.player
}
self.present(self.playerController, animated: true, completion: {
self.playerController.player?.play()
})
}
Related
The below code used to work in Xcode8. But now it is not working in Xcode 9.1 with target iOS11.
I did the following:
class ViewController: UIViewController {
var documentInteractionController: UIDocumentInteractionController = UIDocumentInteractionController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func ShareImages(_ sender: AnyObject)
{
let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
if let whatsappURL = URL(string: urlString) {
if UIApplication.shared.canOpenURL(whatsappURL as URL) {
if let image = UIImage(named: "whatsappIcon") {
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
do {
try imageData.write(to: tempFile, options: .atomic)
self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
self.documentInteractionController.uti = "net.whatsapp.image"
self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
} catch {
print(error)
}
}
}
} else {
// Cannot open whatsapp
}
}
}
}
// Added this in info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
Theres no error in my code but ImagevIew image doesn't show
let imageCache = NSCache()
extension UIImageView {
func loadImageUsingCacheWithUrlString(urlString: String) {
//self.image = nil
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cachedImage
return
}
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async(execute: {
if let currImage = UIImage(data: data!) {
imageCache.setObject(currImage, forKey: urlString as AnyObject)
self.image = currImage
}
})
}).resume()
}
}
I'm looking for a little help on how to populate text into a twitter post, using the button below I can get a label to show "00:35' Goal for"
When the button is clicked I would like to open twitter which I can work out, and populate it ready for tweeting.
#IBAction func goalClicked(_ sender: UIButton) {
tempTimelineLbl.text = "\(stopWatchString)' \("Goal for")"
}
I will use the code below to open twitter
let twUrl: URL = URL(string: "twitter://user?screen_name=\(club.twitter)")!
let twUrlWeb: URL = URL(string: "https://twitter.com/\(club.twitter)")!
if (UIApplication.shared.canOpenURL(twUrl)) {
UIApplication.shared.open(twUrl, options: [:], completionHandler: {
(Sucess) in
})
} else {
UIApplication.shared.open(twUrlWeb, options: [:], completionHandler: {
(Sucess) in
})
}
Followed this
https://developer.apple.com/reference/social/slcomposeviewcontroller
#IBAction func goalClicked(_ sender: UIButton) {
let stopWatchString = stopWatch.elapsedTimeSinceStart()
stopwatchLabel.text = stopWatchString
let vc = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
vc?.setInitialText("Some Test String")
vc?.add(#imageLiteral(resourceName: "goal"))
present(vc!, animated: true, completion: nil)
}
I have a ViewController containing a WKWebView, the view is positioned correctly the first time it loads, but after moving to another view (I'm opening another view by intercepting links from the WebView) and pressing the navigation item (back button) it briefly appears in the right place, then reloads with the top of the webview behind the navigation bar so the top of the page is cut off.
class HomeVC: BaseViewController, WKNavigationDelegate, WKUIDelegate {
var webView: WKWebView?
override func viewDidAppear(_ animated: Bool) {
self.edgesForExtendedLayout = UIRectEdge.top;
super.viewDidLoad()
addSlideMenuButton()
let screenSize: CGRect = UIScreen.main.bounds
let frameRect: CGRect = CGRect(x: 0, y: 100, width: screenSize.width, height: screenSize.height)
let url: NSURL = Bundle.main.url(forResource: "services", withExtension: "html")! as NSURL
let requestObj: NSURLRequest = NSURLRequest(url: url as URL);
self.webView = WKWebView(frame: frameRect)
self.webView?.load(requestObj as URLRequest)
self.webView?.navigationDelegate = self
self.webView?.uiDelegate = self
self.view = self.webView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationItem.title = ""
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "SELECT A SERVICE"
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
let link: String = (webView.url?.absoluteString)!
print(link)
if(link == "file:///haircut") {
print(link)
self.openViewControllerBasedOnIdentifier("WebVC")
}
}
I've searched around and can't find any similar issues, nor can I see anything obvious in the code.
You have are calling super.viewDidLoad from func viewDidAppear(), what can cause unexpected behaviour. Therefore your UIViewController subclass will never notify its superclass, that the view has been loaded.
override func viewDidAppear(_ animated: Bool) {
// Do not do this before calling super!
self.edgesForExtendedLayout = UIRectEdge.top;
// You are calling the wrong the function for super
// It should be super.viewDidAppear(animated)
super.viewDidLoad()
addSlideMenuButton()
let screenSize: CGRect = UIScreen.main.bounds
let frameRect: CGRect = CGRect(x: 0, y: 100, width: screenSize.width, height: screenSize.height)
let url: NSURL = Bundle.main.url(forResource: "services", withExtension: "html")! as NSURL
let requestObj: NSURLRequest = NSURLRequest(url: url as URL);
self.webView = WKWebView(frame: frameRect)
self.webView?.load(requestObj as URLRequest)
self.webView?.navigationDelegate = self
self.webView?.uiDelegate = self
self.view = self.webView
}
please help me log is shown playing but no sound is heard
let url = URL(string: "https://s3.amazonaws.com/kargopolov/BlueCafe.mp3")
let playerItem = AVPlayerItem(url: url! as URL)
let player=AVPlayer(playerItem: playerItem)
player.volume=1.0
player.play()
if (player.rate != 0 && player.error == nil) {
print("playing")
}
else
{
print("error",player.error)
}
You need a to assign the player to a variable that doesn't go out of scope, eg
class ViewControllerA: UIViewController {
var avPlayer: AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view
}
override func viewDidAppear(_ animated: Bool) {
let videoURL = NSURL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
avPlayer = AVPlayer(url: videoURL! as URL)
let playerLayer = AVPlayerLayer(player: avPlayer)
playerLayer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width * 3.0 / 4.0)
self.view.layer.addSublayer(playerLayer)
avPlayer.play()
}
}
Declare Player Variable before
var playerT : AVPlayer!
Now you able to play song from url
let url = URL(string: "https://s3.amazonaws.com/kargopolov/BlueCafe.mp3")
playerT = AVPlayer(url: url!)
playerT.volume = 1.0
playerT.play()
if playerT.rate != 0 && playerT.error == nil{
print("Playing")
}else{
print("Error Playing")
}