url nsdata not replacing local writetofile JSON - json

JSON web file is not overwriting and replacing the local JSON file on the App.
-(void)writeJsonToFile
{
NSURL *fileJSON = [[NSBundle mainBundle] URLForResource:#"data" withExtension:#"json"];
NSString *filePath = [NSString stringWithFormat:#"%#",fileJSON];
NSString *stringURL = #"website.com/data.json";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];
}
The destination for urlData and filePath files match each other.
Been looking around the site and other places online, made sure the file path matched.

We can never change the NSBundle file but
you can save in to local then try this
-(void)writeJsonToFile
{
NSString * filePath=[NSString stringWithFormat:#"%#/Documents/data.json",NSHomeDirectory()];
NSString *stringURL = #"website.com/data.json";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];
}
This code replacing local JSON file when call.
Your JSON file save in your application directory/Documents/ and file name is data.json
website.com/data.json do not return json data, please check it and if needed to change your URL.

Related

iOS Download html file from url

I need to download the html file from server url and replace to local html file. I'm using AFNetworking to download the file and store to Documents folder. It's downloading video & audio files. But when i try to download the html files i'm getting below error Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x83d0730 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"solarhtml"];
if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"text/html", nil];
[manager GET:#"http://server.net/projects/index.html"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[operation.responseData writeToFile:[dataPath stringByAppendingPathComponent:#"index.html"] atomically:YES];
NSLog(#"Successfully downloaded file to %#", [NSURL fileURLWithPath:dataPath]);
NSLog(#"THE RESPONSE: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error1) {
NSLog(#"%#", error1);
}];
Access html file:
-(void)estimatesavings:(id)sender{
if(updateclick==YES){
web_estimate=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024, 768)];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"index.html"];
NSURL *targetURL = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[web_estimate loadRequest:request];
web_estimate.delegate=self;
[self.view addSubview:web_estimate];
}else{
NSString *pathToBundle = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:pathToBundle];
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
//CGRect fullScreenRect=[[UIScreen mainScreen]applicationFrame];
web_estimate=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024, 768)];
[web_estimate loadHTMLString:htmlString baseURL:baseURL];
web_estimate.delegate=self;
[self.view addSubview:web_estimate];
}
}
ERROR:
copy failed: Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x83c8b50 {NSSourceFilePathErrorKey=/Users/ranganathagv/Library/Application Support/iPhone Simulator/6.1/Applications/CEDFEBEB-2A5C-40A9-8965-761689FD83C2/ActewAGL.app/index.html, NSUserStringVariant=(
Copy
), NSFilePath=/Users/ranganathagv/Library/Application Support/iPhone Simulator/6.1/Applications/CEDFEBEB-2A5C-40A9-8965-761689FD83C2/ActewAGL.app/index.html, NSDestinationFilePath=/Users/ranganathagv/Library/Application Support/iPhone Simulator/6.1/Applications/CEDFEBEB-2A5C-40A9-8965-761689FD83C2/Documents/solarhtml/index.html, NSUnderlyingError=0x83c89c0 "The operation couldn’t be completed. No such file or directory"}c
There were two problems:
The attempt to use AFJSONResponseSerializer and changing the acceptableContentTypes will not work, because the AFJSONResponseSerializer will accept the response, but will still try to parse the JSON. Instead, you should just use AFHTTPResponseSerializer instead. See https://stackoverflow.com/a/21621530/1271826 for more information.
The other problem rests in your open routine. Rather than just opening the file from the bundle, you should open the file in the Documents folder. You might even want to copy the file from the bundle to the Documents folder (in case it hasn't been downloaded yet).
For example:
NSString *documentsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *solarFolder = [documentsFolder stringByAppendingPathComponent:#"solarhtml"];
NSString *documentsPath = [solarFolder stringByAppendingPathComponent:#"index.html"];
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:documentsPath]) {
NSError *error;
if (![fileManager fileExistsAtPath:solarFolder]) {
if (![fileManager createDirectoryAtPath:solarFolder withIntermediateDirectories:YES attributes:nil error:&error]) {
NSLog(#"create folder failed: %#", error);
}
}
if (![fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&error]) {
NSLog(#"copy failed: %#", error);
}
}
NSString *htmlString = [NSString stringWithContentsOfFile:documentsPath encoding:NSUTF8StringEncoding error:nil];
web_estimate=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024, 768)];
[web_estimate loadHTMLString:htmlString baseURL:baseURL];
This way, if the file hasn't been downloaded at all, this will copy the file from the bundle before trying to open it, if necessary.

How to download html file from server (not local) in NSString

I have a html file on some server. The html file only contains text no photo's or anything else.
What I want to do is download the html file and put the text into a NSString.
Is this possible?
I found some code a few minutes ago:
NSURL *url = [NSURL URLWithString:#"http://www.example.com/file.html"];
NSString *text = [[NSString alloc] initWithContentsOfURL: url
encoding: NSUTF8StringEncoding
error: nil];
But did not work
Try this :
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval: 20];
NSError *requestError;
NSHTTPURLResponse *response = nil;
// Send request synchronously.
NSData *responseData = [NSURLConnection sendSynchronousRequest: request
returningResponse: &response
error: &requestError];
// Get the json string reponse.
NSString *stringResponse = [[NSString alloc]initWithData: responseData
encoding:NSUTF8StringEncoding];

XCode, iOS: Parsing HTML encoding with hpple

I have a problem with encoding when parsing web page with hpple in XCode.
- (void)loadTutorials {
NSURL *tutorialsUrl = [NSURL URLWithString:#"http://qrz.si/members/s55db/"];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl options:NSASCIIStringEncoding error:nil];
TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];
NSString *tutorialsXpathQueryString = #"//td[#class='data']";
NSArray *tutorialsNodes = [tutorialsParsersearchWithXPathQuery:tutorialsXpathQueryString];
NSMutableArray *newTutorials = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in tutorialsNodes) {
Tutorial *tutorial = [[Tutorial alloc] init];
[newTutorials addObject:tutorial];
for (TFHppleElement *child in element.children) {
if ([child.tagName isEqualToString:#"img"]) {
// NSLog([child objectForKey:#"src"]);
} else if ([child.tagName isEqualToString:#"p"]) {
//NSLog([[child firstChild] content]);
tutorial.title = [[child firstChild] content];
}
}
}
_objects = newTutorials;
[self.tableView reloadData];
}
Page should be UTF-8 as the source points out, but I get wierd characters out.
How can I force change encoding of the data? Any help would be highly appreciated!
options:NSASCIIStringEncoding
is useless here, documentation points out that it's not the right way to go.
To set encoding, one must edit XPathQuery.m by Matt Gallagher, that I got in the same tutorial. Changes were visible, but nothing worked, as the site was clearly UTF-8 encoded.
The problems were server side and administrator offered me good old plain XML :)
You are telling NSData object that the contents of the URL you are loading is ASCII not UTF8:
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl options:NSASCIIStringEncoding error:nil];
Which should be
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl options:NSUTF8StringEncoding error:nil];

How do I access a json file from a secure website in iOS5?

How do I access a json file from a secure website in iOS5? I'm parsing with NSJSONSerialization and this is what the method looks like:
- (void)parseJSON {
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:#"https//:username:password#www.mysecuresite.com"]];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *items = [json objectForKey:#"projects"];
[self setTableData:items];
}
Otherwise, accessing an unsecured website and returning the parsed json file is OK, just not over a secured site.

Three20 display local html file

I'm trying to display a local html file from a three20 table controller. The table shows up correctly, but when I select the item, all I get is a blank screen. If I use an external URL, the page shows correctly. I haven't tried using UIWebView, but I was wondering if there was an easy way using the Three20 framework.
Thanks.
EDIT: I forgot that has changed recently...
Assuming you have registered a TTWebController in your navigator that way :
TTNavigator* navigator = [TTNavigator navigator];
TTURLMap* map = navigator.URLMap;
[map from:#"*" toViewController:[TTWebController class]];
You can simply open a local html file that way :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
TTOpenURL([url description]);
Then all you have to to is to add TTTableLinkedItem or subclass (almost all of TT*Cell are) to your dataSource with a local file URL like that :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
TTTableTextItem *item = [TTTableTextItem itemWithText:#"foobar" URL:[url description]];
Much simpler that what I wrote before...
ENDOFEDIT
Forget whats under, unless you're interested in others solutions... (more complex... or not, see last one)
Basically here is how you load content in a UIWebView :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
The three20 TTWebController can take a request in a query :
- (id)initWithNavigatorURL:(NSURL*)URL query:(NSDictionary*)query {
if (self = [self initWithNibName:nil bundle:nil]) {
NSURLRequest* request = [query objectForKey:#"request"];
if (nil != request) {
[self openRequest:request];
} else {
[self openURL:URL];
}
}
return self;
}
So to open a local html file in a TTWebController you could do this :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[[TTNavigator navigator] openURLAction:
[[[TTURLAction actionWithURLPath:#"url://to/your/ttwebcontroller"]
applyQuery:[NSDictionary dictionaryWithObject:ulrRequest
forKey:#"request"]]
applyAnimated:YES]];
Now the last part, to trigger this from a TTTableViewController...
You have in your ViewController to implement :
- (void)didSelectObject:(id)object atIndexPath:(NSIndexPath*)indexPath {
// there you retrieve a *TTTableItem* corresponding to your row
// and call previous snippet from URL...
// TTTableItem class has userInfo property you could use:
TTTableItem *item = (TTTableItem *)object;
NSString *htmlFile = item.userInfo.
[self openLocalHtmlFile:htmlFile];
}
Hope that helps!
Nothing tested, at all, should not compile or whatsoever, but that is a solution.
That's a solution using basic three20 + iOS features. You could also write a TTCustomWebController inheriting from TTWebController that would take urls like #"myapp://openLocalHtml?file=credits" that's not that hard to do...
...That here is a draft :
#interface TTCustomWebController : TTWebController {}
#end
#implementation TTCustomWebController
- (id)initWithFile:(NSString *)name {
self = [super init];
if (self) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:name ofType:#"html"];
NSURL *URL = [NSURL fileURLWithPath:filePath];
[self openURL:URL];
}
return self;
}
#end
Then you could simply use TTTableLinkedItem in your datasource pointing to these #"myapp://openLocalHtml?file=credits"...
Good luck! :)