Fetching data from Facebook multiple times in iOS - ios

I am new to iPhone programming using below code i am login in Facebook and fetching data from Facebook like email id,username after that emailid i am sending to server.But my problem is if already login in Facebook means automatically its calling
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id)user in this method email id sending to server.I don't want like this if i click on button then only i want to fetch Facebook email id and send to server.Please can any one give some idea how to solve it.
-(void)viewdidload
{
FBLoginView *fbLoginview =
[[FBLoginView alloc] initWithPublishPermissions:[NSArray arrayWithObjects:#"publish_actions",#"email",nil] defaultAudience:FBSessionDefaultAudienceFriends];
fbLoginview.frame = CGRectMake(30, 10, 200, 30);
for (id obj in fbLoginview.subviews)
{
if ([obj isKindOfClass:[UIButton class]])
{
loginWithFbButton = obj;
loginWithFbButton.frame = CGRectMake(0, 0, 200, 30);
[loginWithFbButton setBackgroundColor:[UIColor colorWithRed:69.0/255.0 green:115.0/255.0 blue:185.0/255.0 alpha:1]];
[loginWithFbButton setBackgroundImage:nil forState:UIControlStateNormal];
[loginWithFbButton setBackgroundImage:nil forState:UIControlStateSelected];
[loginWithFbButton setBackgroundImage:nil forState:UIControlStateHighlighted];
[loginWithFbButton.layer setBorderWidth:1.0f];
[loginWithFbButton.layer setBorderColor:[UIColor colorWithRed:225.0/255.0 green:227.0/255.0 blue:231.0/255.0 alpha:0.6].CGColor];
loginWithFbButton.layer.masksToBounds = YES;
loginWithFbButton.layer.cornerRadius = 5;
[loginWithFbButton setTitle:#" Get info from Facebook" forState:UIControlStateNormal];
[loginWithFbButton.titleLabel setFont:[UIFont fontWithName:#"HelveticaNeue" size:13]];
loginWithFbButton.titleLabel.textAlignment = NSTextAlignmentCenter;
loginWithFbButton.titleLabel.backgroundColor = [UIColor clearColor];
loginWithFbButton.titleLabel.textColor = [UIColor whiteColor];
CAGradientLayer *gradient1 = [CAGradientLayer layer];
gradient1.frame = loginWithFbButton.bounds;
UIColor *startColour1 = [UIColor colorWithRed:46.0/255.0 green:174.0/255.0 blue:225.0/255.0 alpha:1.0f];
UIColor *endColour1 = [UIColor colorWithRed:46.0/255.0 green:119.0/255.0 blue:225.0/255.0 alpha:1.0f];
gradient1.colors = [NSArray arrayWithObjects:(id)[startColour1 CGColor], (id)[endColour1 CGColor], nil];
[loginWithFbButton.layer insertSublayer:gradient1 atIndex:0];
[fbLoginview addSubview:loginWithFbButton];
}
if ([obj isKindOfClass:[UILabel class]])
{
UILabel * loginLabel = obj;
loginLabel.text = nil;
loginLabel.textAlignment = NSTextAlignmentCenter;
loginLabel.frame = CGRectMake(0, 0, 271, 26);
}
}
fbLoginview.delegate = self;
[loginTempview3 addSubview:fbLoginview];
}
fetching
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
NSLog(#"Loginvieewww");
// self.profilePic.profileID = user.id;
//self.profilePic.profileID = #"1772134559592493";
// NSLog(#"usr_id::%#",user.id); NSLog(#"%#",user);
NSLog(#"usr_first_name::%#",user.first_name);
NSString *emailiddd=[NSString stringWithFormat:#"%#",[user objectForKey:#"email"]];
NSLog(#"%#",emailiddd);
NSLog(#"usr_last_nmae::%#",user.last_name);
NSLog(#"usr_Username::%#",user.username);
NSLog(#"usr_b_day::%#",user.birthday);
NSString *post = [NSString stringWithFormat:#"email=%#",emailiddd];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://54.221.218.162/index.php/api/userClass/registerFBUser/format/xml"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"Aslam here");
NSLog(#"%#",request);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [NSMutableData data];
NSLog(#"%#",webData);
}
else
{
}
}
Thanks
Aslam

Related

Wkwebview cangoback is giving wrong results

I'm showing back button in webview if canGoBack is true.
It works fine but for one particular webpage even though there's no back page to go back, the webview says cangoback as true while cangoback should have been false.
Update
Here is the code snippet to init my webview
-(void)initWebView{
WKUserContentController* userContentController = WKUserContentController.new;
NSString* documentCookie = [self documentCookie];
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource: documentCookie
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
// again, use stringWithFormat: in the above line to inject your values programmatically
[userContentController addUserScript:cookieScript];
WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
webViewConfig.userContentController = userContentController;
self.webviewObj = [[WKWebView alloc] initWithFrame:CGRectMake(self.vuParent.frame.origin.x, self.vuParent.frame.origin.y, self.vuParent.frame.size.width, self.vuParent.frame.size.height) configuration:webViewConfig];
self.webviewObj.UIDelegate = self;
[self.webviewObj setBackgroundColor:[UIColor whiteColor]];
self.webviewObj.translatesAutoresizingMaskIntoConstraints=false;
[self.vuParent addSubview:self.webviewObj];
}
Here is how I load a request in my webview
-(void)completeWebRequest
{
NSString* urlToRequestStr = #"";
if ([[self targetUrl] length]) {
urlToRequestStr = [self targetUrl];
}
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: urlToRequestStr]];
if (self.isPOST) {
NSMutableData *body = [[NSMutableData alloc] initWithData:[self.postParams dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[body length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:body];
}
[self initWebView];
self.webviewObj.scrollView.scrollEnabled=false;
[self.view setBackgroundColor:[UIColor whiteColor]];
[self.webviewObj setOpaque:false];
self.webviewObj.navigationDelegate = self;
[self setOriginalUrlToRequest:tempRequest];
[[self webviewObj] loadRequest:tempRequest];
}
Here is how I check if back button needs to be shown or not.
[self setBackButtonCheckTimer:[NSTimer timerWithTimeInterval:0.1 target:self selector:#selector(chkBackBtn) userInfo:nil repeats:true]];
- (void) chkBackBtn {
if ([[self webviewObj] canGoBack]) {
[[self navigationItem] setLeftBarButtonItem:[self bkButton]];
}
else{
[[self navigationItem] setLeftBarButtonItem:nil];
}
}
There is a way that you can use it in order to debug such a problem.
The canGoBack method works based on backForwardList.
You can validate what you have in the list and change it.

how to add json parse data in core data in iOS?

This my data parsing code parsing is done.how to add that data in core data
-(void)DataRetireve
{
deatilinfoarray = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString: #"http://sms.instatalkcommunications.com/apireq/GetSMSCategories?t=1&h=admin&param=1"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
(void)requestFinished:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSString *responseString = nil;
if (!error)
{
responseString = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init] ;
NSMutableArray *jsondata = [parser objectWithString:responseString];
NSMutableArray *jsondata1 = [[NSMutableArray alloc]init];
for(int i=0;i<jsondata.count;i++)
{
info *myinfo=[[info alloc]init];
myinfo.Id=#"Id";
myinfo.Name=#"Name";
myinfo.IsActive=#"IsActive";
[jsondata1 addObject:myinfo];
NSLog(#"%#",responseString);
}
for(int i=0;i<jsondata1.count;i++)
{
info *myinfo= [jsondata1 objectAtIndex:i];
[jsondata1 addObject:myinfo];
}
The simplest way you can use it is-
int yPossion = 50, xPossion = 10; int temp = 0;
UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:self.view.frame];
[self.view addSubview:scrollView];
for (int i = 0; i<50; i++){
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundColor:[UIColor blackColor]];
[aButton setBackgroundImage:[UIImage imageNamed:#"icon-menu.png"] forState:UIControlStateNormal];
[aButton setTitle:[NSString stringWithFormat:#" %d",i] forState:UIControlStateNormal];
[aButton setFrame:CGRectMake(xPossion, yPossion, 100, 50)];
[scrollView addSubview:aButton];
xPossion += aButton.frame.size.width+15;
temp++;
if (temp==3) {
yPossion = aButton.frame.origin.y+aButton.frame.size.height+15;
temp = 0;
xPossion = 10;
[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width, yPossion+50)];
}
}
But if you want to it using autoLayout constrains then you can follow this link may be it will help you.

UIButton not firing

I have a UIButton dynamically created inside a UITapGestureRecognizer, I have set the button handler but the handler never gets called when the button is pressed.
Here is how I am creating the UIButton in the tap gesture:
UIButton *uiButton = [[UIButton alloc] init];
[uiButton setTitle:#"Back" forState:UIControlStateNormal];
[uiButton setFrame:CGRectMake(0, 20, 80, 25)];
[uiButton addTarget:self action:#selector(myButtonClick) forControlEvents:UIControlEventTouchDown];
And this is the Button Handler:
- (void)myButtonClick {
// button was tapped - do something
if(NULL) {
}
}
This has been EDITED:
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {
CGPoint location = [recognizer locationInView:[recognizer.view superview]];
CGPoint touchPoint=[recognizer locationInView:[recognizer.view superview]];
UIViewMenuItem *tempView = (UIViewMenuItem *)recognizer.view;
NSNumber *tag = [NSNumber numberWithInt:tempView.tag];
NSString *idCat = [tempView getCatId];
NSLog(#"TAG %#",idCat);
//NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: [NSString stringWithFormat:#"http://localhost:8888/MAMP/WHFC/SubCategories.php?categoryid//=%d", idCat]]];
NSString *myRequestString = [NSString stringWithFormat:#"categoryid=%#",idCat];
// Create Data from request
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://localhost:8888/MAMP/WHFC/SubCategories.php"]];
// set Request Type
[request setHTTPMethod: #"POST"];
// Set content-type
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
// Set Request Body
[request setHTTPBody: myRequestData];
// Now send a request and get Response
NSData *data = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
NSError *err;
NSArray *arrCategoryList = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
const unsigned char *ptr = [data bytes];
for(int i=0; i<[data length]; ++i) {
unsigned char c = *ptr++;
NSLog(#"char=%c hex=%x", c, c);
}
self.data = [[NSMutableArray alloc] init];
for(NSDictionary *dictCategory in arrCategoryList)
{
NSString *strCategoryId = [dictCategory objectForKey:#"CategoryId"];
NSString *strCategoryName = [dictCategory objectForKey:#"Name"];
NSLog(#"%# : %#",strCategoryId,strCategoryName);
Listing *listing = [[Listing alloc] init];
listing.catId = strCategoryId;
listing.name = strCategoryName;
[self.data addObject:listing];
}
UIViewController *viewController = [[UIViewController alloc] init];
viewController.view.backgroundColor = [UIColor whiteColor];
UIView *uiView = [[UIView alloc] init];
[uiView setFrame:CGRectMake(0, 480, 320, 480)];
[uiView setBackgroundColor:[UIColor grayColor]];
viewController.view = uiView;
UINavigationBar *uiNavigationBar = [[UINavigationBar alloc] init];
[uiView setFrame:CGRectMake(0, 0, 320, 50)];
[uiView addSubview:uiNavigationBar];
UIButton *uiButton = [[UIButton alloc] init];
[uiButton setTitle:#"Back" forState:UIControlStateNormal];
[uiButton setFrame:CGRectMake(0, 20, 80, 25)];
[uiButton addTarget:self action:#selector(myButtonClick) forControlEvents:UIControlEventTouchDown];
[uiNavigationBar addSubview:uiButton];
uiTableView1 = [[UITableView alloc] init];
[uiTableView1 setFrame:CGRectMake(0, 50, 320, 480)];
uiTableView1.dataSource = self;
uiTableView1.delegate = self;
[uiView addSubview:uiTableView1];
[self presentViewController:viewController animated:YES completion:nil];
//Do stuff here...
}
- (void)myButtonClick {
// button was tapped - do something
if(NULL) {
}
}
Maybe your gesture recognizer is catching the touch and therefor is never reaching the button. To let the button get the event you have to set the delegate of UIGestureRecognizerDelegate and implement something like this
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if ((touch.view == mybutton)||(touch.view == anyOtherButton)) {
return NO;
}
return YES;
}
hope it helps
Biggest mistake you have made is you used forControlEvents is UIControlEventTouchDown. Your requirement is different here.`
Solution : It should be UIControlEventTouchUpInside as button gets clicked when touched.
Replace below line with yours
[uiButton addTarget:self action:#selector(myButtonClick) forControlEvents:UIControlEventTouchUpInside];
EDIT : Also superview of button is out of bound ie y is 480 it should be 0
Replace below line with yours
[uiView setFrame:CGRectMake(0, 0, 320, 480)];

ProgressHUD problems with Asynchronous request

I'm trying to progressHUD in the Asynchronous request, but it does not seem to work probably. What i want is it to show the progessHUD until the Asynchronous request is done. at the moment it is not showing in the beginning, but after 3 sec it is showing for 0.1 second or something and after that the Asynchronous request is completed. What am i doing wrong, to achieve that the progessHUD is shown when the viewisloaded to the Asynchronous request is done?
As you can see below i've added progressHUD show and dismiss in the viewDidLoad and in the firstRequest method.
Viewdidload:
- (void)viewDidLoad
{
[super viewDidLoad];
[ProgressHUD show:#"Please Wait..."];
buttonLogin = [[UIBarButtonItem alloc] initWithTitle:#"Login" style:UIBarButtonItemStyleBordered target:self action:#selector(actionLogin)];
buttonLogout = [[UIBarButtonItem alloc] initWithTitle:#"Logout" style:UIBarButtonItemStyleBordered target:self action:#selector(actionLogout)];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
self.theTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight-160) style:UITableViewStylePlain];
self.theTableView.dataSource = self;
self.theTableView.delegate = self;
[self.view addSubview:self.theTableView];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
self.navigationController.navigationBar.titleTextAttributes = #{NSForegroundColorAttributeName : [UIColor whiteColor]};
fixtures = [[NSMutableArray alloc] init];
sections = [[NSMutableArray alloc] init];
sortedArray = [[NSMutableArray alloc] init];
[self firstRequest];
self.bannerView = [[GADBannerView alloc] initWithFrame:CGRectMake(0.0, self.view.frame.size.height-100, GAD_SIZE_320x50.width, GAD_SIZE_320x50.height)];
self.theTableView.backgroundColor = [UIColor colorWithRed:243/255.0f green:243/255.0f blue:247/255.0f alpha:1.0f];
self.view.backgroundColor = [UIColor colorWithRed:243/255.0f green:243/255.0f blue:247/255.0f alpha:1.0f];
[self checkAuthStatus];
[ProgressHUD dismiss];
}
the request:
-(void)firstRequest
{
NSURL *url = [NSURL URLWithString:#"URL"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
[ProgressHUD show:#"Please Wait..."];
jsonResult = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
int subObjects = ((NSArray *)jsonResult[#"match"]).count;
for (int i = 0; i <= subObjects-1; i++) {
NSString *date = [NSString stringWithFormat:#"%# %#",[[[jsonResult valueForKey:#"match"] valueForKey:#"playdate"] objectAtIndex:i], [[[jsonResult valueForKey:#"match"] valueForKey:#"time"] objectAtIndex:i]];
NSString *identifier = [[NSLocale currentLocale] localeIdentifier];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone: [NSTimeZone timeZoneWithName:#"US/Arizona"]];
[df setLocale:[NSLocale localeWithLocaleIdentifier:identifier]];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *myDate = [df dateFromString:[NSString stringWithFormat:#"%#", date]];
NSArray *items = [[NSString stringWithFormat:#"%#", myDate] componentsSeparatedByString:#" "];
NSString *home = [[[jsonResult valueForKey:#"match"] valueForKey:#"hometeam"] objectAtIndex:i];
NSString *away = [[[jsonResult valueForKey:#"match"] valueForKey:#"awayteam"] objectAtIndex:i];
NSString *league = [[[jsonResult valueForKey:#"match"] valueForKey:#"league"] objectAtIndex:i];
[fixtures addObject:
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
items[0], #"date",
items[1], #"time",
home, #"home",
away, #"away",
league, #"league",
nil]];
[sections addObject:
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
items[0], #"date",
nil]];
}
NSArray *copy = [sections copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
if ([sections indexOfObject: object inRange: NSMakeRange(0, index)] != NSNotFound) {
[sections removeObjectAtIndex: index];
}
index--;
}
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject: descriptor];
NSArray* reverseTheArray = [[sections valueForKey:#"date"] sortedArrayUsingDescriptors:descriptors];
reversedArray = [[reverseTheArray reverseObjectEnumerator] allObjects];
[self.theTableView reloadData];
[ProgressHUD dismiss];
}
];
}
You should show ProgressHUD before sending a request.
Your code should look like this.
-(void)firstRequest
{
[ProgressHUD show:#"Please Wait..."];
NSURL *url = [NSURL URLWithString:#"URL"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
// request processing stuff
...
[ProgressHUD dismiss];
}
];
Explanation. When you call sendAsynchronousRequest... the request itself performed somewhere in background thread. The network operation may take some time, 1-5-10 seconds. Your completionHandler will be executed once the request completes (after the delay). So you should show ProgressHUD before sending a request. Then start the request. And dismiss ProgressHUD at the end of your completionHandler block after everything is processed.
Update
There is one more issue I noticed in your code. viewDidLoad method is called only once on view controller when its view is loaded but at this point the view itself is not presented on screen. So you will not actually see ProgressHUD called from viewDidLoad. You may be interested in viewWillAppear and viewDidAppear methods if you want to handle when view is presented on screen.
I assume your view controller is designed to show data retrieved from web api. I believe the best option is to call your api in viewWillAppear.
- (void)viewDidLoad
{
[super viewDidLoad];
buttonLogin = [[UIBarButtonItem alloc] initWithTitle:#"Login" style:UIBarButtonItemStyleBordered target:self action:#selector(actionLogin)];
buttonLogout = [[UIBarButtonItem alloc] initWithTitle:#"Logout" style:UIBarButtonItemStyleBordered target:self action:#selector(actionLogout)];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
self.theTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight-160) style:UITableViewStylePlain];
self.theTableView.dataSource = self;
self.theTableView.delegate = self;
[self.view addSubview:self.theTableView];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
self.navigationController.navigationBar.titleTextAttributes = #{NSForegroundColorAttributeName : [UIColor whiteColor]};
fixtures = [[NSMutableArray alloc] init];
sections = [[NSMutableArray alloc] init];
sortedArray = [[NSMutableArray alloc] init];
self.bannerView = [[GADBannerView alloc] initWithFrame:CGRectMake(0.0, self.view.frame.size.height-100, GAD_SIZE_320x50.width, GAD_SIZE_320x50.height)];
self.theTableView.backgroundColor = [UIColor colorWithRed:243/255.0f green:243/255.0f blue:247/255.0f alpha:1.0f];
self.view.backgroundColor = [UIColor colorWithRed:243/255.0f green:243/255.0f blue:247/255.0f alpha:1.0f];
[self checkAuthStatus];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self firstRequest];
}
-(void)firstRequest
{
[ProgressHUD show:#"Please Wait..."];
NSURL *url = [NSURL URLWithString:#"URL"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
// request processing stuff
...
[ProgressHUD dismiss];
}
];
}

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