How to access image from Asset URL in iPhone? - iphone

I am getting asset URL from NSURL* localUrl = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL]; and I saved it in a local database. And at the time of retrieving I have got an string and I have convert it into NSURL through NSURL *url1 = [NSURL URLWithString:image_path]; but when I get NSData from this URL through NSData *myData = [NSData dataWithContentsOfURL:url1]; it return NULL. Can anyone help me to get NSData and convert it into image.

You can not convert it direct. You will have to use ALAsset Block. Here is the complete description for same thing.
display image from URL retrieved from ALAsset in iPhone

Related

Creating a AVAsset with a HTTP NSURL

I'm trying to merge two NSURLs that contain video references. One of the urls point to a video on AWS and the other points to a video that is stored locally. My exporting code works because I've tried it with two local videos, but whenever I try merge the HTTP url and the local url I get this error: Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo=0x155d2f20 {NSUnderlyingError=0x155b4f60 "The operation couldn’t be completed. No such file or directory", NSLocalizedDescription=The requested URL was not found on this server.}
This is the code to create the AVAssets:
AVAsset *firstAsset = [AVAsset assetWithURL:awsURL];
Does AVAssetExportSession require local urls to be used?
#MichaelScaria, many thanks for posting what you figured out, i was on this for about 3 days. below is my solution in full when i was trying to get AVAssets from both local urls and remote urls
+ (AVAsset*)getAVAssetFromRemoteUrl:(NSURL*)url
{
if (!NSTemporaryDirectory())
{
// no tmp dir for the app (need to create one)
}
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:#"temp"] URLByAppendingPathExtension:#"mp4"];
NSLog(#"fileURL: %#", [fileURL path]);
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToURL:fileURL options:NSAtomicWrite error:nil];
AVAsset *asset = [AVAsset assetWithURL:fileURL];
return asset;
}
+ (AVAsset*)getAVAssetFromLocalUrl:(NSURL*)url
{
AVURLAsset *asset = [AVAsset assetWithURL:url];
return asset;
}
I saved the online url to a temporary directory and used the temporary url to merge the video and it worked.
NSData *urlData = [NSData dataWithContentsOfURL:initalURL];
[urlData writeToFile:path options:NSAtomicWrite error:nil]
Maybe you need to use AVURLAsset or other subclasses instead? From the docs:
You often instantiate an asset using AVURLAsset—a concrete subclass of AVAsset—with NSURLs that refer to audiovisual media resources, such as streams (including HTTP live streams), QuickTime movie files, MP3 files, and files of other types. You can also instantiate an asset using other concrete subclasses that extend the basic model for audiovisual media in useful ways, as AVComposition does for temporal editing.

Get image bytes

I am trying to load the bytes of an image like this:
NSURL *img = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"img" ofType:#"png"] isDirectory:NO];
NSString * test = [NSString stringWithContentsOfFile:[img absoluteString] encoding:NSASCIIStringEncoding error:&err];
But I always get following error:
Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn\u2019t be completed.
(Cocoa error 260.)" UserInfo=0xc02abf0
{NSFilePath=file://localhost/Users/admin/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/C55551DB-152A-43D6-A1E0-9845105709D6/myApp.app/img.png,
NSUnderlyingError=0xc02ccc0 "The operation couldn\u2019t be completed. Folder or file does not exist"}
However the file DOES exist, and if I copy/paste the NSFilePath into the browser it finds the image. What could be wrong?
Why not
NSString *path = [[NSBundle mainBundle] pathforResource:#"img" ofType:"png"];
NSData *data = [NSData dataWithContentsOfFile:path];
You can't just store random bytes in an NSString - it will try to convert them into a string and might fail. You need to use an NSData object for binary data.
You also don't need to use NSURLs at all; NSBundle will give you a path as a string.
As you are using the file URL, use [img path] instead of [img absoluteString] in the second line.
Or use [NSURL URLWithPath] in the first line.
Store bytes in NSData:
NSData *bytes = UIImagePNGRepresentation([UIImage imageNamed:#"myImage.png"]);
NSData* imageData = UIImagePNGRepresentation("imagename.."); //the image is converted to bytes

NSString to NSURL?

Trying to convert a string to NSURL and this is not happening.
barcodeTextLabel.text = foundCode.barcodeString;
urlToGrab = [NSString stringWithFormat:#"%#", foundCode.barcodeString]; // foundCode.barcodeString is an NSString
urlToGrab shows the following "error invalid CFStringRef"
This is how you create an NSURL from an NSString:
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
You can use following for creating the file path to url.
NSURL *yourURL = [NSURL fileURLWithPath:#"/Users/xyz/Desktop/abc.sqlite"];
If foundCode.barcodeString is the string you want as your URL, then (like the above answer) use the NSURL class method URLWithString:(NSString *).
Your code should look like:
NSURL urlToGrab = [NSURL URLWithString:foundCode.barcodeString];
Where is your error coming into to play? The way your code is, urlToGrab is an instance of NSString. I would imagine you would get an error like you described if you tried to make an HTTP request on an NSString rather than NSURL.
Swapnali patil's answer works, but I will add an explanation.
You will get a nil if the format of NSString doesn't fit file criteria for NSURL (file:///xxx/file.ext).
My needs were with loading a JPG image via URL file path to nsdata; NSURL * u=[[NSURL alloc] initWithString:fpath] returned nil, but NSURL *yourURL = [NSURL fileURLWithPath:fpath] as in mentioned answer worked. A URL for files will be file:///users/xxx/pic.jpg format and give disk access. NSURL * u=[[NSURL alloc] initWithString:(NSString*) ] will also give nil object if nsstring is web URL but if missing http://

problem while getting key value for url to data , then to uiimage

I have a URL with tag:
http://ws.cdyne.com/WeatherWS/Images/sunny.gif
When I do like this:
NSURL *url=[NSURL URLWithString:#"http://ws.cdyne.com/WeatherWS/Images/sunny.gif"];
it's getting image in gdb and I am able to download from this URL. But when I write code like this:
NSURL *url=[jsonItem objectForKey:#"PictureURL"];
(where jsonItem is dictionary and passing it to data and then to UIImage), then it shows an exception.
When I get the value of:
[jsonItem objectForKey:#"PictureURL"];
in gdb then it shows like:
2011-03-15 11:08:16.405 XML[1576:20b] jsonURKL ..... ...
http://ws.cdyne.com/WeatherWS/Images/thunderstorms.gif (in next line in gdb)
I need to download through this:
NSURL *url=[jsonItem objectForKey:#"PictureURL"];
I am not able to do that. What could be wrong?
Url itself one string.
so you have to use below code
NSURL *url=[NSURL URLWithString:[jsonItem objectForKey:#"PictureURL"]];
NSData *data = [NSData dataWithContentsOfURL: url];
now setimgge with [UIImage imageWithData: data]; this code
please do this in following way,
NSURL *url=[NSURL URLWithString:[jsonItem objectForKey:#"PictureURL"]];
NSData *data = [NSData dataWithContentsOfURL: url];
cell.iconImage.image=[UIImage imageWithData: data];

iPhone - NSData from local file's URL

I have a NSURL object which gives me the path of a local file (in documents folder). I want to populate an NSData object with the contents of this file. Tried using dataWithContentsOfURL: but this fails. I know the file exists because the iPhone SDK returns the path.
Can someone please tell me how I can get an NSData object from the URL of a local file?
Thanks.
// Given some file path URL: NSURL *pathURL
// Note: [pathURL isFileURL] must return YES
NSString *path = [pathURL path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
Swift code:
let data = FileManager.default.contents(atPath: path)
To get this work you just need to do:
NSURL *imgPath = [[NSBundle mainBundle] URLForResource:#"search" withExtension:#"png"];
NSString*stringPath = [imgPath absoluteString]; //this is correct
//you can again use it in NSURL eg if you have async loading images and your mechanism
//uses only url like mine (but sometimes i need local files to load)
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]];
UIImage *ready = [[[UIImage alloc] initWithData:data] autorelease];
Make sure your local URL starts with "file://"
then you would just have to do this:
NSData *fileData = [NSData dataWithContentsOfFile:fileURL.path];
For swift3 I found answer from following URL helpful
( I was getting following path , after capturing image using phonegap plugin
file:///var/mobile/Containers/Data/Application/B64B06DE-7976-45CF-9BE2-661F0F309A06/tmp/abcded.jpg )
https://stackoverflow.com/a/41043447/6383908
if let videoURL = URL(string: urlString), let videodata = try? Data(contentsOf: videoURL) {
//Add code of Alamofire here
}
guard let data = FileManager.default.contents(atPath: path) else
{ ...