NSData

[NSData]OPENから保存まで


AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#
005# com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013
014##画像のURL
015set strURL to ("https://abs.twimg.com/favicons/twitter.2.ico") as text
016set ocidURLString to refMe's NSString's stringWithString:(strURL)
017set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLString)
018set ocidFileName to ocidURL's lastPathComponent()
019
020##NSDATAに読み込む
021set ocidOption to (refMe's NSDataReadingMappedIfSafe)
022set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error| :(reference)
023if (item 2 of listResponse) = (missing value) then
024  log "正常処理"
025  set ocidReadData to (item 1 of listResponse)
026else if (item 2 of listResponse) ≠ (missing value) then
027  set strErrorNO to (item 2 of listResponse)'s code() as text
028  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
029  refMe's NSLog("■:" & strErrorNO & strErrorMes)
030  return "エラーしました" & strErrorNO & strErrorMes
031end if
032
033#保存用のパスを作っておく
034set appFileManager to refMe's NSFileManager's defaultManager()
035set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
036set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
037set ocidSaveFilePathURL to ocidDesktopDirPathURL's URLByAppendingPathComponent:(ocidFileName) isDirectory:(false)
038
039##NSDataで保存
040set ocidOption to (refMe's NSDataWritingAtomic)
041set listDone to ocidReadData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error| :(reference)
042if (item 1 of listDone) is true then
043  log "正常処理"
044else if (item 2 of listDone) ≠ (missing value) then
045  set strErrorNO to (item 2 of listDone)'s code() as text
046  set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
047  refMe's NSLog("■:" & strErrorNO & strErrorMes)
048  return "エラーしました" & strErrorNO & strErrorMes
049end if
AppleScriptで生成しました

|

[RTFFromRange]ブランク(空)のRTFリッチテキスト書類を作成する

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
#                       com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application

################################
##### パス関連
################################
set strFilePath to "~/Desktop/空のRTF書類.rtf" as text
set ocidFilePathStr to refMe's NSString's stringWithString:strFilePath
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false

################################
##### NSAttributedString関連
################################
####空のNSAttributedString
set ocidBlankStrings to refMe's NSAttributedString's alloc()'s initWithString:""
####NSdataにRTFとして保存
set ocidBlankRTFData to ocidBlankStrings's RTFFromRange:{location:0, |length|:0} documentAttributes:(missing value)

################################
##### 保存
################################
####ファイルに書き出し
set boolFileWrite to (ocidBlankRTFData's writeToURL:ocidFilePathURL atomically:true)


|

[Json]祝祭日の取得

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSData : a reference to refMe's NSData
property refNSURL : a reference to refMe's NSURL
property refNSDictionary : a reference to refMe's NSDictionary
property refNSMutableDictionary : a reference to refMe's NSMutableDictionary
property refNSJSONSerialization : a reference to refMe's NSJSONSerialization

###URL
set strURL to "https://holidays-jp.github.io/api/v1/date.json"



#####################
###NSURL
set ocidJsonURL to (refNSURL's URLWithString:strURL)
###URLの内容を読み込む
set listDownLoadData to refNSData's dataWithContentsOfURL:ocidJsonURL options:0 |error|:(reference)
-->戻り値がList
####JSONのデータ部
set ocidJsonData to (item 1 of listDownLoadData)
####エラー情報
set ocidNSErrorData to item 2 of listDownLoadData
if ocidNSErrorData is not (missing value) then
doGetErrorData(ocidNSErrorData)
end if
#####################
###JSON初期化
set listJSONSerialization to (refNSJSONSerialization's JSONObjectWithData:ocidJsonData options:0 |error|:(reference))
set ocidJsonData to item 1 of listJSONSerialization
#####レコードに格納
set ocidJsonResponse to (refNSDictionary's alloc()'s initWithDictionary:ocidJsonData)

#####################
###参照

set strDateText to "2023-08-11" as text

set ocidValue to ocidJsonResponse's valueForKey:strDateText
log ocidValue as text
-->(*山の日*)

set strDateText to "2023-08-12" as text

set ocidValue to ocidJsonResponse's valueForKey:strDateText
log ocidValue as text
-->(*missing value*)




to doGetErrorData(ocidNSErrorData)
#####個別のエラー情報
log "エラーコード:" & ocidNSErrorData's code() as text
log "エラードメイン:" & ocidNSErrorData's domain() as text
log "Description:" & ocidNSErrorData's localizedDescription() as text
log "FailureReason:" & ocidNSErrorData's localizedFailureReason() as text
log ocidNSErrorData's localizedRecoverySuggestion() as text
log ocidNSErrorData's localizedRecoveryOptions() as text
log ocidNSErrorData's recoveryAttempter() as text
log ocidNSErrorData's helpAnchor() as text
set ocidNSErrorUserInfo to ocidNSErrorData's userInfo()
set ocidAllValues to ocidNSErrorUserInfo's allValues() as list
set ocidAllKeys to ocidNSErrorUserInfo's allKeys() as list
repeat with ocidKeys in ocidAllKeys
if (ocidKeys as text) is "NSUnderlyingError" then
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedDescription() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedFailureReason() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoverySuggestion() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoveryOptions() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s recoveryAttempter() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s helpAnchor() as text
else
####それ以外の値はそのままテキストで読める
try
log (ocidKeys as text) & ": " & (ocidNSErrorUserInfo's valueForKey:ocidKeys) as text
end try
end if
end repeat

end doGetErrorData

|

[NSPropertyListSerialization] plist データ Data形式

BASE64のテキストとして格納される



#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSData : a reference to refMe's NSData
property refNSURL : a reference to refMe's NSURL
property refNSMutableDictionary : a reference to refMe's NSMutableDictionary
property refNSPropertyListSerialization : a reference to refMe's NSPropertyListSerialization


###デスクトップに空のplistを作成
set strFilePath to ("~/Desktop/com.smaple.test.plist")
###NSStringにして
set ocidPosixPath to refNSString's stringWithString:strFilePath
##NSStringフルパスにして
set ocidPosixFullPath to ocidPosixPath's stringByStandardizingPath



###空のレコード
set ocidPlistData to refNSMutableDictionary's alloc()'s initWithCapacity:0
--->特に意味ないけどtellしておいた方が可読性は高いね
tell ocidPlistData
-->テキストをデータで
set strVale to "美しい日本語"
##NSstringにして
set ocidString to refNSString's stringWithString:strVale
###DATAにして
set ocidData to ocidString's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
###書き込み
ocidPlistData's setObject:(ocidData) forKey:"data01"

-->イメージをデータで
set strFilePath to "/System/Library/Desktop Pictures/Solid Colors/Black.png"
###URLにして
set ocidFilePathURL to refNSURL's alloc()'s initFileURLWithPath:strFilePath
###Dataに読み込んで
set ocidDataContants to refNSData's dataWithContentsOfURL:ocidFilePathURL
###BASE64にして
set ocidDataContantsStr to ocidDataContants's base64EncodedStringWithOptions:(refMe's NSDataBase64EncodingEndLineWithLineFeed)
###書き込み
set ocidData to ocidDataContantsStr's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
ocidPlistData's setObject:(ocidData) forKey:"data02"


end tell
######################
###定型どちらか選ぶ
###バイナリー形式
set ocidBinplist to refMe's NSPropertyListBinaryFormat_v1_0
###XML形式
set ocidXmlplist to refMe's NSPropertyListXMLFormat_v1_0
####書き込み用にバイナリーデータに変換
set ocidPlistEditData to refMe's NSPropertyListSerialization's dataWithPropertyList:ocidPlistData format:ocidXmlplist options:0 |error|:(missing value)
####書き込み
####ocidPlistEditData's writeToFile:ocidPosixFullPath atomically:true
set boolWritetoUrlArray to ocidPlistEditData's writeToFile:ocidPosixFullPath options:0 |error|:(reference)
log boolWritetoUrlArray
log class of boolWritetoUrlArray as text
(*
NSDataWritingAtomic = 1UL << 0,
NSDataWritingWithoutOverwriting = 1UL << 1,
NSDataWritingFileProtectionNone = 0x10000000,
NSDataWritingFileProtectionComplete = 0x20000000,
NSDataWritingFileProtectionCompleteUnlessOpen = 0x30000000,
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication = 0x40000000,
NSDataWritingFileProtectionMask = 0xf0000000,
*)
set ocidWriteToUrlResults to item 1 of boolWritetoUrlArray
set ocidErrorResults to item 2 of boolWritetoUrlArray
log ocidWriteToUrlResults
log
if ocidWriteToUrlResults is true then
ocidPlistEditData's release()
ocidPlistData's release()
else
try
log ocidWriteToUrlResults's localizedDescription() as text
log ocidWriteToUrlResults's localizedFailureReason() as text
log ocidWriteToUrlResults's localizedRecoverySuggestion() as text
log ocidWriteToUrlResults's localizedRecoveryOptions() as text
log ocidWriteToUrlResults's recoveryAttempter() as text
log ocidWriteToUrlResults's helpAnchor() as text
end try
log "ファイルの書き込みに失敗しました"
end if

|

[XML] initWithData

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSArray : a reference to objMe's NSArray
property objNSMutableString : a reference to objMe's NSMutableString
property objNSURL : a reference to objMe's NSURL


property objNSData : a reference to objMe's NSData

property objNSXMLElement : a reference to objMe's NSXMLElement
property objNSXMLParser : a reference to objMe's NSXMLParser
property objNSXMLDocument : a reference to objMe's NSXMLDocument
property objNSXMLNodePreserveWhitespace : a reference to objMe's NSXMLNodePreserveWhitespace


property objNSNotFound : a reference to 9.22337203685477E+18 + 5807

set objFileManager to objMe's NSFileManager's defaultManager()


set strPosixPath to "/Applications/Utilities/Adobe Sync/CoreSync/customhook/coresync.xml"
log strPosixPath as text
log class of strPosixPath

set ocidPosixPath to objNSString's stringWithString:strPosixPath
log ocidPosixPath as text
log className() of ocidPosixPath as text

-->(*__NSCFString*)


set ocidPosixFullPath to ocidPosixPath's stringByStandardizingPath
log ocidPosixFullPath as text
log className() of ocidPosixFullPath as text

-->(*NSPathStore2*)

set ocidPosixPathURL to objNSURL's fileURLWithPath:ocidPosixFullPath
log ocidPosixPathURL as text
log className() of ocidPosixPathURL as text

-->(*NSURL*)


set ocidXMLdata to objNSData's dataWithContentsOfURL:ocidPosixPathURL
log ocidXMLdata as list
log className() of ocidXMLdata as text
-->(*NSConcreteData*)


set {ocidXMLdata, ocidErrorRef} to objNSXMLDocument's alloc()'s initWithData:ocidXMLdata options:(objNSXMLNodePreserveWhitespace) |error|:(reference)
log ocidXMLdata as list
log className() of ocidXMLdata as text
-->(*NSXMLDocument*)

set ocidRootElement to ocidXMLdata's rootElement()
log ocidRootElement as list
log className() of ocidRootElement as text
-->(*NSXMLFidelityElement*)
log "###ここから要素"
repeat with objElement in ocidRootElement's children()
log "Name:" & objElement's |name|() as text
log "Value:" & objElement's stringValue() as text
log className() of objElement as text
###子要素
log objElement's children() as list

end repeat




ocidXMLdata's release()


display notification "処理終了" with title "処理が終了" subtitle "処理が終了しました" sound name "Sonumi"
log ">>>>>>>>>>>>処理終了<<<<<<<<<<<<<<<"
return ">>>>>>>>>>>>処理終了<<<<<<<<<<<<<<<"




#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat

end doLogView
#########################

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat AddOn Acrobat Annotation Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat python Acrobat Reader Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Adobe Adobe FDKO Adobe RemoteUpdateManager AppKit Apple AppleScript AppleScript do shell script AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript System Events AppleScript System Events Plist AppleScript Video Applications AppStore Archive Attributes Automator BackUp Barcode Barcode QR Barcode QR Decode Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome CIImage CityCode CloudStorage Color com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Device Diff Disk Dock DropBox Droplet eMail Encode % Encode Decode Encode UTF8 Error EXIFData ffmpeg File Finder Firefox Folder FolderAction Fonts GIF github Guide HTML HTML Entity Icon Illustrator Image Events Image2PDF ImageOptim iPhone iWork Javascript Jedit Json Label Leading Zero List locationd LRC lsappinfo LSSharedFileList m3u8 Mail MakePDF Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Mouse Music NetWork Notes NSArray NSArray Sort NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSColor NSColorList NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSPrintOperation NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth OneDrive PDF PDFAnnotation PDFAnnotationWidget PDFContext PDFDisplayBox PDFDocumentPermissions PDFImageRep PDFKit PDFnUP PDFOutline perl Photoshop PlistBuddy pluginkit postalcode PostScript prefPane Preview Python QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver SF Symbols character id SF Symbols Entity sips Skype Slack Sound Spotlight sqlite SRT StandardAdditions Swift System Settings TCC TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code Wacom webarchive webp Wifi Windows XML XML EPUB XML OPML XML Plist XML RSS XML savedSearch XML SVG XML TTML XML webloc XML XMP YouTube zoom