iOS: NSString loses URL, (null) is shown - ios

This is my Code so far:
NSString *listedImageURL = listedProduct.image;
NSLog(#"URL: %#", listedImageURL);
This Code works fine and NSLog shows me the correct URL. But when I try the following Code, NSLog shows up (null):
NSString *listedImageURL = listedProduct.image;
NSURL *imageURL = [NSURL URLWithString:listedImageURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
What am I doing wrong??

I believe that relower is on the right track, the documentation states:
This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘#’. Note that ‘%’ escapes are translated via UTF-8.
I believe that it would be helpful to identify which characters might be causing an issue for you if you were to post some examples of the URLs that you are converting.
I would suggest logging: listedImageURL
and then also running:
NSString *escapedImageUrl = [listedProduct.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
then log that.
That should let you see what is being escaped and what is being missed. It can be something as simple as a stray space.
You could also try using NSASCIIStringEncoding instead of NSUTF8StringEncoding and see if that makes a difference.

it can be null, because of your string to url convertion.
Try this code below;
NSString *listedImageURL = [listedProduct.image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *imageURL = [NSURL URLWithString:listedImageURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
will work for you i think. good luck.

Related

NSMutableArray to NSString to UIImageView CODE CRASHES

Any idea why my code would crash? I am taking an NSMutableArray converting it to an NSString and using the string to get the URL for my UIImageView. Crashes at NSURL Line.
NSString *imgstring = [imageOne componentsJoinedByString:#""];
NSURL *imageURL = [NSURL URLWithString:imgstring];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
self.imageview.image = [UIImage imageWithData:imageData];
});
});
From the Apple Documentation,
URLString: The URL string with which to initialize the NSURL object. Must be a URL that conforms to RFC 2396. This method parses URLString according to RFCs 1738 and 1808.
In OS X v10.7 and later or iOS 5 and later, this method returns nil if the URL string is nil. In earlier versions, this method throws an exception if the URL string is nil.

Converting from JSON string to UIImage always gives null?

I Get this kind of JSON:
NOTE: I put dots in "content" because it is too long byte array abd just to explain the situation.
{
"id":"53abc6a7975a9c10c292f670",
"nfcId":"testse",
"company":"TESt",
"qrId":"testvalue",
"address":"ajs;ldfh",
"mimeType":"IMAGE",
"url":"",
"content":"iVBORw0KGgoAAAANSUhEUgAA....."
}
And im trying to get this Json and diplay this information
the "content" field has a Byte array converted on the server from Image to byte array.
I use this code in xCode to convert those bytes to NSData, then to UIImage to be able to display it in UIImageView:
NSData *dataImage = [jsonArray[key] dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"data = %#", dataImage);
UIImage *img = [UIImage imageWithData:dataImage];
NSLog(#"img = %#", img);
The image is always gives me null.Although, data give me array of data.
I tried all kinds of encodings as a NSData parameters also:
dataUsingEncoding:NSASCIIStringEncoding
dataUsingEncoding:NSUTF8StringEncoding
dataUsingEncoding:NSUTF16StringEncoding
dataUsingEncoding:NSUTF32StringEncoding
I've used code like this before
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"data:image/png;base64,%#",jsonArray[key]]];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:imageData];
Note that initWithBase64EncodedString is only available from iOS7 onwards
I tried this code just right now and it works:
NSData* dataImage = [[NSData alloc] initWithBase64EncodedString:jsonArray[key] options:0];
UIImage *img = [UIImage imageWithData:dataImage];
The "content" encoded by Base64 String type.

How to loop to retrieve images from web with NSData where an array holds url strings?

using URL in objective C is always misleading. Percent Encoding works in one situation and not in another. I just can't get why its so difficult to work with URL in objective C when other languages like C# never complain about such matters.
[NSData dataWithContentOfURL:] retrieves image if url is hard-coded, but not when it is provided from some variable that is retrieved at runtime. Percent Encoding is not working here. Whats the best way to handle URL in dynamic situation like this and others too?
NSString *logoString = [feeds[indexPath.row] objectForKey:#"logo"];
NSURL *logoURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#",logoString]];
NSData *logoData = [NSData dataWithContentsOfURL:logoURL];
UIImage *logoImage = [UIImage imageWithData:logoData];
imageView.image = logoImage;
percent encoding code:
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 );

NSUTF8StringEncoding gives me this %0A%20%20%20%20%22http://example.com/example.jpg%22%0A

I'm trying to load pictures from twitter. If i just use the URL in the json results without encoding, in the dataWithContentsOfURL, I get nil URL argument. If I encode it, I get as follow's
%0A%20%20%20%20%22http://example.com/example.jpg%22%0A.
I know I can use rangeOfString: or stringByReplacingOccurrencesOfString: but can I be sure that it will always be the same, is there another way to handle this, and why is this happening to my twitter response and not my instagram response?
I have also tried
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]
and it does nothing.
This is the URL directly from the json...
2013-11-08 22:09:31:812 JaVu[1839:1547] -[SingleEventTableViewController tableView:cellForRowAtIndexPath:] [Line 406] (
"http://pbs.twimg.com/media/BYWHiq1IYAAwSCR.jpg"
)
Here is my code
if ([post valueForKeyPath:#"entities.media.media_url"]) {
NSString *twitterString = [[NSString stringWithFormat:#"%#", [post valueForKeyPath:#"entities.media.media_url"]]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
twitterString = [twitterString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#", twitterString);
if (twitterString != nil){
NSURL *twitterPhotoUrl = [NSURL URLWithString:twitterString];
NSLog(#"%#", twitterPhotoUrl);
dispatch_queue_t queue = kBgQueue;
dispatch_async(queue, ^{
NSError *error;
NSData* data = [NSData dataWithContentsOfURL:twitterPhotoUrl options:NSDataReadingUncached error:&error];
UIImage *image = [UIImage imageWithData:data];
dispatch_sync(dispatch_get_main_queue(), ^{
[streamPhotoArray replaceObjectAtIndex:indexPath.row withObject:image];
cell.instagramPhoto.image = image;
});
});
}
}
The log output you show appears to be an array, since it has parentheses with the string on a separate line.
You shouldn't need to encode the string if it's already a valid URL string and in fact doing so is wrong and will break things.
%0A%20%20%20%20%22 stands for a \n followed by 4 spaces and then ". This is in accordance with the description in the console. Have you used NSJSONSerialization to obtain the URL from JSON data?
Not the answer rather a step in solving the error,: Change your code to this and post the output. Combining several method calls in one makes debugging harder.
NSLog(#"post: '%#", post);
NSString * twitterString;
twitterString = [post valueForKeyPath:#"entities.media.media_url"];
NSLog(#"twitterString 1: '%#", twitterString);
twitterString = [twitterString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"twitterString 2: '%#", twitterString);
twitterString = [twitterString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"twitterString 3: '%#", twitterString);
BTW, [NSString stringWithFormat:#"%#"... is not necessary.

How to disable or bypass escape sequence in iOS string for Base64 Image url data

I am receiving base64 strings from a json request from my server...
The base64 strings look like this:
"/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1J..." (well shortened)
Now my problem is that when I turn this from the NSString > NSURL, the backslashes escape from the string...
"/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1J"
i.e. "/" turns into just "/"
Now I'm pretty sure that this is the problem for my encoding to a UIImage problems (going through the following method: NSString -> NSURL -> NSData -> UIImage)
Code to create UIImage:
imageAllArray = [pathwayResults valueForKey:#"images_data_base64"];
NSURL *image2URL = [NSURL URLWithString:[imageAllArray objectAtIndex:1]];
NSData *image2Data = [NSData dataWithContentsOfURL:image2URL];
imageTwo = [UIImage imageWithData:image2Data];
Does anyone know a way to ensure that the backslashes stay within the string to convert?
Or is there another/easier way to go about this?
NSString *encodedString = [#"your string" stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I found that the backslashes weren't doing much harm at all and that it was because I forgot to prepend the string with: "data:image/png;base64,"
See below:
NSString *prepender = #"data:image/png;base64,";
NSString *image1String = [NSString stringWithFormat:#"%#%#", prepender, [pathwayImageArray objectAtIndex:0]];
NSURL *image1URL = [NSURL URLWithString:image1String];
NSData *image1Data = [NSData dataWithContentsOfURL:image1URL];
imageOne = [UIImage imageWithData:image1Data];
Hope this helps someone else!

Resources