开发者

Can not save data in subdirectory of Documents iPhone

开发者 https://www.devze.com 2023-03-14 07:10 出处:网络
I want to create a subdirectory (Document/MyFolder) in iphone. I can create subdirectory but can not save data in subdirectory. Here is my code

I want to create a subdirectory (Document/MyFolder) in iphone. I can create subdirectory but can not save data in subdirectory. Here is my code

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"YYYYMMDD_HHMMSS"];

 NSDate *date = [[NSDate alloc] init];

 NSString *currentDate = [dateFormat stringFromDate:date];

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

 NSString *documentsDirectory = [paths objectAtIndex:0];

 NSString *tileImageName = [NSString stringWithFormat:@"%@%@",currentDate,@".png"];

 NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

 if (![[NSFileManager defaultManager] fi开发者_JAVA百科leExistsAtPath:dataPath]){

 [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; 

 }

 NSData* data = UIImagePNGRepresentation(tileImage);

 [data writeToFile:dataPath atomically:YES];

 [dateFormat release];

 [date release];

How can save data in this subdirectory?

Also I need to delete this folder when user clicks button. How can I delete this subdirectory (in this case MyFolder)?

Thanks.


Your dataPath doesn't include tileImageName. You should define a tileImagePath to include the tileImageName. It should probably be,

 NSString * tileImageName = [NSString stringWithFormat:@"%@%@",currentDate,@".png"];
 NSString * dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];
 NSString * tileImagePath = [dataPath stringByAppendingPathComponent:tileImageName];

 if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
     [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; 
 }

 NSData * data = UIImagePNGRepresentation(tileImage);    
 [data writeToFile:tileImagePath atomically:YES];

So your dataPath is something like ../Documents/MyFolder and not ../Documents/MyFolder/20110622_011700.png as you intended.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号