How do I convert NSOpenPanel.URL to a string? - macos

I was trying to display an open file dialog in OSX via Xcode and Swift.
I then wanted to put the filename in a TextField.
I started with
#IBOutlet weak var lblFileName: NSTextField!
#IBAction func FileOpen(sender: AnyObject) {
var f:NSOpenPanel = NSOpenPanel()
f.title = "open that file"
f.allowsMultipleSelection = false
f.canChooseDirectories = false
f.runModal()
var thefile = f.URLs[0].absoluteString
println(thefile)
//failed: lblFileName.stringValue = thefile
lblFileName.stringValue = "I want this to be the filename!"
}
println(thefile) worked, so it was just an issue with converting the URL
The variable "thefile" wasn't a string and all attempts to cast it failed.
I did get it working so I thought I'd post the answer here as well.

Here's the code that ended up working
note I created a string named mystring and had to use the ? and the ! to get things to work.
If there's an easier/better way please add that in the comments!
#IBOutlet weak var lblFileName: NSTextField!
#IBAction func FileOpen(sender: AnyObject) {
var f:NSOpenPanel = NSOpenPanel()
f.title = "open that file"
f.allowsMultipleSelection = false
f.canChooseDirectories = false
f.runModal()
var thefile = f.URLs[0].absoluteString
println(thefile)
var mystring:String? = thefile
lblFileName.stringValue = mystring!
}

Related

How to use an array to fill the title text

I've created a customized keyboard using UIView. I'm trying to auto-fill the letters using a for loop but with no success.
func initializeSubviews() {
let xibFileName = "keyboardView" // xib extension not included b
let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)![0] as! UIView
self.addSubview(view)
view.frame = self.bounds
setKeyboardText()
}
#IBOutlet var keyboardLetters: [myKeyboardBtn]!
func setKeyboardText() {
let str = "abcdefghijklmnopqrstuvwxyz"
let characterArray = Array(str)
for (Index, key) in keyboardLetters.enumerated() {
key.titleLabel?.text = String(characterArray[Index])
}
// [a,b,c,d,...]
}
what am I doing wrong?
According to Apple
"To set the actual text of the label, use setTitle(_:for:)
(button.titleLabel.text does not let you set the text)."

How to import ViewController data into email in Swift 3?

I am VERY new to Swift/xcode and I've built my first app but I'm stuck on one part. I have a button that opens an email and I would like to take the selections from a picker, two date pickers and a text input and import them into the email. I want the user to make their choices and just click send when the email opens. Everything works fine but I can't figure out how to import the data from the app into the email despite searching all over. Any suggestions?
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["myemail#myemail.com"])
mailComposerVC.setSubject("EQUIPMENT RESERVATION REQUEST")
mailComposerVC.setMessageBody("test email message", isHTML: false)
return mailComposerVC
}
Basically, I want to replace the "test email message" string with the selections from my date pickers, picker and text input.
I was able to figure this out using the link from Kevin above and the following links:
How to store data from a picker view in a variable when a button is pressed?
Get just the date (no time) from UIDatePicker
The revised code is below and works exactly as I wanted it to:
#IBOutlet weak var StartDate: UIDatePicker!
#IBOutlet weak var EndDate: UIDatePicker!
#IBOutlet weak var HowMany: UITextField!
func configuredMailComposeViewController() -> MFMailComposeViewController {
let chosen = Picker1.selectedRow(inComponent: 0)
let chosenString = words[chosen]
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd"
let stringDate = dateFormatter.string(from: StartDate.date)
let Start = stringDate
let number = HowMany.text
let stringendDate = dateFormatter.string(from: EndDate.date)
let End = stringendDate
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["myemail#example.com"])
mailComposerVC.setSubject("Email Subject")
mailComposerVC.setMessageBody ("Please reserve \(number ?? "") of
the following **\(chosenString)** from \(Start) to \(End).
Thanks.", isHTML: false)
return mailComposerVC
}

How can I rename label with another class attribute?

So, here is the part of class OnboardingViewController, where declared and initialized reviewConsentStep.
class OnboardingViewController: UIViewController {
// MARK: IB actions
#IBAction func joinButtonTapped(sender: UIButton) {
let consentDocument = ConsentDocument()
let consentStep = ORKVisualConsentStep(identifier: "VisualConsentStep", document: consentDocument)
let healthDataStep = HealthDataStep(identifier: "Health")
let signature = consentDocument.signatures!.first!
let reviewConsentStep = ORKConsentReviewStep(identifier: "ConsentReviewStep", signature: signature, inDocument: consentDocument)
reviewConsentStep.text = "Review the consent form."
reviewConsentStep.reasonForConsent = "Consent to join the Developer Health Research Study."
let passcodeStep = ORKPasscodeStep(identifier: "Passcode")
passcodeStep.text = "Now you will create a passcode to identify yourself to the app and protect access to information you've entered."
let completionStep = ORKCompletionStep(identifier: "CompletionStep")
completionStep.title = "Welcome aboard."
completionStep.text = "Thank you for joining this study."
let orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, healthDataStep, passcodeStep, completionStep])
let taskViewController = ORKTaskViewController(task: orderedTask, taskRunUUID: nil)
taskViewController.delegate = self
presentViewController(taskViewController, animated: true, completion: nil)
}
I want to use reviewConsentStep.signature?.givenName and reviewConsentStep.signature?.familyName here:
#IBOutlet var applicationNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
applicationNameLabel.text = reviewConsentStep.signature?.givenName/////////... here
If it possible, please tell me how can I do it?

Root Privilegs for NSTask in Swift

I searched a lot on the web to find a simple way to get root privileges in my NSTask but I only found old articles which are written in Objective-C. But my Xcode Project is written in Swift :x is there a way to solve this problem to run a NSTask with Root Privilegs? :) I know I have to use something like AppleScript, STPrivilegedTask or the BetterAuthorizationSample from Apple but all I've found is written in Objective-C...
My Idea is to create a application that makes a storage media bootable with the command createinstallmedia :p all works perfectly the only problem is that the command wants root privileges, for testing I simply open my Terminal and login as Root but this is not the greatest solution for this Problem :D so please help me! :o
My Code the only thing that miss is the code to get root access:
import Cocoa
class ViewController: NSViewController {
var Task = NSTask()
var openPanel = NSOpenPanel()
var workingpath_createinstallmedia : String!
var workingpath_medium : String!
var workingpath_application : String!
var volume_flag = "--volume"
var applicationpath_flag = "--applicationpath"
var nointeraction_flag = "--nointeraction"
var commandpath : String!
var postcommand : [String]!
var DirectoryOS : NSURL!
var DirectoryMedium : NSURL!
#IBOutlet weak var PathControlOS: NSPathControl!
#IBOutlet weak var PathControlMedium: NSPathControl!
#IBOutlet weak var Outputlabel: NSTextField!
#IBAction func OSauswählen(sender: AnyObject) {
openPanel.canChooseDirectories = false
openPanel.canChooseFiles = true
openPanel.canCreateDirectories = false
openPanel.allowsMultipleSelection = false
if openPanel.runModal() == NSModalResponseOK {
DirectoryOS = openPanel.URLs[0] as NSURL
PathControlOS.objectValue = DirectoryOS
}
}
#IBAction func Mediumauswählen(sender: AnyObject) {
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = false
openPanel.canCreateDirectories = false
openPanel.allowsMultipleSelection = false
if openPanel.runModal() == NSModalResponseOK {
DirectoryMedium = openPanel.URLs[0] as NSURL
PathControlMedium.objectValue = DirectoryMedium
}
}
#IBAction func starttask(sender: AnyObject) {
// edit Strings
// Createinstallmedia
workingpath_createinstallmedia = String(DirectoryOS)
workingpath_createinstallmedia = workingpath_createinstallmedia.stringByReplacingOccurrencesOfString("file://", withString: "")
workingpath_application = workingpath_createinstallmedia.stringByReplacingOccurrencesOfString("%20", withString: " ")
workingpath_createinstallmedia = workingpath_application + "/Contents/Resources/createinstallmedia"
// Medium
workingpath_medium = String(DirectoryMedium)
workingpath_medium = workingpath_medium.stringByReplacingOccurrencesOfString("file://", withString: "")
workingpath_medium = workingpath_medium.stringByReplacingOccurrencesOfString("%20", withString: " ")
// config Task Parameters
commandpath = workingpath_createinstallmedia
postcommand = [volume_flag,workingpath_medium,applicationpath_flag,workingpath_application,nointeraction_flag]
// commit the Parameters to the Task
Task.launchPath = commandpath
Task.arguments = postcommand
// start Task
Task.launch()
Task.waitUntilExit()
}
}
Thanks for your help!!!
I solved using sudo into the command and asking to the user for the password to give directly to the sudo, in the following way:
echo "passwordhere" | sudo -S command --arguments
and doing this using the sh shell executable to run the process, using this method i successfully created an app to create bootable mac os install media called TINU, but you need to be careful while dealing with user password, i chose to make my app open source to let others know what it does with this kinds of tasks that needs user password, but on mac os you should create specialized programs that does this kind of privileged tasks and then start them using system apis that will manage authentication for you and let the specialized program to do his job.

error message in Xcode v 6.3.2

I'm getting this error message in relation to the exclamation mark at the end of this line:
sound1.URL = soundURL!
"Cannot assign a value of type ‘NSURL’ to a value of type ‘NSURL’
Type"
I've googled this issue and looked at a couple of explanations for this error code but I still can't work out what's wrong. Can anyone help?
import UIKit
import AVFoundation
class SoundListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var audioPlayer = AVAudioPlayer()
var sounds: [Sound] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.dataSource = self
self.tableView.delegate = self
var soundPath = NSBundle.mainBundle().pathForResource("mhsTesting", ofType: "m4a")
var soundURL = NSURL.fileURLWithPath(soundPath!)
var sound1 = Sound()
sound1.name = "Michael"
sound1.URL = soundURL!
self.sounds.append(sound1)
}
}
This is your Sound class?
class Sound{
var name: String?
var URL : NSURL.Type?
}
Try with code below:
class Sound{
var name: String?
var URL : NSURL?
}

Resources