UIButton not firing - ios

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)];

Related

Data from JSON not updating in UICollectionView

I'm creating an app with a Newsfeed as a UICollectionView however it doesn't seem to update when I change the JSON file. I am using a UIRefreshControl to refresh it but I can't tell if my issue is to do with this or to do with how the JSON is read (or something else entirely).
viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.navigationItem.title = #"News";
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,23,16);
[btn setBackgroundImage:[UIImage imageNamed:#"menuImage.png"] forState:UIControlStateNormal];
[btn addTarget:(NavigationViewController *)self.navigationController action:#selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.leftBarButtonItem = barBtn;
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:nil];
[self fetchFeed];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat frameWidth = screenRect.size.width - 20;
CGFloat frameHeight = screenRect.size.height - 20;
_collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(10, 10, frameWidth, frameHeight) collectionViewLayout:layout];
[_collectionView setDataSource: self];
[_collectionView setDelegate: self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:_collectionView];
UIRefreshControl * refreshControl = [[UIRefreshControl alloc] init];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Refresh Images"];
[_collectionView addSubview:refreshControl];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.collectionView reloadItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]];
[self.collectionView reloadData];
}
fetchFeed
- (void)fetchFeed
{
NSString *requestString = #"http://www.jameslester.xyz/example.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.articles = jsonObject[#"articles"];
NSLog(#"%#", self.articles);
NSLog(#"Feed Fetched!!!");
dispatch_async(dispatch_get_main_queue(), ^{[self.collectionView reloadData];
});
}];
[dataTask resume];
}
refresh
- (void)refresh:(id)sender
{
[self fetchFeed];
[(UIRefreshControl *)sender endRefreshing];
NSLog(#"Refreshed");
}
Any help will be really appreciated.
Collection View Data Source
#define LABEL_TAG 100001
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UILabel *articleTitle = [cell.contentView viewWithTag:LABEL_TAG];
NSDictionary *article = self.articles[indexPath.row];
if (!articleTitle) {
articleTitle = [[UILabel alloc]initWithFrame:CGRectMake(5, cell.bounds.size.height - cell.bounds.size.height / 2.2, cell.bounds.size.width - 10, cell.bounds.size.height / 2)];
articleTitle.textColor = [UIColor whiteColor];
articleTitle.numberOfLines = 3;
articleTitle.adjustsFontSizeToFitWidth = YES;
articleTitle.tag = LABEL_TAG;
[cell.contentView addSubview:articleTitle];
}
articleTitle.text = article[#"title"];
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: article[#"image"]]];
UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]];
[bgImageView setContentMode:UIViewContentModeScaleAspectFill];
[bgImageView setClipsToBounds:YES];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(0, cell.bounds.size.height - cell.bounds.size.height / 2, cell.bounds.size.width, cell.bounds.size.height/2);
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
//gradient.locations = [NSArray arrayWithObjects:[NSNumber numberWithInt:0.0],[NSNumber numberWithInt:0.5], nil];
[bgImageView.layer insertSublayer:gradient atIndex:0];
cell.backgroundView = bgImageView;
return cell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionView *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 10; // This is the minimum inter item spacing, can be more
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 10;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
int x = screenWidth/2 - 15;
int y = x;
return CGSizeMake(x, y);
}
- (void)collectionView:(UICollectionView *)colView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
NSDictionary *article = self.articles[indexPath.row];
NSURL *URL = [NSURL URLWithString:article[#"url"]];
self.webViewController.title = article[#"title"];
self.webViewController.URL = URL;
[self.navigationController pushViewController:self.webViewController
animated:YES];
}
If NSLog(#"%#", self.articles) works and shows data you have proven that you are getting network data back. Did you set up your UIView as the delegate and the datasource properly? This is usually done at the top of the UIViewController class and looks like this:
class MyClassName: UICollectionViewDataSource {
// Your code here.
}
One way to check if the datasource is set up correctly is to set a breakpoint here
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
print(“This shows that I’m getting called”)
// Your custom code
}
When you call
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
})
this will in turn call cellForItemAtIndexPath to display data. If cellForItemAtIndexPath isn’t called then you have not properly set your UICollectionViewDataSource
Try to this
- (void)fetchFeed {
NSString *requestString = #"http://www.jameslester.xyz/example.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest*req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask*dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.articles = jsonObject[#"articles"];
NSLog(#"%#", self.articles);
NSLog(#"Feed Fetched!!!");
dispatch_async(dispatch_get_main_queue(), ^{
[_collectionView reloadData];
});
}];
[dataTask resume];
}

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.

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];
}
];
}

Fetching data from Facebook multiple times in 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

load image to tableView

i am using table view to display image fron internet and its taking time to load the image..
i tried
dispatch_async(imageQueue_, ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[record imageURLString]];
dispatch_async(dispatch_get_main_queue(), ^{
[[cell imageView] setImage:[UIImage imageWithData:imageData]];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
});
but its loading image slowly and repeating the images till the other images will load in the same row..
is there any way to load all the images in tableview at same time (normally it will happen one by one..)?
Make 2 class with AsyncImageView.h and .m
In AsyncImageView.h
#interface AsyncImageView : UIView
{
NSURLConnection *connection;
NSMutableData *data;
NSString *urlString; // key for image cache dictionary
}
-(void)loadImageFromURL:(NSURL*)url;
- (void)StoreImage:(UIImage*)image String:(NSString *)str;
#end
and In .m
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame])
{
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
- (void)dealloc
{
[connection cancel];
[connection release];
[data release];
[super dealloc];
}
-(void)loadImageFromURL:(NSURL*)url
{
if (connection != nil)
{
[connection cancel];
[connection release];
connection = nil;
}
if (data != nil)
{
[data release];
data = nil;
}
if (imageCache == nil) // lazily create image cache
imageCache = [[ImageCache alloc] initWithMaxSize:2*1024*1024]; // 2 MB Image cache
[urlString release];
urlString = [[url absoluteString] copy];
UIImage *cachedImage = [imageCache imageForKey:urlString];
if (cachedImage != nil) {
if ([[self subviews] count] > 0)
{
[[[self subviews] objectAtIndex:0] removeFromSuperview];
}
UIImageView *imageView = [[[UIImageView alloc] initWithImage:cachedImage] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout]; // is this necessary if superview gets setNeedsLayout?
[self setNeedsLayout];
return;
}
#define SPINNY_TAG 5555
UIActivityIndicatorView *spinny = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinny.backgroundColor=[UIColor whiteColor];
// spinny.tag = SPINNY_TAG;
// spinny.center = self.center;
[spinny startAnimating];
[self addSubview:spinny];
[spinny release];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)incrementalData
{
if (data==nil)
{
data = [[NSMutableData alloc] initWithCapacity:2048];
}
[data appendData:incrementalData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection
{
[connection release];
connection = nil;
UIView *spinny = [self viewWithTag:SPINNY_TAG];
[spinny removeFromSuperview];
if ([[self subviews] count] > 0)
{
[[[self subviews] objectAtIndex:0] removeFromSuperview];
}
UIImage *image = [UIImage imageWithData:data];
[imageCache insertImage:image withSize:[data length] forKey:urlString];
UIImageView *imageView = [[[UIImageView alloc] initWithImage:image] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout];
[self setNeedsLayout];
[data release];
data = nil;
}
And in your class where you are displaying tableview just import AsyncImageView.h and in tableView cellForRowAtIndexPath write
AsyncImageView *asyncImageView = nil;
UIImageView *cellImage = (UIImageView *)[cell viewWithTag:1];
asyncImageView = [[AsyncImageView alloc] initWithFrame:cellImage.frame] ;
[asyncImageView loadImageFromURL:YourImageURL];
asyncImageView.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:asyncImageView];
I have used it and works fine. Hope it'll work for you also.. :)
As Eugene mentioned, use SDWebImage. Makes this stuff so simple.
You load images lazily to the tableview.
Here is the Great Example by Apple.

Resources