reload a UIwebview from main view automatically (view based application) - iphone

I have a view based application. Now on the opening view I have some buttons and a picture and a small web view.
The web view has its own .h/.m file the calls a JSON request to fill it. That works great.
My problem is that when the app is closed and reopened the webview is not updating. How to I get that to work?
welcomeMessage.m (connected to webview)
- (void)awakeFromNib{
[NSThread sleepForTimeInterval:1];
NSUserDefaults *gMess =[NSUserDefaults standardUserDefaults];
NSString *myMess=[gMess stringForKey:#"welcomeMessage"];
NSLog(#"WEBVIEW CLASS %#",myMess);
if (myMess == NULL) {
NSString *html = [NSString stringWithFormat:#"<body style ='background-color:#FFFF33' align='center'><p>Welcome</p><p>Check out our Daily Winners</p></body>"];
[welcomeMessage loadHTMLString:html baseURL:[NSURL URLWithString:#"http://www.myapp.com/api/welcome/welcomemessage.php?iappid=37"]];
}
else{
NSString *html = [NSString stringWithFormat:#"<body style ='background-color:#FFFF33' align='center'> %# </body>", myMess];
[welcomeMessage loadHTMLString:html baseURL:[NSURL URLWithString:#"http://www.myapp.com/api/welcome/welcomemessage.php?iappid=37"]];
}
}
Mainviewcontroller json
- (void)viewDidLoad
{
// Create new SBJSON parser object
SBJsonParser *object = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.kickintheapp.com/api/welcome/welcomemessage.php?iappid=37"]];
// NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.json"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *jsonParseError;
NSDictionary *status = [object objectWithString:json_string error:&jsonParseError];
if (!status) {
// there's been a parse error; look at jsonParseError
// for example:
NSLog(#"JSON parse error: %#", jsonParseError);
}
NSString *messValue = [status objectForKey:#"message"];
NSUserDefaults *gMess = [NSUserDefaults standardUserDefaults];
[gMess setObject:messValue forKey:#"welcomeMessage"];
}

Check out Apple's documentation on an iOS's lifecycle. You will find all callbacks you need in there:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html
Especially – applicationWillEnterForeground: will be interesting for you.

Related

How to upload data from iphone app to mysql data base

I have a EMR app and i want that i may send the data which i have collected like images and voice to server. in data base so how can i do this . Is there any way to send these data to server through post method.
Here is an example of a HTTP Post request
// define your form fields here:
NSString *content = #"field1=42&field2=Hello";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.example.com/form.php"]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
Might want to reference http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSURLConnection_Class/Reference/Reference.html
This tutorial is also helpful http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service
In that case, you can do follow two ways:
1. if you strictly like to using POST (i like), u can using cocoahttpserver project:
https://github.com/robbiehanson/CocoaHTTPServer
In iphone app, you can do this code to send POST request:
-(NSDictionary *) getJSONAnswerForFunctionVersionTwo:(NSString *)function
withJSONRequest:(NSMutableDictionary *)request;
{
[self updateUIwithMessage:#"server download is started" withObjectID:nil withLatestMessage:NO error:NO];
NSDictionary *finalResultAlloc = [[NSMutableDictionary alloc] init];
#autoreleasepool {
NSError *error = nil;
NSString *jsonStringForReturn = [request JSONStringWithOptions:JKSerializeOptionNone serializeUnsupportedClassesUsingBlock:nil error:&error];
if (error) NSLog(#"CLIENT CONTROLLER: json decoding error:%# in function:%#",[error localizedDescription],function);
NSData *bodyData = [jsonStringForReturn dataUsingEncoding:NSUTF8StringEncoding];
NSData *dataForBody = [[[NSData alloc] initWithData:bodyData] autorelease];
//NSLog(#"CLIENT CONTROLLER: string lenght is:%# bytes",[NSNumber numberWithUnsignedInteger:[dataForBody length]]);
NSString *functionString = [NSString stringWithFormat:#"/%#",function];
NSURL *urlForRequest = [NSURL URLWithString:functionString relativeToURL:mainServer];
NSMutableURLRequest *requestToServer = [NSMutableURLRequest requestWithURL:urlForRequest];
[requestToServer setHTTPMethod:#"POST"];
[requestToServer setHTTPBody:dataForBody];
[requestToServer setTimeoutInterval:600];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[urlForRequest host]];
NSData *receivedResult = [NSURLConnection sendSynchronousRequest:requestToServer returningResponse:nil error:&error];
if (error) {
NSLog(#"CLIENT CONTROLLER: getJSON answer error download:%#",[error localizedDescription]);
[self updateUIwithMessage:[error localizedDescription] withObjectID:nil withLatestMessage:YES error:NO];
[finalResultAlloc release];
return nil;
}
NSString *answer = [[NSString alloc] initWithData:receivedResult encoding:NSUTF8StringEncoding];
JSONDecoder *jkitDecoder = [JSONDecoder decoder];
NSDictionary *finalResult = [jkitDecoder objectWithUTF8String:(const unsigned char *)[answer UTF8String] length:[answer length] error:&error];
[finalResultAlloc setValuesForKeysWithDictionary:finalResult];
[answer release];
[self updateUIwithMessage:#"server download is finished" withObjectID:nil withLatestMessage:NO error:NO];
if (error) NSLog(#"CLIENT CONTROLLER: getJSON answer failed to decode answer with error:%#",[error localizedDescription]);
}
NSDictionary *finalResultToReturn = [NSDictionary dictionaryWithDictionary:finalResultAlloc];
[finalResultAlloc release];
return finalResultToReturn;
}
Don't forget to pack attributes with images to base64.
Finally, if u don't like to keep data, which u send in you mac app, u can send to u database using any database C api. I recommend to using core data to save receive data.

Use of undeclared identifier in json for iOS

I am getting a use of undeclared identifier error in my json but I am following the example from http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
how do I fix this? Yes I am very new to objective-c \ ios :) Thanks
I am putting this code in my view based application in my viewcontroller.m file
The issue is with "SBJSON *parser = [[SBJSON alloc] init];"
// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.json"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey:#"text"], [[status objectForKey:#"user"] objectForKey:#"screen_name"]);
}
Try changing the line to SBJsonParser *parser = [[SBJsonParser alloc] init];
Edit:
A way that can be easier is to use the NSString category that SBJSON provides:
NSArray *statuses = (NSArray *)[json_string JSONValue];

xml parsering from webserver in iphone

To all
I am trying to parser the xml in my project But I have the code for xml parsing for locally I want the server base xml parsing how can i pass that
This is my xml parsing link i want to use:
http://www.google.com/ig/api?weather=,,,50500000,30500000
This my xml parsing for calling local file how can I call my webserver xml link for parsing.I need different-differnet type of calling xml link for parsing:
- (void)viewDidLoad
{
[super viewDidLoad];
_forecastInfo=nil;
currentcond=nil;
forecastcond=nil;
// Pass the NSData to the parser whether its from local file or its coming from web.... NSString *fileName=[[NSBundle mainBundle] pathForResource:#"weather" ofType:#"xml"];
NSData *data=[NSData dataWithContentsOfFile:fileName];
ForecastInfoParser *parser=[[ForecastInfoParser alloc]init];
parser.delegate=self;
[parser parseData:data];
}
NSURL *url = [[NSURL alloc] initWithString:#"hhttp://www.google.com/ig/api?weather=,,,50500000,30500000"];
NSData *data = [NSData dataWithContentsOfURL:url];
// 2 -- parsing
parser = [[MyParser alloc] init];
[parser parseXML:data];
NSString *URL=#"http://www.google.com";
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];
NSString * theString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
[resp release];
[err release];
NSLog(#"response: %#", theString);

Encoding Problem in iphone

Below is my code..
NSString *strResponce = [[NSString alloc] initWithData:JsonData encoding:NSASCIIStringEncoding];
here string has some data.
[JsonData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
ArrayWebContent=[json objectWithString:strResponce error:&error];
But array is null.
any suggestion....
check your json data first put the content of the string strResponce in to the url
Checking json data are proper for parsing
if it gonna generate the parse error than you should check the content of the ws as it may content special charactor for which iphone can not support parsing
good luck
Try with below functions.
- (id) objectWithUrl:(NSURL *)url
{
SBJSON *jsonParser = [SBJSON new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
Let me know for any difficulty.

Get driving direction in iPhone

I read both iPhone and Google Map for iPhone EULA and want to implement a static driving direction map in my iPhone application (native).
I am finding a simple way to get route data and display with build-in route display feature in iOS 4 SDK' Mapkit.
Is there any programmer implement a feature like this with Google Map and Bing Map? Since Bing Map provided routing data in SOAP web service, it's seem easier to programming driving direction with Bing's service.
I found the solution for this. Just use a JSON parser to got google map API
For example:
NSDictionary *testJsondata = [self testJson:GoogleMapXMLDirectionQueryString];
NSLog(#"Here is the title of the response: %#", [testJsondata valueForKey:#"status"]);
for (id key in testJsondata) {
NSLog(#"key: %#, value: %#", key, [testJsondata objectForKey:key]);
}
}
- (NSDictionary *) testJson : (NSString*) url
{
id response = [self objectWithUrl:[NSURL URLWithString:url]];
NSDictionary *feed = (NSDictionary *)response;
return feed;
}
- (id) objectWithUrl:(NSURL *)url
{
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSString *)stringWithUrl:(NSURL *)url
{
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse: &response
error: &error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (NSString *)getDirectionInXML:(NSString *)GoogleMapXMLDirectionQueryString
{
NSError *error;
NSURLResponse *response;
NSData *dataReply;
NSString *stringReply;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString: [NSString stringWithFormat:GoogleMapXMLDirectionQueryString]]];
[request setHTTPMethod: #"GET"];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
return stringReply;
}