AVPlayer: Unable to play() a mpg video - swift

The following simple class doesn't play a video URL. What I get is a black empty screen. Why?
import Foundation
import AVKit
import AVFoundation
class EditShowVideoViewController:AVPlayerViewController {
override func viewDidLoad() {
var error: NSError?
if let urlString = gBlissMedium!.mediumURL {
let url = NSURL(string: urlString)
player = AVPlayer(URL:url)
}
}
override func viewDidAppear(animated: Bool) {
player.play()
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
(lldb) po urlString
"http://files.parsetfss.com/6b8388b7-14c6-431a-a795-2b33f9d47081/tfss-56cf2c67-111c-4724-8e63-3755fe1b85f7-hst_1.mpg"

if let urlString = gBlissMedium!.mediumURL {
let url = NSURL(string: urlString)
player = AVPlayer(URL:url)
}
here player is being defined locally in viewDidLoad, it should be an instance variable of the class

Related

Swift: Parse does not load a video from URL

I am trying to stream a video from backend to my device.I have a video url from backend but screen displays nothing. However, youtube url it works. Can anyone guide me why this video is not playing and how can it be played? I am using pod 'YouTubePlayer' to play the video.
let cell: VideoTableViewCell = tableView.dequeueReusableCell(withIdentifier: "VideoTableViewCell") as! VideoTableViewCell
var query = PFQuery(className:"Videos")
query.getObjectInBackground(withId: "83kli72i62") { (parseObject, error) -> Void in
let videoFile = parseObject!["Question"] as! PFFileObject
self.videoUrl = videoFile.url
let url = NSURL(string: self.videoUrl! )
cell.playerView.loadVideoURL(url as! URL)
}
i have an app that is pulling videos from firebase and playing them with the avplayer, check out my code below and see how it works
class IsoLateralLowRowViewController: UIViewController {
#IBOutlet weak var playv: UIButton!
let avPlayerViewController = AVPlayerViewController()
var avPlayer:AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
self.view.addBackground()
let movieUrl:NSURL? = NSURL(string: "https://firebasestorage.googleapis.com/v0/b/messenger-test-d225b.appspot.com/o/test%2FTestVideo.mov?alt=media&token=bd4ccba3-b446-43bc-809e-b1152aa3c2ff")
if let url = movieUrl {
self.avPlayer = AVPlayer(url: url as URL)
self.avPlayerViewController.player = self.avPlayer
}
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: avPlayerViewController.player?.currentItem)
self.present(self.avPlayerViewController, animated: true) { () -> Void in
self.avPlayerViewController.player?.play() // Do any additional setup after loading the view.
}
}
#objc func playerDidFinishPlaying(note: NSNotification) {
self.avPlayerViewController.dismiss(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

Can't solve this? How would you fix this? "Variable binding in a condition requires an initializer" and "Expected '{' after 'if' condition"

The title summarized my problem. I'm new to coding and I don't understand how to solve the problem.
I've tried pretty much all I know.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
#IBOutlet weak var PowerLVLlabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func randomNumber(_ sender: Any) {
let randomNumber = Int.random(in: 1000...10000)
PowerLVLlabel.text = String(randomNumber)
if case { randomNumber; >=9000 == (true);
func playVideo() {
guard let path = Bundle.main.path(forResource: "over 9000", ofType:"mp4") else {
debugPrint("over 9000.mp4 not found")
return
}
{let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true) }
{player.play()
}
try this:
func playVideo(){
guard let path = Bundle.main.path(forResource: "over 9000", ofType:"mp4") else {
debugPrint("over 9000.mp4 not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true)
player.play()
}
#IBAction func randomNumber(_ sender: Any) {
let randomNumber = Int.random(in: 1000...10000)
PowerLVLlabel.text = String(randomNumber)
if randomNumber >= 9000{
playVideo()
}
}
You need to get playVideo function out of randomNumber and remove some un needed ; and {}
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var powerLVLlabel: UILabel!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func playVideo() {
guard let path = Bundle.main.path(forResource: "over 9000", ofType:"mp4") else {
debugPrint("over 9000.mp4 not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true)
player.play()
}
#IBAction func randomNumber(_ sender: Any) {
let randomNumber = Int.random(in: 1000...10000)
powerLVLlabel.text = String(randomNumber)
if randomNumber >= 9000 {
playVideo()
}
}
}

How to pass data from view controller to data model in swift

I am building a simple app that talks to a web service.
I have used the delegates method to communicate data (from my model to view controller).
But I am not sure how to read the data from view controller (text_field.text) in my model. I need to do that so that I can pass the right parameter to my webservice
my view controller is:
import UIKit
class ViewController: UIViewController,HomeModelDelegate {
var homeModel = HomeModel()
#IBOutlet weak var loginid: UITextField!
#IBOutlet weak var pwd: UITextField!
#IBAction func submit(_ sender: UIButton) {
homeModel.chkpwd()
//Here viewcontroller is assigning itself to the homemodel's delegate property
homeModel.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
loginid.layer.cornerRadius=10
pwd.layer.cornerRadius = 10
}
func itemsDownloaded(locations: [Location]) {
loginid.text = locations[0].pwd
}
}
My model code is:
import UIKit
protocol HomeModelDelegate{
func itemsDownloaded(locations:[Location])
}
class HomeModel: NSObject
{
var delegate:HomeModelDelegate?
func chkpwd()
{
//Hit the webservice url
let x = ViewController()
let z = x.loginid
let serviceUrl = "http://www.xyz.in/webservice.php?loginid=(loginid.text)"
//download the json data
let url = URL(string: serviceUrl)
if let url = url {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url, completionHandler:
{ (data, response, error) in
if error == nil {
//succeeded
self.parseJson(data!)
}
else {
//failed
}
})
task.resume()
}
}
func parseJson(_ data:Data){
var locArray = [Location]()
do{
let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
for jsonResult in jsonArray{
let jsonDict = jsonResult as! [String:String]
let loc = Location(pwd: jsonDict["loginid"]!, loginid: jsonDict["pwd"]!)
locArray.append(loc)
//pass the location back to the delegate
delegate?.itemsDownloaded(locations: locArray)
}
}
catch{
print("An error occured")
}
}
}
Please try this :
import UIKit
class ViewController: UIViewController,HomeModelDelegate {
var homeModel = HomeModel()
#IBOutlet weak var loginid: UITextField!
#IBOutlet weak var pwd: UITextField!
#IBAction func submit(_ sender: UIButton) {
homeModel.z = loginid.text! // ASSIGNING z here
homeModel.chkpwd()
//Here viewcontroller is assigning itself to the homemodel's delegate property
homeModel.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
loginid.layer.cornerRadius=10
pwd.layer.cornerRadius = 10
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func itemsDownloaded(locations: [Location]) {
loginid.text = locations[0].pwd
}
}
Model :
import UIKit
protocol HomeModelDelegate{
func itemsDownloaded(locations:[Location])
}
class HomeModel: NSObject
{
var z:String = "" // INITIALIZING z
var delegate:HomeModelDelegate?
func chkpwd()
{
print(z) // CALLING z
//Hit the webservice url
let serviceUrl = "http://www.xyz.in/webservice.php?loginid=(loginid.text)"
//download the json data
let url = URL(string: serviceUrl)
if let url = url {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url, completionHandler:
{ (data, response, error) in
if error == nil {
//succeeded
self.parseJson(data!)
} else {
//failed
}
})
task.resume()
}
}
func parseJson(_ data:Data){
var locArray = [Location]()
do{
let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
for jsonResult in jsonArray{
let jsonDict = jsonResult as! [String:String]
let loc = Location(pwd: jsonDict["loginid"]!, loginid: jsonDict["pwd"]!)
locArray.append(loc)
//pass the location back to the delegate
delegate?.itemsDownloaded(locations: locArray)
}
} catch {
print("An error occured")
}
}
}

Record And Play Voice in Separate Class (Swift3)

I used many codes that was for record an play the voice, but most of them are not in swift3 and they don't work in my app.
This code works, but I want to create a separate class from the viewcontroller that do recording an playing voices. Also the mentioned github code is complex an I'm searching for a simplified code.
Update:
After recording, when I check existence of the recorded file, the file doesn't exist, and it raises EXC_BAD_ACCESS error on appDelegate.
What's wrong?
Any suggestions would be appreciated.
Try to record audio by wirting line
let isRec = AudioManager.shared.record(fileName: "rec")
if isRec returned true then recording is happening else not.
To finish recording use : let recordedURL = AudioManager.shared.finishRecording()
To play recorded file send above url to setupUpPlayer() function in manager class
Not to forget to use extension code snippets give below the code snippet which are delegate functions of AVAudioRecorder and AVAudioPlayer
import Foundation
import AVFoundation
class AudioManager: NSObject {
static let shared = AudioManager()
var recordingSession: AVAudioSession?
var recorder: AVAudioRecorder?
var meterTimer: Timer?
var recorderApc0: Float = 0
var recorderPeak0: Float = 0
//PLayer
var player: AVAudioPlayer?
var savedFileURL: URL?
func setup() {
recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession?.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
try recordingSession?.setActive(true)
recordingSession?.requestRecordPermission({ (allowed) in
if allowed {
print("Mic Authorised")
} else {
print("Mic not Authorised")
}
})
} catch {
print("Failed to set Category", error.localizedDescription)
}
}
func record(fileName: String) -> Bool {
setup()
let url = getUserPath().appendingPathComponent(fileName + ".m4a")
let audioURL = URL.init(fileURLWithPath: url.path)
let recordSettings: [String: Any] = [AVFormatIDKey: kAudioFormatMPEG4AAC,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 44100.0]
do {
recorder = try AVAudioRecorder.init(url: audioURL, settings: recordSettings)
recorder?.delegate = self
recorder?.isMeteringEnabled = true
recorder?.prepareToRecord()
recorder?.record()
self.meterTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (timer: Timer) in
//Update Recording Meter Values so we can track voice loudness
if let recorder = self.recorder {
recorder.updateMeters()
self.recorderApc0 = recorder.averagePower(forChannel: 0)
self.recorderPeak0 = recorder.peakPower(forChannel: 0)
}
})
savedFileURL = url
print("Recording")
return true
} catch {
print("Error Handling", error.localizedDescription)
return false
}
}
func getUserPath() -> URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
}
func finishRecording() -> String {
recorder?.stop()
self.meterTimer?.invalidate()
var fileURL: String?
if let url: URL = recorder?.url {
fileURL = String(describing: url)
}
return /fileURL
}
//Player
func setupPlayer(_ url: URL) {
do {
try player = AVAudioPlayer.init(contentsOf: url)
} catch {
print("Error1", error.localizedDescription)
}
player?.prepareToPlay()
player?.play()
player?.volume = 1.0
player?.delegate = self
}
}
//MARK:- Audio Recorder Delegate
extension AudioManager: AVAudioRecorderDelegate {
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
print("AudioManager Finish Recording")
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
print("Encoding Error", /error?.localizedDescription)
}
}
//MARK:- Audio Player Delegates
extension AudioManager: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
successfully flag: Bool) {
player.stop()
print("Finish Playing")
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer,
error: Error?) {
print(/error?.localizedDescription)
}
}

how to fix Memory leak array on AlamofireObjectMapper

How can I solve the leak that happened in the sample code below, as seen in this image:
import UIKit
import Alamofire
import AlamofireObjectMapper
class ViewController: UIViewController {
#IBAction func action(_ sender: Any) {
load { (posts: [Post]) in
posts.map({ (post: Post) -> Void in
print(post.title)
})
}
}
func load( posts: (([Post]) -> Void)!) {
let urlString = "https://jsonplaceholder.typicode.com/posts"
let url = try! urlString.asURL()
Alamofire.request(url).validate().responseArray { (response: DataResponse<[Post]>) in
guard let postArray = response.result.value else {return}
posts(postArray)
}
}
}