Hi,
I'm reading Everyday AppleScriptObjC 3rd Edition by Shane Stanley and I've just found how to get tags of a file (in Chapter 14, 'One For the Files'). We can use the -getResourceValue:forKey:error: method of the NSURL class, like the following:
on tagsOfFileAtPath:POSIXPath
set theURL to current application'sclass "NSURL"'s fileURLWithPath:POSIXPath
set {theResult, theTags, theError} to theURL'sgetResourceValue:(reference) forKey:(current application'sNSURLTagNamesKey) |error|:(reference)
if theResult as boolean is false then
error (theError'slocalizedDescription() as text)
else
set theTags to theTags as list
if theTags = {missing value} then set theTags to {}
return theTags
end if
end tagsOfFileAtPath:
The NSURL class has also the -setResourceValue:forKey:error: method and we can use this method to add tags to a file, like the following:
on addTag:aListtoTheFileAtPath:POSIXPath
set newTagList to (its tagsOfFileAtPath:POSIXPath) & aList
set newTag to current application'sNSArray'sarrayWithArray:newTagList
set theURL to current application'sclass "NSURL"'s fileURLWithPath:POSIXPath
set {theResult, theError} to theURL'ssetResourceValue:newTagforKey:(current application'sNSURLTagNamesKey) |error|:(reference)
if theResult as boolean is false then
error (theError'slocalizedDescription() as text)
else
return (its tagsOfFileAtPath:POSIXPath)
end if
end addTag:toTheFileAtPath:
In case of Preview.app, we can use those scripts by the following statements:
use AppleScript version "2.4"
use framework "Foundation"
set thePOSIXPath to path of front document of application "Preview"
try
its addTag:{"Tag1", "Tag2"} toTheFileAtPath:thePOSIXPath
on error errMess
-- handle the error
end try