iPhone将图像保存到文档目录

时间:2012-08-27 23:35:01

标签: iphone objective-c ios

我正在从用户的照片库中检索图像,并将该图像保存在文档目录中。我目前正在根据用户在文本字段中输入的内容命名图片。这是有效的,但文本字段对于图片来说并不是一个好名字。我想使用某种唯一标识符来命名图片。

有任何想法或建议吗?我只是不想在用户保存大量照片时发生冲突。

3 个答案:

答案 0 :(得分:3)

一种方法是使用UUID。这是一个例子:

// return a new autoreleased UUID string
- (NSString *)generateUuidString
{
  // create a new UUID which you own
  CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);

  // create a new CFStringRef (toll-free bridged to NSString)
  // that you own
  NSString *uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);

  // transfer ownership of the string
  // to the autorelease pool
  [uuidString autorelease];

  // release the UUID
  CFRelease(uuid);

  return uuidString;
}

或ARC版本:

// Create universally unique identifier (object)
CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);

// Get the string representation of CFUUID object.
NSString *uuidStr = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject);
CFRelease(uuidObject);

更简单的iOS6 +解决方案:

NSString *UUID = [[NSUUID UUID] UUIDString];

此处有更多信息:http://blog.ablepear.com/2010/09/creating-guid-or-uuid-in-objective-c.html和此处:http://en.wikipedia.org/wiki/Universally_unique_identifier

答案 1 :(得分:3)

昨天我必须通过一些变化来解决同样的问题:将图像保存在临时目录中,因为图片将被上传到Dropbox。

我所做的是获取自UNIX纪元以来重命名图像的秒数。

这是整个方法。您需要对其进行修改以满足您的需求,但您应该从中获得解决问题的基本要素:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *imageToUpload = [info objectForKey:UIImagePickerControllerOriginalImage];

    NSDate *dateForPictureName = [NSDate date];
    NSTimeInterval timeInterval = [dateForPictureName timeIntervalSince1970];
    NSMutableString *fileName = [NSMutableString stringWithFormat:@"%f", timeInterval];
    NSRange thePeriod = [fileName rangeOfString:@"."]; //Epoch returns with a period for some reason.
    [fileName deleteCharactersInRange:thePeriod];
    [fileName appendString:@".jpeg"];
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(imageToUpload, 1.0)];
    [imageData writeToFile:filePath atomically:YES];

    [[self restClient] uploadFile:fileName toPath:currentPath withParentRev:nil fromPath:filePath];

    [picker dismissModalViewControllerAnimated:YES];
}

答案 2 :(得分:0)

假设您的目标是用户输入的内容具有您想要附加到照片的某些含义,那么只需在标题末尾添加一个数字,直到找到有效的

例如

  

PicnicDay.jpg

     

PicnicDay 1.jpg

     

PicnicDay 2.jpg