NSData returns <> - ios

I am converting url data into UIImage. This is my code.
NSURL *url = [NSURL URLWithString:strImgURL];
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
NSLog(#"Image Error-------%#",[error localizedDescription]);
imgProf = [[UIImage alloc] initWithData:data];
but My data always returns <>
(lldb) po data
<>
But when I type this url in browser I can get the image. What is the reason for this?
Please help me. Thanks

You're getting an empty response because your code (app) can't authenticate with the server by the sounds of it. This should generally be returned as an error but it depends on the response from the server.
You need to deal with the authentication first, so the app has an auth token or cookie or something and then you can make your request (potentially supplying the auth details in headers).

Related

make response Url Valid Ios

I am developing ios application where I am waiting for response which should be uploaded image Url. I am converting NSData to NSString this way.
NSString* resultInString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
when I log resultInString, I get __NSCFString * #"\"http:\/\/em.avatars.s3.amazonaws.com\/avatarsd765c404-887c-4c0e-a08b-f7066ec9befe.png\"" 0x17777080
I have no idea how to validate this url to set UIImageview in my application. please give me a hint.
before say something about solution i think your getting url from NSData is incorrect.
The response seems to be JSON-encoded. So simply decode the response string using a JSON library (SBJson, JsonKit etc.)
or you can user correct encode for your NSData.
after all you can create a NSUrl from your string & if it's exist so it's valid.
i write a sample code for you
you should remove some charectar from your url by this way or like this
[urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
and for validation
NSUrl * url = [[NSURL alloc] initWithString:urlString];
if(url){ //valid url
}

NSData dataWithContentsOfUrl: loads outdated data

In my app I load some static JSON string from some server.
Every now and then the JSON file is updated and then I want the app to reload the data.
Now, that I updated the file on the server the app does not reflect the change. If I take the URL to that file from the app's code and copy it into a browser and fetch the file there, I clearly see the updates. But when I run the app and log the json string to the debug console, then I clearly see an outdated version of the file's content.
Is there any caching involved? Can I force the iOS to actually reload it?
This is how I load it now:
NSURL * url = [NSURL URLWithString:[DOWNLOAD_URL stringByAppendingString:DOWNLOAD_FILE]];
NSError * error;
NSData *jsonData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
NSLog(#"JSON: %#", [NSString stringWithUTF8String:[jsonData bytes]]);
The option NSDataReadingUncached should prevent the system from caching the data.
PS: When I run the app on a different device, then it receives the current data. But when I again let it run on the original device - on which I observe this behaviour - then the data "received" is still outdated. So it really looks like some cashing issue to me.
Here is an idea. Try calling
[[NSURLCache sharedURLCache] removeAllCachedResponses];
For more granular control on cashing use NSURLConnection or NSURLSession.
I did try Mundi's suggestion, to try clearing the cache, but this didn't make any difference in my iPhone app.
So, I tried a trick which I use in my Angular webapps, and appended the current time (in ticks) to the URL I'm attempting to open, and that did work:
NSString* originalURL = #"http://somewebservices/data/1234";
NSString* newURL = [NSString stringWithFormat:#"%#?t=%f", originalURL,
[[NSDate date] timeIntervalSince1970]];
NSLog(#"Loading data from: '%#'", newURL);
NSURL *url = [NSURL URLWithString:newURL];
if (url == nil)
return false;
NSError *error;
NSData* urlData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
(Sigh.)
I'm getting too old for this stuff....

+[NSURL URLWithString:] returning nil

I use this code to load a UIImage from a URL:
NSURL *imageURL = [NSURL URLWithString:#"http://testwebsite.com/image.png"];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
imageView.image = [UIImage imageWithData: imageData];
but I'm stuck at a URL that looks like this one :
http://www.testwebsite.com/getFile?userID=123
this works fine in the browser but returns nil in the imageData variable above.
how can I load the image from such an obscured URL (i.e. from a URL that does not show off the file name but rather redirects to the image file) ?
thank you in advance.
for some weird reason I have to use :
[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
when I create the URL and this solved the issue.
NSData initWithContentsOfURL: returns nil if the data cannot be loaded (i.e. if you get a HTTP error code).
Chances are the URL you point to has some referrer blocker or cookie requirement that prevents its use from within your app (just one suggestion of the problem).
I recommend you look at using the following variant instead:
- (id)initWithContentsOfURL:(NSURL *)aURL options:(NSDataReadingOptions)mask error:(NSError **)errorPtr
And pay attention to the value of errorPtr in case the return value is nil.
For example:
NSError *error;
NSData* imageData = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://example.com/notfound"]
options:0 error:&error];
if(imageData == nil) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Got %u bytes", imageData.length);
}
You can see the following error:
Error: Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0xa881c20 {NSURL=http://example.com/notfound}
If you load the image like that it's blocking the main thread and leaving your application unresponsive and I'm not sure if the initWithContentsOfURL: method is handling redirects at all if that is the issue... You can create another class (ImageFetcher for example) that uses NSURLConnection and implements the NSURLConnectionDataDelegate. Using the connection:willSendRequest:redirectResponse: method from the NSURLConnectionDataDelegate you can handle redirects and in the connection:didReceiveData: method you can append the received data to a NSMutableData (it's not guaranteed that you receive all the data in one go). Furthermore you don't have to wait for the connection to finish or download any data if you implement the connection:didReceiveResponse: method and check if the response is indicating an error and in the connectionDidFinishLoading: method you can call another method to update your image view (or call the delegate of the ImageFetcher class with the appropriate data to update the image view).
NSURL URLWithString:#"" will return nil if the URL does not conform to RFC 2396 and they must be escaped
If you read through rfc2396 in the link you will get loads of details
A great site I found for checking where the offending character is, choose the path option for URL
http://www.websitedev.de/temp/rfc2396-check.html.gz

NSMutableURLRequest and JSON - How would I finish this connection?

I am trying to fetch data from an api and I have this code:
// create the URL we'd like to query
NSString *urlString = [NSString stringWithFormat:#"https://www.googleapis.com/adsense/v1.1/reports"];
NSString *token = auth.accessToken;
NSMutableURLRequest *myURL = [NSURL URLWithString:urlString];
[myURL addValue:token forHTTPHeaderField:#"Authentication"];
// we'll receive raw data so we'll create an NSData Object with it
######
How would I complete this step? So far I have
NSData *myData =
######
// now we'll parse our data using NSJSONSerialization
id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
// typecast an array and list its contents
NSArray *jsonArray = (NSArray *)myJSON;
NSLog(#"%#", jsonArray);
How would I connect on the 9th line?
It looks like you are putting all this code in one place (making a synchronous network request). This is typically a bad idea. You should put the first part (creating and starting the request) in one place, and put the parsing code in a separate method / block that gets called once the request is completed. (This is called an asynchronous network request.)
You should take a look at +[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]. You can pass your NSURLRequest in here, and then specify the completion (parsing, etc.) in the completion handler. It will give you the NSData object you're looking for - see documentation here.
If you have more than a handful of network connections, this can get unwieldy. You may want to look at a third party library like AFNetworking, which can manage much of the tedious stuff for you, and let you focus on calling a URL, and parsing the response.
You need:
NSData *myData = [NSURLConnection sendSynchronousRequest:myURL returningResponse:nil error:nil];
This is a synchronous call. I'll suggest always using asynchronous webcalls is a good way.

How to turn image data in JSON from WCF Data Services into UIImage in iOS

How do I get image data out of JSON returned by a WCF Data Service?
I've got a WCF Data Service serving some objects that include some binary data that is an image (column type in SQL Server is image). It comes across as text gibberish in the JSON. In the iOS client I'm writing for this service, I want to display this data as an image ([UIImage imageWitData:myData]).
Here is what I'm doing:
NSData *networkData = nil; //assume this magically gets data from the service
NSError *err = nil;
//assume the returned JSON has one object and is not an array
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:networkData
options:NSJSONReadingAllowFragments error:&err];
//handle error if needed
NSString *imageString = [dict objectForKey:#"Image"];
NSData *imageData = [imageString dataUsingEncoding:NSUTF8StringEncoding];
///The service is using UTF-8.
UIImage *image = [UIImage imageWithData:imageData];
Putting that image in a UIImageView doesn't show anything. What am I doing wrong?
Turns out that binary data returned from WCF Data Services is base64 encoded. I'm using the NSData-Base64 category to parse it, and it's working great. So the solution looks like this:
NSData imageData = [NSData dataFromBase64String:imageString];
When I imported those files into my project ARC threw up some errors, but I was able to solve them by removing a couple of autorelease calls in the .m file.

Resources