开发者

Can't get Images from the iPhone device folder

I'm trying to get some images from the device (iPhone) and show them on screen.

The image files are saved on my device and separated in folders like this: (...)/Documents/1/image1.png.

Here is the code of the function where I'm trying to get the image

-(UIImage *) getImageFromDevice:(NSString *) fileName 
                        idImage:(int)        idImage{

    NSString *path;

    path = [[self dataFilePath] stringByAppendingString:@"/"];
    path = [path stringByAppendingString: [[NSString alloc] initWithFormat:@"%d",idImage]];
    path = [path stringByAppendingString:@"/"];
    path = [path stringByAppendingString:fileName];

    NSLog(@"path = %@", path);

    NSURL *deviceImage开发者_如何学JAVAUrl = [[NSURL alloc] initWithString:path];
    NSData *imageData = [NSData dataWithContentsOfURL:deviceImageUrl];
    UIImage *deviceImage = [UIImage imageWithData:imageData];

    return deviceImage;

}

And this is the function to get the path to the device folder that's working fine:

-(NSString *)dataFilePath{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    return documentsDirectory;

}

But when I set the NSURL *deviceImageUrl with [[NSURL alloc] initWithString:path] the deviceImageUrl becomes nil.

What I'm doing wrong?


//NSURL *deviceImageUrl = [[NSURL alloc] initWithString:path];
//NSData *imageData = [NSData dataWithContentsOfURL:deviceImageUrl];
//UIImage *deviceImage = [UIImage imageWithData:imageData];    
UIImage *deviceImage = [[[UIImage alloc] initWithContentsOfFile:path]autorelease];


Try using fileURLWithPath: instead of URLWithString: ;)

NSURL *deviceImageUrl = [NSURL fileURLWithPath:path]; // autoreleased url

I always mess up with these two methods, too ... they're making me crazy.


You should not use initWithString: , this must conform to URL format as described in RFCs. If you just want to use a system path, use this : (don't forget to release after use it)

NSURL *deviceImageUrl = [[NSURL alloc] initFileURLWithPath:path isDirectory:NO];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜