NSOpenPanel as sheet - swift

Ive looked around at other answers, but nothing seems to be helping my case.
I have a viewController class which contains an IBAction for a button. This button should open a NSOpenPanel as a sheet from that viewController:
class ViewController: NSViewController {
#IBAction func folderSelection(sender: AnyObject) {
var myFiledialog: NSOpenPanel = NSOpenPanel()
myFiledialog.prompt = "Select path"
myFiledialog.worksWhenModal = true
myFiledialog.allowsMultipleSelection = false
myFiledialog.canChooseDirectories = true
myFiledialog.canChooseFiles = false
myFiledialog.resolvesAliases = true
//myFiledialog.runModal()
myFiledialog.beginSheetModalForWindow(self.view.window!, completionHandler: nil)
var chosenpath = myFiledialog.URL
if (chosenpath!= nil)
{
var TheFile = chosenpath!.absoluteString!
println(TheFile)
//do something with TheFile
}
else
{
println("nothing chosen")
}
}
}
The problem comes from myFileDialog.beginSheetModalForWindow(..) , it works with the line above, but that is not a sheet effect

You need to call beginSheetModalForWindow from your panel on your window, and use a completion block:
let myFiledialog = NSOpenPanel()
myFiledialog.prompt = "Select path"
myFiledialog.worksWhenModal = true
myFiledialog.allowsMultipleSelection = false
myFiledialog.canChooseDirectories = true
myFiledialog.canChooseFiles = false
myFiledialog.resolvesAliases = true
myFiledialog.beginSheetModalForWindow(window, completionHandler: { num in
if num == NSModalResponseOK {
let path = myFiledialog.URL
print(path)
} else {
print("nothing chosen")
}
})

Swift 5
let dialog = NSOpenPanel()
dialog.beginSheetModal(for: self.view.window!){ result in
if result == .OK, let url = dialog.url {
print("Got", url)
}
}

Related

Status bar app does not show file picker correctly

I'm working on status bar app.
I want to show file picker to select my image.
Here is my code:
Button("Select image") {
let openPanel = NSOpenPanel()
openPanel.prompt = "Select File"
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = true
openPanel.allowedFileTypes = ["png","jpg","jpeg"]
openPanel.begin { (result) -> Void in
if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
let selectedPath = openPanel.url!.path
if let nsData = NSData(contentsOfFile: selectedPath) {
imageData = Data(referencing: nsData)
}
}
}
}
It's shown, but behind my app (which is not on status bar)
So how to just show file picker and hide that weird view.

YPImagePicker and sending image and video to another controller

I am trying to send a photo and video from one controller to another with the YPImagePicker pod. I am having an issue understanding how to use this file.
var selectedItems = [YPMediaItem]()
let selectedImageV = UIImageView()
#objc func showPicker() {
var config = YPImagePickerConfiguration()
config.library.mediaType = .photoAndVideo
config.library.onlySquare = true
config.showsFilters = false
config.shouldSaveNewPicturesToAlbum = true
config.albumName = "RecipeSharing"
config.video.compression = AVAssetExportPresetMediumQuality
config.startOnScreen = .library
config.screens = [.library, .photo, .video]
config.video.recordingTimeLimit = 5.0
config.video.libraryTimeLimit = 500.0
config.video.trimmerMaxDuration = 60.0
config.video.trimmerMinDuration = 3.0
config.video.fileType = .mov
config.showsCrop = .rectangle(ratio: (16/9))
config.targetImageSize = YPImageSize.original
config.wordings.libraryTitle = "Gallery"
config.hidesStatusBar = false
config.hidesBottomBar = false
config.library.maxNumberOfItems = 5
let picker = YPImagePicker(configuration: config)
picker.didFinishPicking { [unowned picker] items, _ in
if let photo = items.singlePhoto {
let finalShareVC = NewInstructionsController()
picker.navigationController?.pushViewController(finalShareVC, animated: true)
}
}
picker.didFinishPicking { [unowned picker] items, _ in
if let video = items.singleVideo {
let finalShareVC = NewInstructionsController()
picker.navigationController?.pushViewController(finalShareVC, animated: true)
}
}
present(picker, animated: true, completion: nil)
}
My Second Controller has the the code as the following.
var selectedImage: UIImage? {
didSet {
guard let image = selectedImage else { return }
instructionsImage.image = image
}
}
This is used to receive the file the photo I believe. Does anyone know what I have to use to send a photo and video to another controller so that it can be used. I have tried reading a lot on this pod. I get to the save option in this pod and then it does not do anything. I was wondering if anyone had an idea or could help me. Maybe I dont need to push the view but I am unsure. Thank you.

How to setup a Bar Button with a value of firebase?

I want to check if the user is a admin or not. If the user is a admin, I want to show a bar button. If not, the bar button should be hidden.
I call the following code in viewDidLoad:
#IBOutlet weak var beitraegeMelden: UIBarButtonItem!
var admin = false
func setupBarButton() {
observeAdmin()
if admin == true {
self.beitraegeMelden.isEnabled = true
self.navigationItem.rightBarButtonItem = self.beitraegeMelden
} else {
self.beitraegeMelden.isEnabled = false
self.navigationItem.rightBarButtonItem = nil
}
}
func observeAdmin() {
guard let currentUserUid = UserApi.shared.CURRENT_USER_ID else { return }
let REF_ADMIN = Database.database().reference().child("users").child(currentUserUid).child("admin")
REF_ADMIN.observeSingleEvent(of: .value) { (admin) in
let adminRecht = admin.value as? Bool
if adminRecht == true {
self.admin = true
} else {
self.admin = false
}
}
}
Here my database structure of the actually logged in user:
users
currentUid
admin: true
The admin value never gets true.
Thanks in advance for your help!
You need a completion as the call to firebase is asynchronous
func observeAdmin(completion:#escaping((Bool) -> () )) {
guard let currentUserUid = UserApi.shared.CURRENT_USER_ID else { return }
let REF_ADMIN = Database.database().reference().child("users").child(currentUserUid).child("admin")
REF_ADMIN.observeSingleEvent(of: .value) { (admin) in
completion( (admin.value as? Bool) ?? false )
}
}
Call
observeAdmin { (res) in
self.beitraegeMelden.isEnabled = res
self.navigationItem.rightBarButtonItem = res ? self.beitraegeMelden : nil
}

CGImageDestinationCreateWithURL return nill value

I am developing a MacOS app for to edit metadata of image. For this purpose, I use CGImageDestinationCreateWithURL function for to create destination to the file located in 'Documents' or 'Desktop' but it returns nil value. I checked paremeters of the function (URL and file type) several times but can not find reason of the issue.
Here is the code
#IBAction func browseFile(_ sender: AnyObject) {
let dialog = NSOpenPanel()
dialog.title = "Choose a .txt file"
dialog.showsResizeIndicator = true
dialog.showsHiddenFiles = false
dialog.canChooseDirectories = true
dialog.canCreateDirectories = true
dialog.allowsMultipleSelection = false
dialog.allowedFileTypes = nil
if dialog.runModal() == NSApplication.ModalResponse.OK {
let result = dialog.url // Pathname of the file
if result != nil {
let path = result!.path
filename_field.stringValue = path
let imageSource = CGImageSourceCreateWithURL(result as! CFURL, nil)
let type = CGImageSourceGetType(imageSource!)
let uurl = NSURL(fileURLWithPath: path)
// here I am trying to create a destination but it returns nil
var imageDest: CGImageDestination = CGImageDestinationCreateWithURL(uurl, type!, 1, nil)!
}
} else {
// User clicked on "Cancel"
return
}
}

Sound through UIButton does not work, swift

I have 4 buttons that trigger 4 different sounds. All buttons work, I have a println button 1, button2, etc.. For some reason I am only hearing sounds that come through button 3 and 4. I used the same coding method for all buttons and audio players, So I have no idea what the problem could be. This is my code.
There are no errors or anything and again all buttons and audio players work the same, so I'm not sure why button 1 and 2 don't work.
Any help would be much appreciated.
class MusicPlayer {
var onePlayer : AVAudioPlayer?
var twoPlayer : AVAudioPlayer?
var threePlayer : AVAudioPlayer?
var fourPlayer : AVAudioPlayer?
func playOneSound() {
twoPlayer!.play()
}
func playTwoSound() {
twoPlayer!.play()
}
func playThreeSound() {
threePlayer!.play()
}
func playFourSound() {
fourPlayer!.play()
}
func stopOneSound() {
twoPlayer!.stop()
}
func stopTwoSound() {
twoPlayer!.stop()
}
func stopThreeSound() {
threePlayer!.stop()
}
func stopFourSound() {
fourPlayer!.stop()
}
class var sharedInstance: MusicPlayer {
struct Static {
static var instance: MusicPlayer?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = MusicPlayer()
}
return Static.instance!
}
init() {
// Create an NSURL for the correct file
let oneSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Go To Sleep 1", ofType: "mp3")!)
let twoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Go To Sleep 2", ofType: "mp3")!)
let threeSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Go To Sleep 3", ofType: "mp3")!)
let fourSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Go To Sleep 5", ofType: "mp3")!)
// Create a new AVAudioPlayer with the correct file
onePlayer = AVAudioPlayer(contentsOfURL: oneSound, error: nil)
twoPlayer = AVAudioPlayer(contentsOfURL: twoSound, error: nil)
threePlayer = AVAudioPlayer(contentsOfURL: threeSound, error: nil)
fourPlayer = AVAudioPlayer(contentsOfURL: fourSound, error: nil)
/*onePlayer!.volume = masterEffectSoundLevel
twoPlayer!.volume = masterEffectSoundLevel
threePlayer!.volume = masterEffectSoundLevel
fourPlayer!.volume = masterEffectSoundLevel*/
// Prepare for playback, set loop count to infinite, start playback
onePlayer!.prepareToPlay()
twoPlayer!.prepareToPlay()
threePlayer!.prepareToPlay()
fourPlayer!.prepareToPlay()
}
This is my code for the buttons :
#IBAction func settingOneButton(sender: UIButton) {
settingOne.hidden = false
settingTwo.hidden = true
settingThree.hidden = true
settingFour.hidden = true
}
#IBAction func settingTwoButton(sender: UIButton) {
settingOne.hidden = true
settingTwo.hidden = false
settingThree.hidden = true
settingFour.hidden = true
}
#IBAction func settingThreeButton(sender: UIButton) {
settingOne.hidden = true
settingTwo.hidden = true
settingThree.hidden = false
settingFour.hidden = true
}
#IBAction func settingFourButton(sender: UIButton) {
settingOne.hidden = true
settingTwo.hidden = true
settingThree.hidden = true
settingFour.hidden = false
}
#IBAction func goToSleepPressed(sender: AnyObject) {
if settingOne.hidden == false {
MusicPlayer.sharedInstance.playOneSound()
MusicPlayer.sharedInstance.stopTwoSound()
MusicPlayer.sharedInstance.stopThreeSound()
MusicPlayer.sharedInstance.stopFourSound()
println("one")
} else if settingTwo.hidden == false {
MusicPlayer.sharedInstance.playTwoSound()
MusicPlayer.sharedInstance.stopOneSound()
MusicPlayer.sharedInstance.stopThreeSound()
MusicPlayer.sharedInstance.stopFourSound()
println("two")
} else if settingThree.hidden == false {
MusicPlayer.sharedInstance.playThreeSound()
MusicPlayer.sharedInstance.stopOneSound()
MusicPlayer.sharedInstance.stopTwoSound()
MusicPlayer.sharedInstance.stopFourSound()
println("three")
} else if settingFour.hidden == false {
MusicPlayer.sharedInstance.playFourSound()
MusicPlayer.sharedInstance.stopOneSound()
MusicPlayer.sharedInstance.stopTwoSound()
MusicPlayer.sharedInstance.stopThreeSound()
println("four")
}
}
I figured out what the problem was. I had twoPlayer both in playOneSound() and playTwoSound().