I'm trying to get system GeneratedUID programmetically, i'm able to get the UID from command line using "dscl . -search /Users GeneratedUID 00052AE8-5000-6000-9007-666F6B666A66"
Can anyone help how to get this GeneratedUID programmetically?
This worked for me. It returns the first GeneratedUID that it finds for the current user, or nil if none are found.
There are lots of errors to handle, making the logic more complicated than it really should be.
-(NSString*) getGeneratedUID {
NSString* retval = nil;
ODSession *mySession = [ODSession defaultSession];
NSError *err;
ODNode *myNode = [ODNode nodeWithSession:mySession type:kODNodeTypeAuthentication error:&err];
NSString* username = NSUserName();
ODQuery *myQuery = [ODQuery queryWithNode: myNode
forRecordTypes: kODRecordTypeUsers
attribute: kODAttributeTypeRecordName
matchType: kODMatchEqualTo
queryValues: username
returnAttributes: kODAttributeTypeStandardOnly
maximumResults: 0
error: &err];
if (err) {
NSLog(#"Error creating current user query: %#", [err localizedDescription]);
}
else {
NSArray* queryResults = [myQuery resultsAllowingPartial:NO error:&err];
if (err) {
NSLog(#"Error executing current user query: %#", [err localizedDescription]);
}
else {
if ( [queryResults count] > 0 ) {
ODRecord* firstQueryResult = [queryResults objectAtIndex:0];
NSArray* uidValues = [firstQueryResult valuesForAttribute:#kDS1AttrGeneratedUID error:&err];
if (err) {
NSLog(#"Error getting GeneratedUID attribute for current user: %#", [err localizedDescription]);
}
else {
if ([uidValues count] > 0) {
retval = (NSString*) [uidValues objectAtIndex:0];
}
else {
NSLog(#"No GeneratedUID values for current username: %#", username);
}
}
}
else {
NSLog(#"No results from current user query for username: %#", username);
}
}
}
return retval;
}
just use the following code to retrive UID.... import the SecurityConfiguration.framework before you add the code..
NSString* GetConsoleUser(uid_t* p_uid, gid_t* p_gid) {
NSString* name = (NSString*)CFBridgingRelease(SCDynamicStoreCopyConsoleUser(
NULL, p_uid, p_gid));
return name ;
}
you have to play around the string to get the "UID".
Related
I added Realm pod to my tvos project. However it crash when I just try:
[RLMRealm defaultRealm]
It crash in simulator and device. I created a tvos empty project, added the Realms pod and it works. So I guess it's something related with the current project.
If the problem appear in the line 361 of RLMRealm file.
try {
realm->_realm = [self openSharedRealm:config error:error];
}
catch (SchemaMismatchException const& exception) {
if (configuration.deleteRealmIfMigrationNeeded) {
BOOL success = [[NSFileManager defaultManager] removeItemAtURL:configuration.fileURL error:nil];
if (success) {
realm->_realm = [self openSharedRealm:config error:error];
} else {
RLMSetErrorOrThrow(RLMMakeError(RLMException(exception)), error);
return nil;
}
} else {
RLMSetErrorOrThrow(RLMMakeError(RLMException(exception)), error);
return nil;
}
}
It executes RLMSetErrorOrThrow(RLMMakeError(RLMException(exception)), error); but the error is nil and it doesn't give me any extra information
I have a profile view controller where the user can set or change his or her profile picture but am getting constant errors that do not make sense to me.
-(void)getProfilePicture
{
PFUser *user = [PFUser currentUser];
NSLog(#"file--%#",[user objectForKey:PF_USER_PICTURE]);
userName = user[PF_USER_USERNAME];
status = user[PF_USER_STATUS];
if ([user objectForKey:PF_USER_PICTURE]) {
[imageUser setFile:[user objectForKey:PF_USER_PICTURE]];
[imageUser loadInBackground];
}
else{
imageUser.image = [UIImage imageNamed:#"blank_profile#2x.png"];
}
// fieldName.text = user[PF_USER_FULLNAME];
}
#pragma mark - UIActionSheetDelegate
I receive the following errors portrayed in my ProfileViewController.m (I can provide/add .h if needed):
"No visible #interface for 'UIImageView' declares the selector 'setFile:'
"No visible #interface for 'UIImageView' declares the selector 'loadInBackground'
Any help would be much appreciated or any supporting code thats needed, thanks.
Try this and see what it does for you:
-(void)getProfilePicture
{
PFUser *user = [PFUser currentUser];
NSLog(#"file--%#",[user objectForKey:PF_USER_PICTURE]);
userName = user[PF_USER_USERNAME];
status = user[PF_USER_STATUS];
if ([user objectForKey:PF_USER_PICTURE]) {
userImage.file = [user objectForKey:PF_USER_PICTURE];
[userImage loadInBackground:^(UIImage *image, NSError *error) {
if (!error) {
imageUser.image = image;
[imageUser setNeedsDisplay];
} else {
NSLog(#"%#", error);
}
}];
}
else{
imageUser.image = [UIImage imageNamed:#"blank_profile#2x.png"];
}
// fieldName.text = user[PF_USER_FULLNAME];
}
#pragma mark - UIActionSheetDelegate
This is assuming your userImage is a PFImageView and [user objectForKey:PF_USER_PICTURE] is a PFFile.
EDIT
Actually, looking at your error it seems that userImage is just a UIImageView not a PFImageView, which might be the source of all your problems. Try making the userImage a PFImageView
I've looked over the Security framework documentation but I can't seem to be able to find a way to get all of the certificates on a given keychain. Are there methods to accomplish this?
After mining the documentation, header files, and source files, I’ve come up with the following code:
#import <Security/Security.h>
- (void)logMessageForStatus:(OSStatus)status
functionName:(NSString *)functionName
{
CFStringRef errorMessage;
errorMessage = SecCopyErrorMessageString(status, NULL);
NSLog(#"error after %#: %#", functionName, (NSString *)errorMessage);
CFRelease(errorMessage);
}
- (void)listCertificates
{
OSStatus status;
SecKeychainSearchRef search = NULL;
// The first argument being NULL indicates the user's current keychain list
status = SecKeychainSearchCreateFromAttributes(NULL,
kSecCertificateItemClass, NULL, &search);
if (status != errSecSuccess) {
[self logMessageForStatus:status
functionName:#"SecKeychainSearchCreateFromAttributes()"];
return;
}
SecKeychainItemRef searchItem = NULL;
while (SecKeychainSearchCopyNext(search, &searchItem) != errSecItemNotFound) {
SecKeychainAttributeList attrList;
CSSM_DATA certData;
attrList.count = 0;
attrList.attr = NULL;
status = SecKeychainItemCopyContent(searchItem, NULL, &attrList,
(UInt32 *)(&certData.Length),
(void **)(&certData.Data));
if (status != errSecSuccess) {
[self logMessageForStatus:status
functionName:#"SecKeychainItemCopyContent()"];
CFRelease(searchItem);
continue;
}
// At this point you should have a valid CSSM_DATA structure
// representing the certificate
SecCertificateRef certificate;
status = SecCertificateCreateFromData(&certData, CSSM_CERT_X_509v3,
CSSM_CERT_ENCODING_BER, &certificate);
if (status != errSecSuccess) {
[self logMessageForStatus:status
functionName:#"SecCertificateCreateFromData()"];
SecKeychainItemFreeContent(&attrList, certData.Data);
CFRelease(searchItem);
continue;
}
// Do whatever you want to do with the certificate
// For instance, print its common name (if there's one)
CFStringRef commonName = NULL;
SecCertificateCopyCommonName(certificate, &commonName);
NSLog(#"common name = %#", (NSString *)commonName);
if (commonName) CFRelease(commonName);
SecKeychainItemFreeContent(&attrList, certData.Data);
CFRelease(searchItem);
}
CFRelease(search);
}
If you target Mac OS 10.6 or later, you can use SecItemCopyMatching to easily query the keychain:
SecKeychainRef keychain = ...
NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
kSecClassCertificate, kSecClass,
[NSArray arrayWithObject:(id)keychain], kSecMatchSearchList,
kCFBooleanTrue, kSecReturnRef,
kSecMatchLimitAll, kSecMatchLimit,
nil];
NSArray *items = nil;
OSStatus status = SecItemCopyMatching((CFDictionaryRef)query, (CFTypeRef *)&items);
if (status) {
if (status != errSecItemNotFound)
LKKCReportError(status, #"Can't search keychain");
return nil;
}
return [items autorelease]; // items contains all SecCertificateRefs in keychain
Note that you must not use this to implement certificate validation — the presence of a CA certificate in a keychain does not indicate that it is trusted to sign certificates for any particular policy. See the Certificate, Key, and Trust Programming Guide to learn how to do certificate validation with the Keychain.
http://developer.apple.com/library/mac/#documentation/Security/Conceptual/CertKeyTrustProgGuide/03tasks/tasks.html#//apple_ref/doc/uid/TP40001358-CH205-SW1
I need to access every file in a folder, including file that exist within nested folders. An example folder might look like this.
animals/
-k.txt
-d.jpg
cat/
-r.txt
-z.jpg
tiger/
-a.jpg
-p.pdf
dog/
-n.txt
-f.jpg
-p.pdf
Say that I wanted to run a process on every file within "animals" that isn't folder. What would be the best way to iterate through the folder "animals" and all of its subfolders to access every file?
Thanks.
Use NSDirectoryEnumerator to recursively enumerate files and directories under the directory you want, and ask it to tell you whether it is a file or directory. The following is based on the example listed at the documentation for -[NSFileManager enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:]:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *directoryURL = … // URL pointing to the directory you want to browse
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];
NSDirectoryEnumerator *enumerator = [fileManager
enumeratorAtURL:directoryURL
includingPropertiesForKeys:keys
options:0
errorHandler:^BOOL(NSURL *url, NSError *error) {
// Handle the error.
// Return YES if the enumeration should continue after the error.
return YES;
}];
for (NSURL *url in enumerator) {
NSError *error;
NSNumber *isDirectory = nil;
if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
// handle error
}
else if (! [isDirectory boolValue]) {
// No error and it’s not a directory; do something with the file
}
}
Maybe you can use something like this:
+(void)openEachFileAt:(NSString*)path
{
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
for (NSString * file in enumerator)
{
// check if it's a directory
BOOL isDirectory = NO;
NSString* fullPath = [path stringByAppendingPathComponent:file];
[[NSFileManager defaultManager] fileExistsAtPath:fullPath
isDirectory: &isDirectory];
if (!isDirectory)
{
// open your file (fullPath)…
}
else
{
[self openEachFileAt: fullPath];
}
}
}
Here is a swift version:
func openEachFile(inDirectory path: String) {
let subs = try! FileManager.default.subpathsOfDirectory(atPath: path)
let totalFiles = subs.count
print(totalFiles)
for sub in subs {
if sub.hasSuffix(".DS_Store") {
//a DS_Store file
}
else if sub.hasSuffix(".xcassets") {
//a xcassets file
}
else if (sub as NSString).substring(to: 4) == ".git" {
//a git file
}
else if sub.hasSuffix(".swift") {
//a swift file
}
else if sub.hasSuffix(".m") {
//a objc file
}
else if sub.hasSuffix(".h") {
//a header file
}
else {
// some other file
}
let fullPath = (path as NSString).appendingPathComponent(sub)
}
}
Here's a solution using -subpathsOfDirectoryAtPath:rootPath, with file URLs and modern Objective-C nullability bells & whistles.
typedef void (^FileEnumerationBlock)(NSURL *_Nonnull fileURL);
#interface NSFileManager (Extensions)
- (void)enumerateWithRootDirectoryURL:(nonnull NSURL *)rootURL
fileHandler:(FileEnumerationBlock _Nonnull)fileHandler
error:(NSError *_Nullable *_Nullable)error;
#end
#implementation NSFileManager (Extensions)
- (void)enumerateWithRootDirectoryURL:(NSURL *)rootURL
fileHandler:(FileEnumerationBlock)fileHandler
error:(NSError **)error {
NSString *rootPath = rootURL.path;
NSAssert(rootPath != nil, #"Invalid root URL %# (nil path)", rootURL);
NSArray *subs = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:rootPath
error:error];
if (!subs) {
return;
}
for (NSString *sub in subs) {
fileHandler([rootURL URLByAppendingPathComponent:sub]);
}
}
#end
… and the same in Swift:
func enumerate(rootDirectoryURL rootURL: NSURL, fileHandler:(URL:NSURL)->Void) throws {
guard let rootPath = rootURL.path else {
preconditionFailure("Invalid root URL: \(rootURL)")
}
let subs = try NSFileManager.defaultManager().subpathsOfDirectoryAtPath(rootPath)
for sub in subs {
fileHandler(URL: rootURL.URLByAppendingPathComponent(sub))
}
}
This code worked for me.
NSMutableString *allHash;
-(NSString*)getIterate:(NSString*)path {
allHash = [NSMutableString stringWithString:#""];
NSDirectoryEnumerator *de= [[NSFileManager defaultManager] enumeratorAtPath:path];
NSString *file;
BOOL isDirectory;
for(file in de)
{
//first check if it's a file
NSString* fullPath = [NSString stringWithFormat:#"%#/%#",path,file];
BOOL fileExistsAtPath = [[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDirectory];
NSLog(#"Check=>%d",fileExistsAtPath);
if (!isDirectory) //its a file
{
//Do with filepath
}
else{ //it's a folder, so recurse
[self enumerateFolder:fullPath];
}
}
return allHash;
}
-(void) enumerateFolder:(NSString*)fileName
{
NSDirectoryEnumerator *de= [[NSFileManager defaultManager] enumeratorAtPath:fileName];
NSString* file;
BOOL isDirectory;
for(file in de)
{
//first check if it's a file
BOOL fileExistsAtPath = [[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory];
if (fileExistsAtPath) {
if (!isDirectory) //its a file
{
//Do with file
}
else{ //it's a folder, so recurse
[self enumerateFolder:file];
}
}
else printf("\nenumeratefolder No file at path %s",[file UTF8String]);
}
}
In Swift we can try the following.
let docsDir = NSHomeDirectory().appending("/Documents")
let localFileManager = FileManager()
let dirEnum = localFileManager.enumerator(atPath: docsDir)
while let file = dirEnum?.nextObject() as? String {
if file.hasSuffix(".doc") {
print(docsDir.appending("/\(file)"))
}
}
Reference
https://developer.apple.com/documentation/foundation/filemanager/1408726-enumerator
How do you delete all the contents of a directory without deleting the directory itself? I want to basically empty a folder yet leave it (and the permissions) intact.
E.g. by using a directory enumerator:
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtPath:path];
NSString *file;
while (file = [enumerator nextObject]) {
NSError *error = nil;
BOOL result = [fileManager removeItemAtPath:[path stringByAppendingPathComponent:file] error:&error];
if (!result && error) {
NSLog(#"Error: %#", error);
}
}
Swift
let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtURL(cacheURL, includingPropertiesForKeys: nil, options: nil, errorHandler: nil)
while let file = enumerator?.nextObject() as? String {
fileManager.removeItemAtURL(cacheURL.URLByAppendingPathComponent(file), error: nil)
}
Try this:
NSFileManager *manager = [NSFileManager defaultManager];
NSString *dirToEmpty = ... //directory to empty
NSError *error = nil;
NSArray *files = [manager contentsOfDirectoryAtPath:dirToEmpty
error:&error];
if(error) {
//deal with error and bail.
}
for(NSString *file in files) {
[manager removeItemAtPath:[dirToEmpty stringByAppendingPathComponent:file]
error:&error];
if(error) {
//an error occurred...
}
}
in swift 2.0:
if let enumerator = NSFileManager.defaultManager().enumeratorAtPath(dataPath) {
while let fileName = enumerator.nextObject() as? String {
do {
try NSFileManager.defaultManager().removeItemAtPath("\(dataPath)\(fileName)")
}
catch let e as NSError {
print(e)
}
catch {
print("error")
}
}
}
Swift 2.1.1:
public func deleteContentsOfFolder()
{
// folderURL
if let folderURL = self.URL()
{
// enumerator
if let enumerator = NSFileManager.defaultManager().enumeratorAtURL(folderURL, includingPropertiesForKeys: nil, options: [], errorHandler: nil)
{
// item
while let item = enumerator.nextObject()
{
// itemURL
if let itemURL = item as? NSURL
{
do
{
try NSFileManager.defaultManager().removeItemAtURL(itemURL)
}
catch let error as NSError
{
print("JBSFile Exception: Could not delete item within folder. \(error)")
}
catch
{
print("JBSFile Exception: Could not delete item within folder.")
}
}
}
}
}
}
Swift 3 if anyone needs it for a quick cut/paste
let fileManager = FileManager.default
let fileUrls = fileManager.enumerator(at: folderUrl, includingPropertiesForKeys: nil)
while let fileUrl = fileUrls?.nextObject() {
do {
try fileManager.removeItem(at: fileUrl as! URL)
} catch {
print(error)
}
}
The documentation for contentsOfDirectoryAtPath:error: says:
The search is shallow and therefore does not return the contents of any subdirectories. This returned array does not contain strings for the current directory (“.”), parent directory (“..”), or resource forks (begin with “._”) and does not traverse symbolic links.
Thus:
---( file != #"." && file != #".." )---
is irrelevant.
You can extend the NSFileManager like this:
extension NSFileManager {
func clearFolderAtPath(path: String) -> Void {
for file in subpathsOfDirectoryAtPath(path, error: nil) as? [String] ?? [] {
self.removeItemAtPath(path.stringByAppendingPathComponent(file), error: nil)
}
}
}
Then, you can clear the folder like this: NSFileManager.defaultManager().clearFolderAtPath("the folder's path")
Georg Fritzsche answer for Swift did not work for me. Instead of reading the enumerated object as a String, read it as NSURL.
let fileManager = NSFileManager.defaultManager()
let url = NSURL(string: "foo/bar")
let enumerator = fileManager.enumeratorAtURL(url, includingPropertiesForKeys: nil, options: nil, errorHandler: nil)
while let file = enumerator?.nextObject() as? NSURL {
fileManager.removeItemAtURL(file, error: nil)
}
Why not deleting the whole directory and recreate afterwards? Just get the file attributes and permissions before deleting it, and then recreate it with the same attributes.