Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Save UIImage to Desktop on iOS Simulator
#if TARGET_IPHONE_SIMULATOR
@interface UIImage (RSSaveToDesktop)
/// Creates a RSUIImage directory on desktop and saves image to it.
-(void)rs_saveToDesktop;
/// Creates a RSUIImage directory on desktop and saves image to it with specified name.
-(void)rs_saveToDesktopWithName:(NSString *)customName;
@end
#endif
#if TARGET_IPHONE_SIMULATOR
#import <pwd.h>
static NSString *homeDirectory(){
NSString *logname = [NSString stringWithCString:getenv("LOGNAME")
encoding:NSUTF8StringEncoding];
struct passwd *pw = getpwnam([logname UTF8String]);
return pw
? [NSString stringWithCString:pw->pw_dir encoding:NSUTF8StringEncoding]
: [@"/Users" stringByAppendingPathComponent:logname];
}
static NSString *createDesktopDirectory(){
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *basePath = [NSString
stringWithFormat:@"%@/Desktop/RSUIImage",homeDirectory()];
NSUInteger n = 0;
while (1) {
++n;
NSString *path = n <=1
? basePath
: [NSString stringWithFormat:@"%@ %u",basePath,n];
BOOL isDirectory;
BOOL exists = [fileManager fileExistsAtPath:path
isDirectory:&isDirectory];
if (exists && isDirectory) return path;
if (!exists) {
NSError *error;
[fileManager createDirectoryAtPath:path
withIntermediateDirectories:NO
attributes:nil
error:&error];
NSCAssert(NULL == error, nil);
return path;
}
}
}
static NSString *snapshotPath(NSString *customName){
if (!customName) customName = @"image";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *directory = createDesktopDirectory();
NSString *basePath = [directory stringByAppendingFormat:@"/%@.png",customName];
NSUInteger n = 0;
while (1) {
++n;
NSString *path = n <=1
? basePath
: [directory stringByAppendingFormat:@"/%@ %u.png",customName,n];
BOOL exists = [fileManager fileExistsAtPath:path isDirectory:NULL];
if (!exists) return path;
}
}
@implementation UIImage (RSSaveToDesktop)
-(void)rs_saveToDesktop{
return [self rs_saveToDesktopWithName:nil];
}
-(void)rs_saveToDesktopWithName:(NSString *)customName{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSData *myImageData = UIImagePNGRepresentation(self);
[fileManager createFileAtPath:snapshotPath(customName)
contents:myImageData
attributes:nil];
}
@end
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment