Thursday, 15 July 2010

objective c - How to get a list of files in the directory os x? -



objective c - How to get a list of files in the directory os x? -

i'm developing application in objective-c. user selects directory (using nsopenpanel) , in application displays list of files in directory. working without problem.

however, if application open anew , without selecting directory through nsopenpanel, want list of files in selected directory in past startup error occurs

nscocoaerrordomain code = 257.

i suspect if user selects directory manually via nsopenpanel, scheme somehow remembers , give read access directory , getting files (using method contentsofdirectoryatpath), , if user not select via nsopenpanel directory , tries list of files error generated access.

how can in case?

if app sandboxed , want have access files/directories between runs, need store security-scoped bookmark directory, rather directory itself.

this means need add together boolean property com.apple.security.files.bookmarks.app-scope set yes entitlements of application, com.apple.security.files.user-selected.read-write allow file selection.

when select directory, need create bookmark it:

nsopenpanel *panel = [[nsopenpanel alloc] init]; panel.canchoosedirectories = yes; nsinteger ret = [panel runmodal]; if (ret == nsfilehandlingpanelokbutton) { nsurl *anurl = [[panel urls] lastobject]; nserror *err; nsdata *data = [anurl bookmarkdatawithoptions:nsurlbookmarkcreationwithsecurityscope includingresourcevaluesforkeys:nil relativetourl:nil error:&err]; if (!data) { nslog(@"%@", err); homecoming no; }

now you've got bookmark, need persist e.g. doing:

nsuserdefaults *def = [nsuserdefaults standarduserdefaults]; [def setobject:data forkey:@"bookmark"]; [def synchronize];

on restart of application, need convert bookmark nsdata url, done doing:

bool stale = no; nserror *anerror; nsurl *url = [nsurl urlbyresolvingbookmarkdata:data options:nsurlbookmarkresolutionwithsecurityscope relativetourl:nil bookmarkdataisstale:&stale error:&anerror]; if (url && !stale) { [anurl startaccessingsecurityscopedresource]; // url [anurl stopaccessingsecurityscopedresource]; } else if (anerror) { nslog(@"%@", anerror); homecoming no; }

and if had used defaults persistence of bookmark data, use:

nsuserdefaults *def = [nsuserdefaults standarduserdefaults]; nsdata *data = [def objectforkey:@"bookmark"];

to restore bookmark info userdefaults.

objective-c osx

No comments:

Post a Comment