Reputation: 376
I need to Read a Image from the specific URL .
It works fine with WWW . but it returns a nil when the URL pointing the Local Folder .
// Works
NSString *sampleData = @"http://blogs-images.forbes.com/ericsavitz/files/2011/05/apple-logo2.jpg";
// Returns nil
NSString *sampleData = @"USER/user2/...";
Note : I am changing the NSString to NSURL and creating the UIImage .
NSURL *url = [NSURL URLWithString: data];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
Upvotes: 5
Views: 11568
Reputation: 957
Try these instead
NSString *path = @"USER/user2/.../xxx.xxx";
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isFileExist = [fileManager fileExistsAtPath:path];
UIImage *image;
if (isFileExist) {
image = [[UIImage alloc] initWithContentsOfFile:path];
}
else {
// do something.<br>
}
Upvotes: 0
Reputation: 876
You should do something like to get the local url :
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@", docDir, nameOfFile];
and finaly, load your image :
UIImage *image = [UIImage imageWithContentsOfFile:pngFilePath];
Upvotes: 0
Reputation: 2278
You are supplying a relative pathname for the file URL. That relative pathname is interpreted relative to the current working directory of the running application, which isn't guaranteed to be anything in particular, and so is almost certainly not what you want.
You can either supply an absolute path - one that starts with '/' - or set your app's current working directory to something explicit, like your user's Documents folder.
Upvotes: 1
Reputation: 5120
First of all, you can NOT read file from such path you given: "USER/user2/...", the file must in your App bundle or in your App's sandbox.
Second, check your path string if there was some texts need to be encoded in URL. Try:
NSURL *url = [NSURL URLWithString:[data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Also, if the url is not nil, you should also check if your [NSData dataWithContentsOfURL:url];
is returning nil. If so, it means your URL is not correct so the method cannot find your file.
P.S., You are mistyping your image create code, you should call alloc
before imageWithData:
.
Upvotes: 0
Reputation: 1813
you probably should have a look into the NSBundle Class. Methods like
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension subdirectory:(NSString *)subpath
or
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension
is probably what you want
Upvotes: 1