简体   繁体   中英

Get user name in RubyMotion OSX

I need to get the user's home directory or at least his name.

Using FileUtils , I need to move files based on their account name, and using ~/ doesn't seem to work.

How would I get the user's account name?

I am not a rubymotion user yet, but in most rubies you can do

ENV["HOME"]

for the home directory and

ENV["USER"]

for the user to achieve exactly that using defined environment variables.

To get to the document's path and create a new folder in OSX you could do.

directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true).first
directory = directory.stringByAppendingPathComponent("Sub Folder")

fileManager = NSFileManager.defaultManager

fileExists = fileManager.fileExistsAtPath(directory)
if (fileExists)
  NSLog("Folder already exists")
else
  if(!fileManager.createDirectoryAtPath(directory, withIntermediateDirectories:true, attributes: nil, error: nil))
    NSLog("Failed to create folder")
  else
    NSLog("Successfully created folder")
  end
end

If all you want is the user account's name you can use NSHost


For the home directory you could use NSHomeDirectory instead.

fm = NSFileManager.defaultManager
directory = NSSearchPathForDirectoriesInDomains(NSHomeDirectory, NSUserDomainMask, true).first
fm.contentsOfDirectoryAtPath(directory, error: nil).each do |file|
  puts file # outputs each file under the home directory
  // Copy file here using NSFileManager
end

You can then use NSFileManager's copyItemAtPath


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM