I need to run the following command from an OSX app:
dscl . -read /Users/user JPEGPhoto | tail -1 | xxd -r -p > /Users/user/Desktop/user.jpg
Ive tried several things such as:
func runScript(launchPath:String, scriptName:String) {
let task = NSTask()
task.launchPath = launchPath
task.arguments = NSArray(objects: scriptName)
let pipe = NSPipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)
}
and
func runCommand(command: String) -> (output: String, exitStatus: Int) {
let tokens = command.componentsSeparatedByString(" ")
let launchPath = tokens[0]
let arguments = tokens[1..<tokens.count]
let task = NSTask()
task.launchPath = launchPath
task.arguments = Array(arguments)
let stdout = NSPipe()
task.standardOutput = stdout
task.launch()
task.waitUntilExit()
let outData = stdout.fileHandleForReading.readDataToEndOfFile()
let outStr = NSString(data: outData, encoding: NSUTF8StringEncoding)
return (outStr, Int(task.terminationStatus))
}
The problem is that these methods execute one command per call, so I would have to call them three times (dscl/tail/xxd) which doesn't work.
When I tried them separately in terminal, it didn't work either.
Any suggestions? Thanks
UPDATE:
After following Ken Thomases' great advice, this is what it looks like in swift:
import Collaboration
func saveUserPicture() {
var userImage:NSImage = CBUserIdentity(posixUID: getuid(), authority: CBIdentityAuthority.defaultIdentityAuthority()).image() as NSImage
var userImageData:NSData = NSBitmapImageRep.representationOfImageRepsInArray(userImage.representations, usingType: NSBitmapImageFileType.NSJPEGFileType, properties: nil )
userImageData.writeToFile("/Users/user/Desktop/file.jpg", atomically: true)
}