How to wait response and parse XML done in afnetworking iOS - iphone

I want to wait until server reponse and parse XML done, then call another function. How can i do that? I used this code to send request to server and use NSXMLParser to parse XML response.
NSURL *url1 = [NSURL URLWithString:#"linkserver"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: url1] ;
NSDictionary *params1 = #{
#"a" : vd;
#"b" : #"all"
};
NSMutableURLRequest *afRequest = [httpClient requestWithMethod:#"GET" path:nil parameters:params1] ;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success");
NSString * parsexmlinput = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
[self parseXMLFile:parsexmlinput];// parse xml
[self getItemFromStatus];// wait to call another function at here???
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);
}
];
[httpClient enqueueHTTPRequestOperation:operation];
}
Please give me any suggestion. Thanks much

You have to make your request synchronous.
refer code something like:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friends/ids.json?"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];

check this tutorial Ray Wenderlich using AFnetworking.
Using blocks and callbacks
- (IBAction)xmlTapped:(id)sender{
NSString *weatherUrl = [NSString stringWithFormat:#"%#weather.php?format=xml",BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFXMLRequestOperation *operation =
[AFXMLRequestOperation XMLParserRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser setShouldProcessNamespaces:YES];
[XMLParser parse];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[NSString stringWithFormat:#"%#",error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[av show];
}];
[operation start];
}

You can do it in synchronous way...
NSURLResponse *response = nil;
NSError *error = nil;
NSURL *url = [NSURL URLWithString:urlStr];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFFormURLParameterEncoding;
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:[url path] parameters:params];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * parsexmlinput = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if(error) {
errorCallback(error, nil);
} else {
//parse the xml here
}
OR
You can achive it by adding [operation waitUntilFinished],after it's added to the operation queue.Refer this==>Can AFNetworking return data synchronously (inside a block)?
OR
EDIT: In case you don't want to use the AFNetworking library.I prefer this way.
NSString *action_Post =[[NSString alloc] initWithFormat:#"authToken=%#",theMutableString];
NSURL *action_Url =[NSURL URLWithString:#"ur url here"];
NSData *action_PostData = [action_Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *action_postLength = [NSString stringWithFormat:#"%d", [action_PostData length]];//your parameter to be posted here
NSMutableURLRequest *action_Request = [[NSMutableURLRequest alloc] init];
[action_Request setURL:action_Url];
[action_Request setHTTPMethod:#"POST"];
[action_Request setValue:action_postLength forHTTPHeaderField:#"Content-Length"];
[action_Request setValue:#"application/xml" forHTTPHeaderField:#"Accept"];
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[action_Request setHTTPBody:action_PostData];
NSURLResponse *action_response;
NSData *action_Result = [NSURLConnection sendSynchronousRequest:action_Request returningResponse:&action_response error:&error];
if (!action_Result)
{
NSLog(#"Error");
}
else
{
//Parse your xml here
//call ur function
}
Modify it according to your GET/PUT methods.But i suggest you to go for POST method,as it is refered to be as secured one.

Related

how to call webservice in xcode by GET Method?

I have this link :
function new_message($chat_id,$user_id,$message,$recipient_ids)
http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2%2C7
return chat_log_id
Can anyone please explain me how to call webserive by this get method or give me the
solution .
what i did with my code is below :
-(void)newMessage{
if ([self connectedToWiFi]){
NSString *urlString = [NSString stringWithFormat:#"www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/1,1,2"];
NSLog(#"urlString is %#", urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *requestURL = [NSURL URLWithString:urlString];
[request setURL:requestURL];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"ERROR = %#",error.localizedDescription);
if(error.localizedDescription == NULL)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> succ %#",returnString);
[delegate ConnectionDidFinishLoading:returnString : #"newMessage"];
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> fail %#",returnString);
[delegate ConnectiondidFailWithError:returnString : #"newMessage"];
}
}];
}
}
how can i handle this ?
Thanks in advance .
I am not sure from your post whether or not you want to "post" or "get." However, gauging from the fact that you set your method to post, and that you are creating something new on your server, I am assuming you want to post.
If you want to post you can use my wrapper method for a post request.
+ (NSData *) myPostRequest: (NSString *) requestString withURL: (NSURL *) url{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:15.0];
NSData *requestBody = [requestString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
return responseData;
}
Where request string is formatted like this:
NSString * requestString = [[NSString alloc] initWithFormat:#"username=%#&password=%#", userInfo[#"username"], userInfo[#"password"]];
This will also shoot back the response data which you can turn into a string like this.
responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
If you are trying to grab data from the server in json format...
+ (NSArray *) myGetRequest: (NSURL *) url{
NSArray *json = [[NSArray alloc] init];
NSData* data = [NSData dataWithContentsOfURL:
url];
NSError *error;
if (data)
json = [[NSArray alloc] initWithArray:[NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error]];
//NSLog(#"get results: \n %#", json);
return json;
}
Pls change ur code like this
-(void)newMessage{
NSString *urlString = [NSString stringWithFormat:#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/27" ];
NSLog(#"urlString is %#", urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *requestURL = [NSURL URLWithString:urlString];
[request setURL:requestURL];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"ERROR = %#",error.localizedDescription);
if(error.localizedDescription == NULL)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> succ %#",returnString);
[self parseStringtoJSON:data];
//[delegate ConnectionDidFinishLoading:returnString : #"newMessage"];
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> fail %#",returnString);
// [delegate ConnectiondidFailWithError:returnString : #"newMessage"];
}
}];
}
-(void)parseStringtoJSON:(NSData *)data{
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"chat id %#",[dict objectForKey:#"chat_log_id"]);
}
u will get the JSON response string as result if u hit that url. If u r familiar with json parsing, u can get the value based on key.
see this link: How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

HTTP Post method php and ios

i'm facing a big problem,
I want to send data to my server, my data is a string.
I do not want to use Get method because the string might be very long, so i want to use POST method but everything goes, wrong, if someone can help me he'll be my hero :)
Here is my php code :
<?php include("config.inc.php");
if (isset($_POST['contentInterro']) && $_POST['contentInterro'] !="" ) {
//$id_user = $_POST['contentInterro'];
//$db->sql_query("INSERT INTO interrogations VALUES(DEFAULT, '$id_user')");
echo "succes";
}else{
echo "This is an error";
}
?>
Here is my app code :
NSData *postData = [stringToPost2 dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *requestPost = [[NSMutableURLRequest alloc] init];
NSURL *urlPost = [NSURL URLWithString:#"http://buzznapps.fr/FDF/postInterrogation.php"];
[requestPost setURL:urlPost];
[requestPost setHTTPMethod:#"POST"];
[requestPost setValue:#"lol" forHTTPHeaderField:#"contentInterro"];
NSError *errorURL;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:requestPost returningResponse:&response error:&errorURL];
NSString *str = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Str = %#",str);
I always get an error, and i've search the web i do not know how to get this data !
Thanks for any help.
#define TIMEOUT_INTERVAL 60
#define CONTENT_TYPE #"Content-Type"
#define URL_ENCODED #"application/x-www-form-urlencoded"
#define GET #"GET"
#define POST #"POST"
-(NSMutableURLRequest*)getNSMutableURLRequestUsingGetMethodWithUrl:(NSString*)url
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
[req setHTTPMethod:GET];
return req;
}
-(NSMutableURLRequest*)getNSMutableURLRequestUsingPOSTMethodWithUrl:(NSString *)url postData:(NSString*)_postData
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
[req setHTTPMethod:POST];
[req addValue:URL_ENCODED forHTTPHeaderField:CONTENT_TYPE];
[req setHTTPBody: [_postData dataUsingEncoding:NSUTF8StringEncoding]];
return req;
}
#try
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *_postData = [NSString stringWithFormat:#"user_name=%#&password=%#",#"user_name",#"password"];
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"error==%#==",[error localizedDescription]);
}
else
{
NSError *errorInJsonParsing;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorInJsonParsing];
if(errorInJsonParsing) //error parsing in json
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"error in json==%#==",[error localizedDescription]);
}
else
{
//do some operations
}
}
}];
}
#catch(NSException *exception)
{
NSLog(#"error in exception==%#==",[exception description]);
}
same way it works for the get method, just call the
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingGetMethodWithUrl:_url]; instead of NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];

How to post an array value in JSON

I want to post an array value in JSON.
Below is my code :
-(void)getConnection {
NSArray *comment=[NSArray arrayWithObjects:#"aaa",#"bbb",#"ccc",#"hello,yes,tell", nil];
NSURL *aurl=[NSURL URLWithString:#"http://sajalaya.com/taskblazer/staffend/form/iphonearraytest.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:aurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:comment options:NSJSONWritingPrettyPrinted error:nil];
NSString *new = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
// NSString *new = [comment JSONString];
// NSArray *new=[comment jsonvalue];
NSString *postString=[NSString stringWithFormat:#"tag=&comment=%#&total=%#",new,#"4"];
NSLog(#"this is post string%#",postString);
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
We don't know your question, but my answer is short and simple. You should use great open source library for this, which is: AFNetworking, and do request like this:
_httpClient = [[AFHTTPClient alloc] initWithBaseURL:[[NSURL alloc] initWithString:#"http://sajalaya.com"]];
[_httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:comment options:NSJSONWritingPrettyPrinted error:nil];
NSString *new = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
new, #"comment",
#4, #"total,
nil];
NSMutableURLRequest *request = [self.httpClient requestWithMethod:#"POST"
path:#"/taskblazer/staffend/form/iphonearraytest.php"
parameters:params];
request.timeoutInterval = 8;
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// failure
}];
Please use the following Mutable Array Operation componentsJoinedByString.
e.g.
NSMutableArray *commennts=[NSMutableArray arrayWithObjects:#"aaa",#"bbb",#"ccc",#"hello,yes,tell", nil];
NSString* strCommentsJoin = [commennts componentsJoinedByString:#","]; // Please use your separator

How to send a Get request in iOS?

I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as
[requestObject setHTTPMethod:#"GET"];
Tell me what could be the problem. Also provide me the code if you have.
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response1 =
[NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSString *getString = [NSString stringWithFormat:#"parameter=%#",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:#"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https:yoururl"]];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
Make sure your requestObject is of type NSMutableURLRequest.
Simply call and use:
(void)jsonFetch{
NSURL *url = [NSURL URLWithString:#"http://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *data = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSError *erro = nil;
if (data!=nil) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro ];
if (json.count > 0) {
for(int i = 0; i<10 ; i++){
[arr addObject:[[[json[#"feed"][#"entry"] objectAtIndex:i]valueForKeyPath:#"im:image"] objectAtIndex:0][#"label"]];
}
}
}
dispatch_sync(dispatch_get_main_queue(),^{
[table reloadData];
});
}];
[data resume];
}

Google Reader Token Request giving 403 error

I am trying to get the token from google reader for my iPhone project. I am able to get the Authorization but when I request for the token, I get a 403 Forbidden
Below is my code implementation. Any help would be appreciated.
//The tokenStorer contains the Authorization key
NSString *tokenStorer = [[NSUserDefaults standardUserDefaults]valueForKey:#"authKey"];
NSLog(#"%#", tokenStorer);
NSDictionary *cookieDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host",
#"iReader", #"User-Agent",
#"gzip, deflate", #"Accept-Encoding",
tokenStorer, #"Authorization",
nil
];
//#"Auth", NSHTTPCookieName, tokenStorer, NSHTTPCookieValue, #"./google.com", NSHTTPCookieDomain, #"/", NSHTTPCookiePath, nil];
//NSHTTPCookie *authCookie = [NSHTTPCookie cookieWithProperties:cookieDictionary];
//Google token url "http://www.google.com/reader/api/0/token?client=clientName"
NSURL *url=[[NSURL alloc] initWithString:GOOGLE_READER_TOKEN_URL];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:cookieDictionary];
NSData *reciveData;
NSURLResponse *response;
NSError *error;
reciveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSMutableURLRequest *tokenRequest= [[NSMutableURLRequest alloc] initWithURL:url];
NSString *trial = [[NSString alloc]initWithData:reciveData encoding:NSASCIIStringEncoding];
NSLog(#"%# %d",trial, response);
[url release];
The below code solved my problem:
-(id)queryLoginDetails {
//authKey returns the authorization key
NSString *tokenStorer = [[NSUserDefaults standardUserDefaults]valueForKey:#"authKey"];
NSLog(#"%#", tokenStorer);
NSString *auth = [[NSString alloc] initWithString:
[NSString stringWithFormat:#"GoogleLogin auth=%#", [tokenStorer substringToIndex:[tokenStorer length]-1]]];
NSDictionary *createHeader = [[NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host", #"iReader", #"User-Agent", #"gzip, deflate", #"Accept-Encoding", auth, #"Authorization", nil]retain];
NSURL *url =[NSURL URLWithString:GOOGLE_READER_TOKEN_URL];
NSData *recieveData;
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:createHeader];
NSURLResponse *response;
NSError *error;
recieveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSString *myString = [[NSString alloc]initWithData:recieveData encoding:NSASCIIStringEncoding];
return myString;
}