NSData dataWithContentsOfUrl: loads outdated data - ios

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....

Related

NSData returns <>

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).

NSURLCache not working after iOS app termination

I am building an app in which I am implementing offline mode as well. For this I used NSURLCache mechanism. When the app is in foreground then the cache mechanism works perfectly even if the device goes in offline mode. The problem comes when I quit the app and then open it in offline mode. This time NSCachedURLResponse is returning nil for the particular request.
Below is the code I am using for this:
Custom Cache Creation:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURLCache *urlCache = [[NSURLCache alloc] initWithMemoryCapacity:1024*1024 diskCapacity:1024*1024*5 diskPath:nil];
[NSURLCache setSharedURLCache:urlCache];
}
Calling server and cached object:
-(void)serverCall
{
NSURLCache *urlCache = [NSURLCache sharedURLCache];
NSString *urlString = nil;
NSHTTPURLResponse *response = nil;
NSError *error = nil;
urlString = [NSString stringWithFormat:#"%#%#",BASE_URL,url];
urlString = [urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSURL *finalUrl = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalUrl];
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
NSData *data = nil;
if ([self checkInternetConnection])
{
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:data];
[urlCache storeCachedResponse:cachedResponse forRequest:request];
}
else
{
NSCachedURLResponse *cachedResponse = [urlCache cachedResponseForRequest:request];
response = cachedResponse.response;
data = cachedResponse.data;
}
}
I can see that caches.db in library path of application the response is saved. But when i am trying to read it in Offline mode (after app is killed from background), the cached response is coming nil. I have gone through following links (and many more) but couldn't find the solution of my problem.
NSURLCache Problem with cache response
How to use NSURLCache to return cached API responses when offline (iOS App)
http://twobitlabs.com/2012/01/ios-ipad-iphone-nsurlcache-uiwebview-memory-utilization/
http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/
Bypassing http response header Cache-Control: how to set cache expiration?
I have checked the http header fields and cached header in the api response and the problem is not from server end.
I have also tried providing a path in diskPath param while creating the custom cache but then it doesn't even load the cached object while the app is in foreground and internet disconnects. I have also changed the expiration date but the working is still same.
I have tried using SDURLCache but I am facing the similar problem. However I have successfully achieved this with ASIHTTPRequest but I don't want to use it as I have written all the server operations once already and I have to change every request with ASIHTTPRequest method.
Please help me find a solution for this.
Thanks in advance....

iOS NSURL queuing mechansim for multiple requests from file

I am very new to iOS development, but I would like to make an app that has two table view controllers (columns): both are a row of images that act as links. The first would be a column of YouTube videos and the second a column of websites. I would like to have all these listed in a file file.txt listed like so: V, http://youtube.com/example W, http://example.com
There would be a long list of those, the V meaning its a video (for the video column) and W for the websites. Now, I understand how to being the single file in, but what happens afterwards is my concern. Can I read each line into some sort of queue and then fire the NSURL request for each one consecutively? How can that be done with NSURL? Is there perhaps a better approach?
There are two questions for me:
Is a text file really the best format?
I might suggest a plist or archive (if the file is only going to exist only in your app's bundle and/or documents folder) or JSON (if it's going to live on a server before delivering it to the user) instead of a text file. It will make it easier to parse this file than a text file. For example, consider the following dictionary:
NSDictionary *dictionary = #{#"videos" : #[#"http://youtube.com/abc", #"http://vimeo.com/xyz"],
#"websites": #[#"http://apple.com", #"http://microsoft.com"]};
You can save that to a plist with:
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"files.plist"];
[dictionary writeToFile:plistPath atomically:YES];
You can add that file to your bundle or whatever, and then read it at a future date with:
dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
You can, alternatively, write that to a JSON file with:
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonPath = [documentsPath stringByAppendingPathComponent:#"files.json"];
[data writeToFile:jsonPath atomically:YES];
You can read that JSON file with:
data = [NSData dataWithContentsOfFile:jsonPath];
dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
Either way, you can get the list of videos or web sites like so:
NSArray *videos = dictionary[#"videos"];
NSArray *websites = dictionary[#"websites"];
Now that you have your arrays of videos and websites, the question then is how you then use those URLs.
You could do something like:
for (NSString *urlString in videos) {
NSURL *url = [NSURL URLWithString: urlString];
// now do something with the URL
}
The big question is what is the "do something" logic. Because you're dealing with a lot of URLs, you would want to use a NSOperation based solution, not a GCD solution, because NSOperationQueue lets you control the degree of concurrency. I'd suggest a NSOperation-based networking library like AFNetworking. For example, to download the HTML for your websites:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 4;
for (NSString *urlString in websites)
{
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// convert the `NSData` responseObject to a string, if you want
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// now do something with it, like saving it in a cache or persistent storage
// I'll just log it
NSLog(#"responseObject string = %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error = %#", error);
}];
[queue addOperation:operation];
}
Having said that, I'm not sure it makes sense to kick off a ton of network requests. Wouldn't you really prefer to wait until the user taps on one of those cells before retrieving it (and for example, then just open that URL in a UIWebView)? You don't want an app that unnecessarily chews up the user's data plan and battery retrieving stuff that they might not want to retrieve. (Apple has rejected apps that request too much data from a cellular connection.) Or, at the very least, if you want to retrieve stuff up front, only retrieve stuff as you need it (e.g. in cellForRowAtIndexPath), which will retrieve the visible rows, rather than the hundreds of rows that might be in your text/plist/json file.
Frankly, we need a clearer articulation of what you're trying to do, and we might be able to help you with more concise counsel.

Corrupted image when uploading in background

I'm developping a little image sharing app for my company. Everything works pretty fine except for one thing : when I upload an image to the server, and switch the app to background, a part of the image is corrupted (all gray).
It seems that the image data is sent correctly as long as the app is live. As soon as I switch to background, it sends nothing as it seems.
For the record, I use ASIHttpRequest, the shouldContinueWhenAppEntersBackground is set to YES and I'm running the app from iOS 4.3 to iOS 6.0. I'm using ARC.
I tried to "retain" (through a strong reference) both the image and the data, nothing there too.
Here are parts of the code :
The
Webservice that sends the image
- (void)sendImage:(UIImage*)image forEmail:(NSString*)email
{
NSString* uploadImage = [NSString stringWithFormat:[self completeUrlForService:SEND_PHOTO], email];
NSURL* url = [NSURL URLWithString:[uploadImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"uploadImage %#", uploadImage);
// setting that we will send a JSON object
[self setRequestType:WebServiceWrapperTypePOSTRequest];
// when posting a picture, it could take more time...
self.request.timeOutSeconds = 4*60;
[self.request setShouldContinueWhenAppEntersBackground:YES];
// setting up the POST data
[self addPostData:image forKey:#"fileContents"];
// start the request
[self startRequestForUrl:url userInfo:[NSDictionary dictionaryWithObject:SEND_PHOTO forKey:URL_KEY]];
}
the actual part of ASIHttpRequest class
self.request = [ASIHTTPRequest requestWithURL:url];
[self.request setShouldContinueWhenAppEntersBackground:YES];
NSString* key = [[self.postDictionnary allKeys] objectAtIndex:0];
UIImage* value = [self.postDictionnary valueForKey:key];
__strong NSData* data = UIImageJPEGRepresentation(value, 1.0);
if (!data) data = UIImagePNGRepresentation(value);
[self.request appendPostData:data];
[self.request setPostLength:data.length];
[self.request setUserInfo:userInfo];
[self.request setDelegate:self];
[self.request startAsynchronous];
If any of you guys has the tinyest idea, I'll take it!
Thanks.
Finally I decided to use a different library (MKNetworkKit) and instead of sending an UIImage, I save the image on disk to the tmp folder and send the file instead. When the download is complete, I just delete the image on disk. It worked liked a charm :)

Prevent an app crash due to a slow connection when retrieving a remote file

I am currently using a function in my app's didFinishLaunchingWithOptions that retrieves a file, saves it to the application directory.
I have found that when there is a weak connection the app will crash when this is happening. I read that there is a 20 second time limit Apple allows before crashing the app. Is this correct? If so, I believe this is causing my issue as the app works flawlessly with the exception of being on a very weak connection.
How could I modify my logic below to try and compensate for this?
- (void)writeJsonToFile
{
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = #"http://link-to-my-data.json";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//attempt to download live data
if (urlData)
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else
{
//file to write to
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
//file to copy from
NSString *json = [ [NSBundle mainBundle] pathForResource:#"data" ofType:#"json" inDirectory:#"html/data" ];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
It's a very bad idea to run this sort of thing on the main thread: I assume you are - basically, you'll block the entire UI while you wait for the network operation to complete.
dataWithContentsOfURL is not a good idea for this sort of thing. It will be much better to use NSURLConnection or one of the wrapper libraries like AFNetworking, because you can handle cases like when the connection times out gracefully.
These libraries also have built-in methods to asynchronously download the data, which prevents the main UI thread from being locked.
When is this downloaded data needed?
Depending on the answer, maybe you can call the method inside a thread. This will prevent the main thread from blocking.
Even if the data is needed from the beginning, you can just create a loader and download the file in the background, then make the app active after the file is downloaded.
I think to be more independent from internal implementation of NSData *urlData = [NSData dataWithContentsOfURL:url]; you should implement you own download class based on NSURLConnection.
The links to read:
URL Loading System Programming Guide
NSURLConnection Class Reference
NSURLConnectionDelegate Protocol Reference
So you can catch all connection errors by your code and implement right behavior in this case.

Resources