Loading correct image to detail view - swift

I have a TableView app that plays music. The tracks are named: 0.mp3, 1.mp3 etc. They play in a detail view where I also want an image of the cover. I named the cover images: 0.png, 1.png etc.
I tried to load the correct image with the code:
self.bookImage.image = UIImage(named: ("/\(trackID!).png"))
but it doesn't work.
Here's some more of my code:
import UIKit
import AVFoundation
class AudioPlayerVC: UIViewController {
var trackID: Int!
var audioPlayer:AVAudioPlayer!
#IBOutlet var bookImage: UIImageView!
#IBAction func play(_ sender: AnyObject) {
if !audioPlayer.isPlaying{
audioPlayer.play()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.bookImage.image = UIImage(named: ("/\(trackID!).png"))
trackLbl.text = "Track \(trackID!)"
let path: String! = Bundle.main.resourcePath?.appending("/\(trackID!).mp3")
let mp3URL = NSURL(fileURLWithPath: path)
do
{
audioPlayer = try AVAudioPlayer(contentsOf: mp3URL as URL)
audioPlayer.play()
}
}
}

You need
self.bookImage.image = UIImage(named:"\(trackID).png")
Or
self.bookImage.image = UIImage(named:"\(trackID)")

First, you don't need / character after opening quotation mark.
self.bookImage.image = UIImage(named:"\(trackID).png")
Should work just fine.

1) Please add your images to Assets.xcassets
2) Name images like 0,1,2,3 in Assets.xcassets
3) Write a code:
let trackId = String(trackId)
self.bookImage.image = UIImage(named: trackId)

Related

loading disk image into NSImage

I am trying to create a CALayer to apply to my view. But, before I even get to that I cannot get an image to load from disk.
What am I doing wrong?
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let image = NSImage(contentsOfFile: "/Users/Shared/background.png")!
let imageView = NSImageView(image: image)
self.view.addSubview(imageView)
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
I have used contentsOfFile as well as byReferencingFile and it doesn't change the behavior. The file exists at that path.
UPDATE: This doesn't work either.
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let fileURL = URL(fileURLWithPath: "/Users/carroll/Desktop/background.jpg")
let image = NSImage(contentsOf: fileURL)
print(image)
let imageView = NSImageView(image: image)
self.view.addSubview(imageView)
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
So this is what is printing to the console:
Optional(<NSImage 0x600003310aa0 Size={576, 828} Reps=(
"NSBitmapImageRep 0x60000260e4c0 Size={576, 828} ColorSpace=(not yet > loaded) BPS=8 BPP=(not yet loaded) Pixels=2400x3450 Alpha=NO Planar=NO Format=(not yet loaded) CurrentBacking=nil (faulting) CGImageSource=0x600000246a60"
)>)
2020-08-10 11:46:57.767358-0500 My App[83208:8822749] Metal API Validation Enabled
2020-08-10 11:46:57.832881-0500 My App[83208:8822749] VPA info: plugin is INTEL, AVD_id = 1080010, AVD_api.Create:0x131373c15
From what I see above from the print statement it looks like it is getting the image, but it shows not loaded yet and then for the CurrentBacking it shows nil (faulting).
UPDATE 2 I was able to get the background to display, but I do not understand why this works and why I have to have set self.view.wantsLayer = true when the Apple Documentation says this property is already set to true as default.
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.wantsLayer = true
let image = NSImage(contentsOf: URL(fileURLWithPath: "/Users/Shared/background.jpg"))
self.view.layer?.contents = image
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}

Populating NSImage in Interface Builder from Folder Reference

I placed a folder with images into my project as Folder Reference. Now I can see it in my Package in Contents/Resources/Images/foo.jpg
I try to populate an NSImage like this:
#IBOutlet var imageView: NSImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = NSImage (named: "Images/foo.jpg")
}
But no image is shown when the app is loaded. I am using interface builder not XIB. Does it make a difference? If I add the images as Group I can use named:"foo.jpg" without any issue.
I understand now the inner workings. This is my solution:
#IBOutlet var imageView: NSImageView!
override func viewDidLoad() {
super.viewDidLoad()
let image = Bundle.main.path(forResource: "foo", ofType: "jpg", inDirectory: "Images")
imageView.image = NSImage (contentsOfFile: image)
}
The reference files are not named in my bundle so they are never found. With the full path it works well.

How to play a video in a macOS application with swift?

I'm trying to get a video I have in my project to play in my macOS application using swift. Here is my code:
import Cocoa
import AVKit
import AVFoundation
class ViewController: NSViewController {
var player : AVPlayer!
var avPlayerLayer : AVPlayerLayer!
#IBOutlet weak var videoPlayer: AVPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
guard let path = Bundle.main.path(forResource: "Background", ofType:"mp4") else {
debugPrint("Not found")
return
}
let playerURL = AVPlayer(url: URL(fileURLWithPath: path))
let playerView = AVPlayerView()
playerView.player = playerURL
playerView.player?.play()
}
}
I also have an AVPlayerView in my storyboard that I have connected to my viewcontroller.
It builds and runs fine but when I run it nothing shows up. I just get a black screen.
Any help is appreciated. Thanks!
The problem is this line:
let playerView = AVPlayerView()
Instead of configuring the player view that is in your interface, you make a whole new separate player view — and then you throw it away.

Play sound with AKAudioPlayer - iOS

How to declare AKAudioPlayer?
I'm using AudioKit Lib and I just need help to play .wav file with change file button.
import UIKit
import AudioKit
class ViewController: UIViewController {
let file = NSBundle.mainBundle().pathForResource("song", ofType: "wav")
let song = AKAudioPlayer(file!) // <--- ERROR = instance member 'file' cannot be used on type
override func viewDidLoad() {
super.viewDidLoad()
AudioKit.output = song
AudioKit.start()
song.play()
}
#IBAction func btn(sender: AnyObject) {
song.replaceFile("NewFile")
song.play()
}
}
This is a very fast solution to your problem. It can be done better but at least you can get the idea.
First try to make a new class with a function to play your file and then another function to reload your new replacement file like this.
class PlayMyMusic {
var songFile = NSBundle.mainBundle()
var player: AKAudioPlayer!
func play(file: String, type: String) -> AKAudioPlayer {
let song = songFile.pathForResource(file, ofType: type)
player = AKAudioPlayer(song!)
return player
}
func rePlay(file: String, type: String, curPlay: AKAudioPlayer) {
let song = songFile.pathForResource(file, ofType: type)
curPlay.stop()
curPlay.replaceFile(song!)
curPlay.play()
}
}
Initiate the class inside your view
class testViewController: UIViewController {
let doPlay = PlayMyMusic().play("A", type: "wav")
.........
.........
Play your music inside your view
override func viewDidLoad() {
super.viewDidLoad()
AudioKit.output = self.doPlay
AudioKit.start()
doPlay.looping = true
doPlay.play()
}
Then when you want to reload a new file use the rePlay function
#IBAction func btn(sender: AnyObject) {
PlayMyMusic().rePlay("C", type: "wav", curPlay: self.doPlay)
}
take look on AudioKit playground
update
AKAudioPlayer is deprecated, use AudioPlayer insted and check AudioKit v5 Migration Guide

Displaying images with action in swift?

I'm a kind new to Xcode/swift, I am trying to build a game where 5 pics need to selected randomly, my code looks something like that :
var options = ["1.png","2.png","3.png","4.png","4.png"]
#IBAction func option1(sender: AnyObject) {
var randomNumber = Int(arc4random_uniform(5))
**iphoneChoise.image(options[randomNumber])** /*This line is not correct*/
}
Please help!
Make an #IBOutlet for your image view.
Then, assuming your images are saved in Images.xcassets:
#IBAction func option1(sender:AnyObject){
var randomNumber = Int(arc4random_uniform(5))
yourImageViewIBOutlet.image = UIImage(named: options[randomNumber])
}
You should try something like :
yourImageView.image = UIImage(named: "imageName")
In you case, it should like like this :
var options = ["1.png","2.png","3.png","4.png","4.png"]
#IBAction func option1(sender: AnyObject) {
var randomNumber = Int(arc4random_uniform(5))
iphoneChoise.image = UIImage(named: options[randomNumber])
}
Make sure the images are within the project (inside the Images.xcassets for example).
If it didn't helped, please provide more information : "what" is _iphoneChoise_ and what error are you facing.
You can simplify the code for your random image by using the following code:
var randomImageGeneratorNumber = acr4random_uniform(5) + 1
YourImageView.image = UIImage(named: "\(randomImageGeneratorNumber).png")
This is called "String Interpolation"
Hope this will help you by making your code a bit shorter.