How to parse JSON response from Rest API - ios

I am working on an app that will parse data from a Rest API. As I haven't done this before, I was wondering if NSScanner or NSRange would work for this. Here is an example using NSScanner for such purposes. It's a small string so it doesn't take much code, so it seemed like a quick and dirty option. Is there an easier and quicker way to do this?
- (void)GetAliasName:(NSString *)cno selector:(NSString*)selectorName completionHandler:(void (^)(NSDictionary *, NSError *))handler
{
NSMutableDictionary *d = [[NSMutableDictionary alloc] init];
[d setValue:interface forKey:#"interface"];
[d setValue:#"GetAlias" forKey:#"method"];
NSMutableDictionary *p = [[NSMutableDictionary alloc] init];
cno = [[NSUserDefaults standardUserDefaults] objectForKey:#"cno"];
[p setValue:cno forKey:#"cno"];
[p setValue:selectorName forKey:#"selector"];
[d setValue:p forKey:#"parameters"];
NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];
[self load:data completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"done");
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"GetAlias RAW response = %#", s);
if (apiConditions)
{
dispatch_async(dispatch_get_main_queue(),
^{
[hud hide:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"No network connection or no data found" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
NSLog(#"data is NIL");
});
}
else
{
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
handler(d, error);
//scans for aliasname
NSString *match = #"AliasName\": \"";
NSString *preTel;
NSString *postTel;
NSScanner *scanner = [NSScanner scannerWithString:s];
[scanner scanUpToString:match intoString:&preTel];
[scanner scanString:match intoString:nil];
postTel = [s substringFromIndex:scanner.scanLocation];
//removes newlines, characters, and whitespaces from aliasname
NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:#"}]\""];
postTel = [[postTel componentsSeparatedByCharactersInSet: trim] componentsJoinedByString: #""];
postTel = [[postTel componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString: #""];
NSLog(#"postTel: %#", postTel);
NSString *docno = [[NSUserDefaults standardUserDefaults] objectForKey:#"docno"];
//if docno is filled in, look up TR by docno
if ([docno isEqual: #""])
{
[self GetTR:(NSString*)postTel customStatus:customStatus completionhandler:^(NSDictionary *dictionary, NSError *error) {
nil;
}];
}
}];
}

There is NSJSONSerialization which is built for this.
Use it as follows:
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSString *aliasName = dictionary[#"AliasName"];
Edit
Since you already use this, and have dictionary, the only step you needed was to access dictionary with needed key(last step).

Related

Forward geocoding doesnt give correct results

I didn't get correct results for Forward geocoding in certain cases. When I search for some places or hotel it shows result of some others places or areas. I have got following code. I study the following link. What url should i place to get correct results.
how can we implement the following given in following site
https://developers.google.com/places/webservice/autocomplete
A request for addresses containing "Vict" with results in French:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=geocode&language=fr&key=API_KEY
A request for cities containing "Vict" with results in Brazilian
Portuguese:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=(cities)&language=pt_BR&key=API_KEY
I have implemented following but it doesn't give the results as i aspected
- (CLLocationCoordinate2D)addressLocation{
NSError *error = nil;
// NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true", SearchtextField];
// NSString *API_KEY=#"AIzaSyB27SkGBzvEYKcxvZ5nmOVWvrA-6Xqf-7A";
NSString *API_KEY=#"AIzaSyCHcqJcqZbP1XpU-WB4VfRct5hpdgqisSY";
NSString *lookUpString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?address=%#&region=np&key=%#", SearchtextField,API_KEY];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
NSArray *locationArray = [[[jsonDict valueForKey:#"results"] valueForKey:#"geometry"] valueForKey:#"location"];
NSString *statusString = [jsonDict valueForKey:#"status"];
if ([statusString isEqualToString:#"OK"])
{
locationArray = [locationArray objectAtIndex:0];
Str_Latitude= [locationArray valueForKey:#"lat"];
Str_Longitude= [locationArray valueForKey:#"lng"];
NSLog(#"LatitudeString:%# & LongitudeString:%#", Str_Latitude, Str_Longitude);
/*Google place latitude Longitude*/
Arr_LatLong = #[Str_Latitude,Str_Longitude];
[[NSUserDefaults standardUserDefaults] setValue:Str_Latitude forKey:#"Str_Latitude"];
[[NSUserDefaults standardUserDefaults] setValue:Str_Longitude forKey:#"Str_Longitude"];
[[NSUserDefaults standardUserDefaults] synchronize];
GogLatitude = [Str_Latitude doubleValue];
Goglongitude = [Str_Longitude doubleValue];
if (Bool_SearchField) {
[self getGoogleAddress];
Bool_SearchField=FALSE;
}else{
}
}else{
UIAlertView *alertview =[[UIAlertView alloc] initWithTitle:#"Address not found" message:#"make sure you enter a valid address" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertview show];
NSLog(#"Something went wrong, couldn't find address");
[self.tableView reloadData];
}
GogLocation.latitude = GogLatitude;
GogLocation.longitude = Goglongitude;
return GogLocation;
}
When i search for radission in maps.google.com it shows as below
But when i search in my app it shows different locations then what I search
You can either take use of the Region Biasing, which according to wiki, should be NP. So add &region=np at the end of your query.
Or you can use the Viewport Biasing to set the bounds of your searches.
I have done what you have asked in one of my apps, but the url is different.
I am posting the function that gets called each time i input something in a text field.
-(void) startAutocomplete{
NSString* baseUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?input=%#&key=AIzaSyDz3HAmNY8NsgIhtA8gtbH-QA08Lg9tej4&types=all", self.locationTextfield.text];
NSURL *url = [NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"Url: %#", url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError!=nil) {
[[[UIAlertView alloc] initWithTitle:nil message:connectionError.localizedDescription delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil] show ] ;
}else{
NSError *error = nil;
self.searchResult= [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//NSLog(#"result:%#",self.searchResult);
[self.tableView reloadData];
}
}];
}

Is it possible to only get a url title without load whole wabpage?

I know that use a UIWebview can get title in delegate method webViewDidFinishLoad
But,I want to know if there is a way to only get the title without load the whole webpage?Like http request or something else?
Create url request with asynchronous call to get data from url.
This can be done like this for example:
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
^(NSURLResponse *response, NSData *data, NSError *err) {
// Get Title
NSString *strTitle = #"";
if (data && !err)
{
NSString *returnDataIntoString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(#"data : %#",returnDataIntoString);
if (returnDataIntoString.length > 0)
{
NSError *error = nil;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithHTMLString:returnDataIntoString encoding:NSUTF8StringEncoding error:&error];
if (doc && !error) {
NSArray *employees = [doc nodesForXPath:#"//title" error:NULL];
for (GDataXMLElement *employe in employees) {
strTitle = [employe stringValue];
}
}
}
}
else
{
NSLog(#"Error : %#",[err description]);
}
//Set Title here
}];
Note : Now i have used third party library to parse html using GDataXML-HTML
Do you have a whole HTML string? You can using regular expression to parse string if you have it:
NSString *string = #"Your HTML String";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"<title[^>]*>(.*?)</title>"
options:0
error:&error];
NSTextCheckingResult *result = [regex firstMatchInString:string options:NSMatchingReportProgress range:NSMakeRange(0, [string length])];
NSRange titleRange = [result rangeAtIndex:1];
NSString *title = [string substringWithRange:titleRange];

Adding Multiple GET Requests to NSMutableArray in iOS App

The app keeps score during a game. Based off of your score, it will retrieve a quote from an online database, using a GET method and returning it in JSON format. For example, your score is 5, you get 1 quote, 10, you get 2 and so on. The view that shows the quote(s) is a UIViewController with a UITextView in it.
I have a for loop that runs based off the score, to run the same GET request over and over again, after a 1.5 second delay so the server housing the database won't reject requests made nearly simultaneously.
I create a few NSStrings and pull information from the JSON data, append it into some basic HTML code and then set that as the UITextView attributedText.
Most of the time this runs great, but every once in a while, I'll expect 2 quotes, and only get 1, or some of the quotes will wind up being the same.
Can someone tell me if there is a better way to go about doing this than how I currently am?
- (void)viewWillAppear:(BOOL)animated {
if ([textView.text isEqualToString:#""]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger getReady = [defaults integerForKey:#"after"];
self.theNumber = getReady;
for(int i = 0; i< self.theNumber; i++) {
[self performSelector:#selector(quoteView) withObject:self afterDelay:1.5 ];
}
}
}
-(void) quoteView {
NSString *bringitalltogether = #"http://url.com&type=json";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:bringitalltogether]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[request setHTTPMethod:#"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
if (code == 200){
}
else
{
UIAlertView *oops = [[UIAlertView alloc] initWithTitle:#"Oops" message:#"The network is having difficulties getting you the quote. Please check your network settings and try again later." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[oops show];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableDictionary *allResults = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
NSArray *book = [allResults valueForKey:#"bookname"];
self.bookstring = [book objectAtIndex:0];
NSArray *chapter = [allResults valueForKey:#"chapter"];
self.chapterstring = [chapter objectAtIndex:0];
NSArray *verse = [allResults valueForKey:#"verse"];
self.versestring = [verse objectAtIndex:0];
NSArray *text = [allResults valueForKey:#"text"];
self.textstring = [text objectAtIndex:0];
[self doneGotIt];
}
- (void) doneGotIt {
if (!self.theArray) {
self.theArray = [[NSMutableArray alloc] init];
}
NSString *doIt = [NSString stringWithFormat:#"%# - %# %#:%#", self.textstring, self.bookstring, self.chapterstring, self.versestring];
[self.theArray addObject:doIt];
NSString *theEnd = [self.theArray componentsJoinedByString:#"\n"];
NSString *loadHTML = [#"<head> <style type='text/css'>a > img {pointer-events: none;cursor: default;}</style></head><b><div align=\"left\"><font size=5>" stringByAppendingString:theEnd];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[loadHTML dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
textView.attributedText = attributedString;
NSLog(#"ARRAY: %#", self.theArray);
NSLog(#"String: %#", theEnd);
}
-(IBAction)finished {
[self dismissViewControllerAnimated:YES completion:nil];
textView = nil;
}
From the NSLogs I have towards the end there, sometimes the NSMutableArray contains several of the same quotes, which is why they don't show in the string, because it eliminates duplicates. My question is if there is a better way to do this that will keep these errors from occurring?
Here is some pseudo code for you
mutableArray = new NSMutableArray
while([mutableArray count] < total) {
quote = getQuote()
if([array indexOfObject:quote] != NSNotFound)
[mutableArray addObject:quote]
}
This will ensure you do not have duplicate quotes. After you have an array of valid quotes, you can then construct the string exactly how you want it.

block not being called on the other end

i'm new to blocks, I have a class of requests with static methods to call me back on UIViewControllers with some blocks
this is the method implementation :
(putting a breakpoint on the block(something) DOES stop there, like it should)
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*callBackArray))block
{
if ([text isEqualToString:#""] || [text isEqualToString:#" "])
{
block(nil);
return;
}
NSString * key = #"someActualKeyHere";
;
NSString * finalText;
NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
[tagger setString:text];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
if ([language isEqualToString:#"he"])
{
finalText = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
else
{
finalText = [text stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
}
NSString *urlString = [NSString stringWithFormat:
#"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%#&types=geocode&sensor=true&key=%#",finalText,key];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (!responseObject && ![responseObject respondsToSelector:#selector(dataWithData:)])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving "
message:#"ERROR"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
return ;
}
NSData * responseData = [NSData dataWithData:responseObject];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSError *err;
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
this is how I call it, notice the NSLog, i put a breakpoint on it and its never called
which is exactly what I want to occur.
[Requests requestSuggestedLocationsForText:text withBlock:^(NSArray *callBackArray)
{
NSLog(#"ROFL");
}];
for the record, I have tried the same method with a different signature (without the returning variable name like so :
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*))block;
still didn't fire my breakpoint :(
I think that this:
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
Never runs because as far as I know, NSString doesn't declare JSONObjectWithData. Your break point will never hit because it will never be called.
It seems like it could just be:
NSData * responseData = [NSData dataWithData:responseObject];
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (!err) {
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
else {
block(nil);
}
The other way you convert it to a string, then back to data, why not just keep it as data?

iOS : Query regarding dynamically created array

I get four parameters from a web service (web service 2 in my flow) - slno, order, flag, name. I don't know how many times these parameters are going to be received. Out of these four paramters, I send 'name' to a label as it contains questions to be asked.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"some url"]];
NSLog(#"Web service 2 url is = %#", url);
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(#"Json data = %# \n error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:Nil];
//NSArray *arrayLabel = [[NSArray alloc] initWithObjects:label1, label2, label3, label4, label5, label6, nil];
//NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:myJsonArray.count];
i = 0;
for(NSDictionary *myJsonDictionary in myJsonArray)
{
//UILabel *label = (UILabel *)[arrayLabel objectAtIndex:i++];
//[label setText:myJsonDictionary[#"Name"]];
NSString *name = myJsonDictionary[#"Name"];
NSLog(#"Question from ws2 is %#", name);
projectIdGobal = myJsonDictionary[#"ProjectID"];
NSLog(#"Project id from ws2 is %#", projectIdGobal);
slno = myJsonDictionary[#"SLNO"];
NSLog(#"slno from ws2 is %#", slno);
NSString *idWS2 = myJsonDictionary[#"ID"];
NSLog(#"id from ws2 is %#", idWS2);
order = myJsonDictionary[#"Order"];
NSLog(#"order from ws2 is %#", order);
flag = myJsonDictionary[#"Flag"];
NSLog(#"flag from ws2 is %#", flag);
[self putLabelsInScrollView:name];
i++;
}
NSLog(#"Number of cycles in for-each = %d", i);
[activity stopAnimating];
}
- (void) putLabelsInScrollView:(NSString *)labelText
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
[label setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0f]];
label.numberOfLines = 2;
[label setText:labelText];
[self.scroll addSubview:label];
yPosition_label += 90;
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.textColor = [UIColor blackColor];
text.font = [UIFont systemFontOfSize:12.0];
text.backgroundColor = [UIColor clearColor];
text.keyboardType = UIKeyboardTypeDefault;
text.delegate = self;
[self.scroll addSubview:text];
yPosition_text += 90;
yPosition_result = yPosition_label + yPosition_text;
[self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
[self.view addSubview:self.scroll];
}
Now I created a dynamically created text fields and stored the answers entered by the user in the array as follows.
- (IBAction)save:(id)sender {
NSMutableArray *mutableTextArray = [[NSMutableArray alloc] init];
for(UITextField *field in self.scroll.subviews)
{
if([field isKindOfClass:[UITextField class]])
{
if([[field text] length] > 0)
{
[mutableTextArray addObject:field.text];
//NSLog(#"Save button 1 : %#", mutableTextArray);
//NSString *str = [str stringByAppendingString:[mutableTextArray objectAtIndex:0]];
//[self fetchStrings:mutableTextArray];
}
}
}
NSLog(#"Save button 2 : %#", mutableTextArray);
[self fetchStrings:mutableTextArray];
}
Now while posting the answer to another web service (web service 3 in my flow), I must pass slno, order, flag i get from web service 2 and the 'answer' that the user enters in the dynamically created field to the 'answer' key. How shall I get these 4 parameters [slno, order, flag (from web service 2) and answer (from dynamic text field)] to post to web service 3?
- (void) fetchStrings:(NSArray *)textArray
{
NSLog(#"Array string = %#", textArray); //I get the array that the user enters in the dynamically created text field here
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSUserDefaults *getDefaults = [NSUserDefaults standardUserDefaults];
NSString *uidObject = [getDefaults objectForKey:#"UIDKEY"];
NSString *str = [NSString stringWithFormat:#"{\"ProjID\": \"%#\",\"Uid\": \"%#\",\"EmailID\": \"%#\",", projectIdGobal, uidObject, emailFromLogin];
str = [str stringByAppendingString:#"\"ProjectInviterFQAnswers\": ["];
**for (SaveAsking *saveAsk in textArray) {
str = [str stringByAppendingString:[NSString stringWithFormat:#"{\"slno\":\"%#\",\"Answer\": \"%#\",\"order\": \"%#\", \"flag\": \"%#\"},", saveAsk.slno, saveAsk.answer, saveAsk.order, saveAsk.flag]]; // I want to save the parameters here
}**
// SaveAsking is a nsobject class where I have used a self created delegate for slno answer order and flag
str = [str stringByAppendingString:#"]}"];
NSLog(#"String is === %#", str);
NSURL *url = [NSURL URLWithString:#"some url"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if(error || !data)
{
NSLog(#"JSON Data not posted!");
[activity stopAnimating];
UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Data not saved" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertMessage show];
}
else
{
[activity startAnimating];
NSLog(#"JSON data posted! :)");
NSError *error = Nil;
NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Response is %#", jsonObject);
}
}];
}
Please do correct my flow if you understood what am i trying to achieve. Number for iterations in left box == number of iterations in right box and the result is in the middle box which needs to be posted to web service.
Try keeping a dictionary of the requests, where the key would be the dynamically created UITextField, and the value would be another dictionary with the values that you need to send.
So , when you create the textField, after adding it to the subview, create a dictionary with your values (sino, order, flag), and set that dictionary to the textfield.
When you are ready to send the data, you'll have a direct connection between the textField and the values for your webservice3.

Resources