Xcode : read plist data and display them as text - xcode

I totally forgot about Xcode AppleScript Application.
Basically, the application will read value from plist file.
My applescript to read this variable is
set the plistfile_path to "~/Desktop/example.plist"
tell application "System Events"
set p_list to property list file (plistfile_path)
-- read the plist data
set theNameFromPlist to value of property list item "theName" of p_list
set theEmailFromPlist to value of property list item "theEmail" of p_list
set thecreationDateFromPlist to value of property list item "creationDate" of p_list
end tell
now how do I integrate this to Xcode?
Should I go on AppDelegate.applescript and add wherever after "applicationWillFinishLaunching_(aNotification)" this script ?
followed by property NametextField : theNameFromPlist
I'm probably totally wrong here, just can't think.
PS swift will do it if any easier

Like vadian said in the comments, In Xcode, System Events won't run properly so you can just use the native Cocoa classes but I prefer to
use "do shell script" applescript/asobjc command and run the "defaults" command so here is a way to do that when the application will finish launching:
on applicationWillFinishLaunching_(aNotification)
set plistFile to "~/Desktop/example.plist"
set theNameFromPlist to do shell script "defaults read " & plistFile & " theName"
set theEmailFromPlist to do shell script "defaults read " & plistFile & " theEmail"
set theCreationDateFromPlist to do shell script "defaults read " & plistFile & " creationDate"
end applicationWillFinishLaunching_
And if you are trying to display the name in a TextField on a Window
in the Interface Builder you can just add Modify the code to this:
property nameTextField : missing value
on applicationWillFinishLaunching_(aNotification)
set plistFile to "~/Desktop/example.plist"
set theNameFromPlist to do shell script "defaults read " & plistFile & " theName"
set theEmailFromPlist to do shell script "defaults read " & plistFile & " theEmail"
set theCreationDateFromPlist to do shell script "defaults read " & plistFile & " creationDate"
tell nameTextField to setStringValue_(theNameFromPlist)
end applicationWillFinishLaunching_
(make sure to connect the property nameTextField to a TextField in the Interface Builder)
hope this Helped!! :D

Mentioning Cocoa classes I actually meant this
set plistFile to POSIX path of (path to desktop) & "example.plist"
set thePlist to (current application's NSDictionary's dictionaryWithContentsOfFile:plistFile) as record
set theNameFromPlist to thePlist's theName
set theEmailFromPlist to thePlist's theEmail
To add new key value pairs and write the plist back to disk add
set thePlist to thePlist & {stringKey:"Foo", booleanKey:false}
set cocoaDictionary to current application's NSDictionary's dictionaryWithDictionary:thePlist
cocoaDictionary's writeToFile:plistFile atomically:true

Related

AppleScript to append date to file

I was recently able to make a drag and drop script in Automator that allowed me to zip and name a file and then automatically apply the date (DDMMYY) but now it's defaulting to (DDMMYYYY) and I can't change it. I've googled for a solution and nothing works since this needs to be at the end of the file name.
Does anyone know what I'm doing wrong or does anyone have an actual script that can help me? Everything I've found only works if the date is at the start of the file name, not at the end (but before the extension).
You can use this AppleScript inside a Run AppleScript action, it renames the archive inserting the date before the file extension
on run {input, parameters}
set thePath to POSIX path of (item 1 of input)
set currentDate to do shell script "date +%d%m%y"
set newPath to text 1 thru -5 of thePath & "_" & currentDate & ".zip"
do shell script "mv " & quoted form of thePath & space & quoted form of newPath
return {POSIX file newPath as alias}
end run
Since you didn't provide any code I can't guess how you name your files, but the way to get DDMMYY is to use shell with the do shell script command:
tell application "Finder"
set theFile to (choose file)
set theName to name of theFile
set name of theFile to theName & "_" & (do shell script "date +%d%m%y") & ".xxx"
end tell
This doesn't get rid of the file extension of the original file. For that to work you would have to use something like this:
tell application "Finder"
set theFile to (choose file)
set theName to name of theFile
set periodIndex to offset of "." in theName
set theName to text 1 thru (periodIndex - 1) of theName
set name of theFile to theName & "_" & (do shell script "date +%d%m%y") & ".xxx"
end tell
The code responsible for removing the file extension comes from this post.
You can add punctuation how you like by putting the desired symbols before the next %. So date +%d.%m.%y is possible and improves readability.

How to work-around AppleScript <<format of disk>> command working from within Script Editor but failing when saved as an .app?

The following script works as desired when run in the AppleScript editor but not when exported as .app and run directly.
tell application "Finder"
set fld to choose folder with prompt "Choose a volume" default location ("/Volumes")
set n to name of fld
set f to format of fld
display dialog n & " is formatted as " & f
end tell
(*
When run from Script Editor result is:
Macbook HD is formatted as Mac OS Extended format
When run from a compiled app result is:
Macbook HD is formatted as «constant ****dfh+»
*)
I'm running OS X 10.11.6 (15G22010). Fixes or work-arounds welcome.
The issue is that Mac OS Extended format is an enumerated constant (actually in integer value). It cannot be accessed outside of a Finder tell block and in an app the display dialog line is apparently treated as being outside the tell block. You have to coerce the enumeration to text.
I suggest this code, it uses the disk class of System Events and lists the disks
set theVolumes to list folder "/Volumes"
set chosenVolume to choose from list theVolumes with prompt "Select a volume"
if chosenVolume is false then return
set chosenVolume to item 1 of chosenVolume
tell application "System Events" to set volumeFormat to (format of disk chosenVolume as text)
display dialog chosenVolume & " is formatted as " & volumeFormat
Edit: The code above doesn't work apparently due to a bug.
This is an alternative with a little help from AppleScriptObjC and the Foundation framework
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
use framework "Foundation"
set theVolumes to list folder "/Volumes"
set chosenVolume to choose from list theVolumes with prompt "Select a volume"
if chosenVolume is false then return
set chosenVolume to item 1 of chosenVolume
tell application "System Events" to set volumeURL to URL of disk chosenVolume
set theURL to current application's NSURL's alloc()'s initWithString:volumeURL
set {success, theFormat, theError} to theURL's getResourceValue:(reference) forKey:(current application's NSURLVolumeLocalizedFormatDescriptionKey) |error|:(reference)
if success then
display dialog chosenVolume & " is formatted as " & (theFormat as text)
else
display dialog theError's localizedDescription() as text
end if

How to reveal default Safari downloads folder through Applescript?

I am new to AppleScript and would like to know how to reveal the default downloads folder in Safari through AppleScript.
--- WHAT I HAVE ALREADY TRIED ---
set filePath to do shell script "defaults read com.apple.Safari DownloadsPath"
do shell script "open " & quoted form of filePath
The above script to my understanding will set the variable "filePath" to Safari's default PList entry in preferences.
This works great as long as the location is NOT somewhere within the user home folder. If its within a user folder, the Log shows me a "~/" before the path with no reference to anything prior to the user home folder (relative path)
How do i accomplish my goal? is there a way to get the absolute path to the folder? Or perhaps an alternative method?
Based on #WilliamTFroggard's answer:
tell application "Finder"
set folderPath to do shell script "defaults read com.apple.Safari DownloadsPath"
if folderPath = "~" or folderPath starts with "~/" then ¬
set folderPath to text 1 thru -2 of POSIX path of (path to home folder) & rest of characters of folderPath
open POSIX file folderPath as alias
activate
end tell
The text element is used to strip the trailing / from the home folder (/Users/johndoe/).
The rest property returns every character following the ~ in folderPath (~/Downloads).
/Users/johndoe + /Downloads = /Users/johndoe/Downloads.
You can do this by Applescript GUI Scripting to make Applescript click the 'show downloads' option from the 'view' menu:
tell application "Safari"
activate
end tell
tell application "System Events"
tell process "Safari"
tell menu bar 1
tell menu bar item "view"
tell menu "View"
click menu item "Show downloads"
end tell
end tell
end tell
end tell
end tell
Here's a method using Python:
do shell script "python -c \"import os; print os.path.expanduser('`defaults read com.apple.Safari DownloadsPath`')\""
If you really want the long AppleScript method, try this:
set filePath to ""
set AppleScript's text item delimiters to "/"
set filePathWords to words of (do shell script "defaults read com.apple.Safari DownloadsPath")
if item 1 of filePathWords is "~" then
set item 1 of filePathWords to (POSIX path of (path to home folder as string))
set filePath to filePathWords as string
else
set filePath to "/" & filePathWords as string
end if
If that second "/" in the path bothers you (it sort of bothers me...), you can use this instead:
set filePath to ""
set AppleScript's text item delimiters to "/"
set filePathWords to words of (do shell script "defaults read com.apple.Safari DownloadsPath")
if item 1 of filePathWords is "~" then
set item 1 of filePathWords to (do shell script "cd ~ && pwd")
set filePath to filePathWords as string
else
set filePath to "/" & filePathWords as string
end if
I think what you want is this:
tell application "Finder"
activate
open ("/Users/yourname/Downloads" as POSIX file)
end tell
Just replace "yourname" with your name in Finder.

Applescript Application will Add Key/Value Pair to Multiple Applications

My goal was to create a drag'n'drop AppleScript application that will replace NSUIElement key/value pairs in the application's info.plist file. This will effectively hide application's icons from the Dock & Application-Switcher.
So far this creates an extra 'Info.plist' file called "Info.plist.plist" in ƒContents, with the NSUIElement value as the only key/value pair (it will not ammend the original file). Can you suggest a solution?
-- OS X 10.3.9
on open ItemList
repeat with x in ItemList
set apppath to POSIX path of x
set infile to quoted form of (apppath & "Contents/Info.plist")
do shell script "defaults write " & infile & " 'NSUIElement' '1'"
end repeat
end open
I'm not sure that I have enough info to come up with an answer, but my guess is that
do shell script "defaults write " & infile & " 'NSUIElement' '1'" with administrator privileges
will work.

Applescript Shell Script Progress

I am creating an applescript that creates a backup image of the /Users folder in Mac Os X. I would like to do one of two things:
Either display a barber pole progress bar while the shell script is running with an option to quit.
Display a dialog box while the script is running with an option to quit.
I have tried doing the shell script with the /dev/null but that ignores all output. I would like to save the output and display it in a dialog for the user.
Here is my code:
set computername to (do shell script "networksetup -getcomputername")
set fin to ""
set theIcon to note
tell application "Finder"
try
set folderalias to "/Users"
set foldersize to physical size of folder (alias ":Users") --(info for folderalias)
set foldersize to (round ((foldersize / 1.0E+9) * 100)) / 100
on error
tell application "System Events"
set foldersize to (round (((get physical size of folder ":Users" as text) / 1.0E+9) * 100)) / 100
end tell
end try
end tell
display dialog "User profile backup utility" & return & return & ¬
"The computer name is: " & computername & return & return & ¬
"The '/Users/' directory size is: " & "~" & foldersize & " GB" & return & return & ¬
"Would you like to backup the '/User' directory now?" & return ¬
buttons {"Cancel", "Backup Now"} default button "Backup Now"
set comd to "hdiutil create ~/Desktop/" & computername & ".dmg -srcfolder /test/"
set fin to do shell script (comd) with administrator privileges
display dialog fin
Displaying a progress bar dialog is not possible with on-board AppleScript (i.e. Standard Additions), but this can be achieved using Shane Stanley’s ASObjC Runner, a scriptable faceless background application which provides, among many over useful functions, a set of progress dialog related commands. Once downloaded onto your system,
tell application "ASObjC Runner"
reset progress
set properties of progress window to {button title:"Abort Backup", button visible:true, message:"Backing up the '" & (POSIX path of folderalias) & "' directory.", detail:"There are " & foldersize & " GB of data to backup – this might take some time.", indeterminate:true}
activate
show progress
end tell
try -- to make sure we destroy the dialog even if the script error out
<your backup operation here>
end try
tell application "ASObjC Runner" to hide progress
will show an indeterminate progress bar (or “barber pole”) while the backup operation runs – at least if it is synchronous (as shell commands called from AS are). As to the output of your shell command, that is automatically returned by the do shell script command – in your code, it is assigned to fin [code lifted more or less wholesale from the ASObjC Runner documentation].
ASObjC Runner can be embedded into an AppleScript application (save your script as an application in AppleScript Editor) by putting it into the bundle’s Resources folder (in Finder, select Show Package Contents in the context menu) and using the path to resource command to call it inside a using terms from block – the documentation I linked to above has details and example code, but, crucially, contains one critical error: your tell statement needs to use the POSIX path to the Resources bundle (tell application (POSIX path of (path to resource "ASObjC Runner.app"))).
A few remarks on your code:
there is a more elegant way to get an alias to the /Users folder:
path to users folder
– no need for hardwiring and calls to Finder. You can then get the shell compatible path to that by using POSIX path of, or, if you need it quoted, quoted form of POSIX path of of it.
I’d recommend using only System Events to get the physical size – unlike Finder, it works in the background. That will allow you to get rid of the tell application "Finder" and try … catch blocks (not sure what you meant to achieve by that one anyway – if you were reacting to error -10004, that is because round does not like to be put inside a tell block).
No need to initialize fin to an empty string – you will get a return value from do shell script.
Speaking of your do shell script, you need to quote the computerName variable of it will break on spaces in that name.
theIcon is never used.
You might want to use display alert instead of display dialog for the user confirmation, as it has a nice emphasis on the first part of the message.
There are a lot of unnecessary parentheses in the code – AppleScript needs some of these to delimit semantic command blocks, but not all of them…
All together mean your code can be modified to:
set computerName to do shell script "networksetup -getcomputername"
set folderAlias to path to users folder
tell application "System Events" to set folderSize to physical size of folderAlias
set folderSize to round(folderSize / 1.0E+9 * 100) / 100
display alert "User profile backup utility" message ¬
"The computer name is: " & computerName & return & return & ¬
"The '" & (POSIX path of folderAlias) & "' directory size is: " & "~" & folderSize & " GB" & return & return & ¬
"Would you like to backup the '" & (POSIX path of folderAlias) & "' directory now?" & return ¬
buttons {"Cancel", "Backup Now"} default button "Backup Now"
set shellCmd to "hdiutil create ~/Desktop/'" & computerName & "'.dmg -srcfolder /test/"
-- progress bar dialog display initialization goes here
try
set shellOutput to do shell script shellCmd with administrator privileges
end try
-- progress bar dialog hiding goes here
display dialog shellOutput
Although not as pretty as kopischke's suggestion, a quick and dirty way to get progress information is to run the command in the terminal itself.
set comd to "hdiutil create -puppetstrings '~/Desktop/" & computername & ".dmg' -srcfolder '/test/'"
tell application "Terminal" to do script comd

Resources