My application has a Facebook Login screen, which after login shows a profile picture, username, email, and logout button.
I am trying to figure out how to link the current users profile picture with a UIView or UIImageView (which ever is more applicable, given I used a UIView called FBProfilePictureView) in the main VC called HomeViewController. Here is the code I have for the LoginViewController that has the FB information asked for and returned. I also have it segue to the HomeViewController once the user info has been entered.
LoginViewController.h:
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <FacebookSDK/FacebookSDK.h>
#interface LoginViewController : UIViewController <FBLoginViewDelegate>
#property (weak, nonatomic) IBOutlet FBLoginView *loginButton;
#property (weak, nonatomic) IBOutlet UILabel *lblLoginStatus;
#property (weak, nonatomic) IBOutlet UILabel *lblUsername;
#property (weak, nonatomic) IBOutlet UILabel *lblEmail;
#property (weak, nonatomic) IBOutlet FBProfilePictureView *profilePicture;
#property (strong, nonatomic) IBOutlet UIImageView *loginwallpaper;
#property (strong, nonatomic) IBOutlet UIImageView *loggedinwallpaper;
#property (strong, nonatomic) IBOutlet UIImageView *FBlogin;
#property (strong, nonatomic) IBOutlet UIImageView *FBlogout;
#end
and here is the LoginViewController.m
#import "LoginViewController.h"
#interface LoginViewController ()
- (void)toggleHiddenState:(BOOL)shouldHide;
#end
#implementation LoginViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self toggleHiddenState:YES];
self.lblLoginStatus.text = #"";
self.loginButton.readPermissions = #[#"public_profile", #"email"];
self.loginButton.layer.cornerRadius = 0;
[self.loginButton.layer setBorderWidth:0.0f];
self.loginButton.delegate = self;
// Do any additional setup after loading the view.
}
-(void)toggleHiddenState:(BOOL)shouldHide{
self.lblUsername.hidden = shouldHide;
self.lblEmail.hidden = shouldHide;
self.profilePicture.hidden = shouldHide;
self.loggedinwallpaper.hidden = shouldHide;
self.FBlogout.hidden = shouldHide;
}
-(void)toggleUnhiddenState:(BOOL)shouldShow{
self.loggedinwallpaper.hidden = NO;
}
-(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView{
self.lblLoginStatus.text = #"";
[self toggleHiddenState:NO];
[self toggleUnhiddenState:YES];
}
-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView{
self.lblLoginStatus.text = #"";
[self toggleHiddenState:YES];
}
-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user{
NSLog(#"%#", user);
self.profilePicture.profileID = user.objectID;
self.lblUsername.text = user.name;
self.lblEmail.text = [user objectForKey:#"email"];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UITabBarController *tabcontroller = (UITabBarController *)[storyboard instantiateViewControllerWithIdentifier:#"HomeViewController"];
[self presentViewController:tabcontroller animated:YES completion:nil];
}
-(void)loginView:(FBLoginView *)loginView handleError:(NSError *)error{
NSLog(#"%#", [error localizedDescription]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
All of the other questions posted on here have not really helped me - they have been too vague.
If someone could just show me how to connect this profile picture to a UIImageView or UIView in the HomeViewController that would be awesome! I know this is easy and I'm just frustrated that this is giving me such an problem
(I know that I need to use the prepareForSeuge method I am just not sure on the syntax of how to accomplish this.)
It will help you. Go to HomeViewController.xib and here put UIView by dragging it.
Now, select that view and on the right side of XCode click on third tab that is Identity Inspector. Here set the class name as FBProfilePictureView then try.
If you want to diplay image in FBProfilePictureView then
Xib/StoryBoard -> Identity Inspector -> class name -> FBProfilePictureView
-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user{
NSLog(#"%#", user);
self.profilePicture.profileID = user.id;
}
If you want to display in imageview
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);
dispatch_async( queue, ^{
// Load UImage from URL
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://graph.facebook.com/%#/picture?width=200&height=200", user.id]];
NSData *data = [NSData dataWithContentsOfURL:url];
// Then to set the image it must be done on the main thread
dispatch_sync( dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:data];
yourImageView.image = image
image = nil;
});
});
Related
Trying to create an image picker with a tap gesture, so when the default picture is tapped it allows the user to pick an image from the device's photo library. For some reason when I click the view in the iOS simulator it simply doesn't do anything and I can't figure out why.
This is what I have so far. I'm pretty new to Objective-C
ViewController.m :
#import "ViewController.h"
interface ViewController ()
#property (weak, nonatomic) IBOutlet UITextField *nameField;
#property (weak, nonatomic) IBOutlet UITextField *brandField;
#property (weak, nonatomic) IBOutlet UITextField *priceField;
#property (weak, nonatomic) IBOutlet UITextField *additionalNotesField;
#property (weak, nonatomic) IBOutlet UIButton *addItem;
#property (weak, nonatomic) IBOutlet UIButton *cancelAdditem;
#property (weak, nonatomic) IBOutlet UIImageView *toyImage;
- (IBAction)imageSelect:(UITapGestureRecognizer *)sender;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_nameField.delegate = self;
_brandField.delegate = self;
_priceField.delegate = self;
_additionalNotesField.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
-(BOOL) textFieldShouldReturn:(UITextField *) textField {
textField.resignFirstResponder;
return true;
}
-(void) textFieldDidEndEditing:( UITextField *) textField {
_nameField.text = textField.text;
_brandField.text = textField.text;
_priceField.text = textField.text;
_additionalNotesField.text = textField.text;
}
- (IBAction)imageSelect:(UITapGestureRecognizer *)sender {
// Hide the keyboard
_nameField.resignFirstResponder;
_brandField.resignFirstResponder;
_priceField.resignFirstResponder;
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init]; // Creates image picker
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // Source for picker is saved photos. Only allow photos to be picked, not taken
// Make sure the picker is notified when the user picks an image
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:true completion:nil];
}
// UIImagePickerControllerDelegete
-(void) imagePickerDidCancel:(UIImagePickerController *) imagePicker {
[self dismissViewControllerAnimated:true completion:nil]; // Dimiss the picker if the user canceled
}
-(void) imagePicker:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage* selectedImage = info[UIImagePickerControllerOriginalImage];
_toyImage.image = selectedImage; // Set the image view to display the selected image
// Dimiss the picker
[self dismissViewControllerAnimated:true completion:nil];
}
#end
As Larme said, I needed to add this line:
_toyImage.userInteractionEnabled = YES;
Im following this tutorial:
http://www.raywenderlich.com/1845/ios-tutorial-how-to-create-a-simple-iphone-app-tutorial-part-2
I get the following errors:
1.Property implementation must have its declaration in interface "RWTDetailViewController"
2.Property "data" not found on object of type "id"
Here is my code:
#import "RWTScaryBugDoc.h"
#import "RWTScaryBugData.h"
#import "RWTUIImageExtras.h"
#import "RWTDetailViewController.h"
#interface RWTDetailViewController ()
- (void)configureView;
#end
#implementation RWTDetailViewController
#pragma mark - Managing the detail item
#synthesize picker = _picker;
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
self.rateView.notSelectedImage = [UIImage imageNamed:#"shockedface2_empty.png"];
self.rateView.halfSelectedImage = [UIImage imageNamed:#"shockedface2_half.png"];
self.rateView.fullSelectedImage = [UIImage imageNamed:#"shockedface2_full.png"];
self.rateView.editable = YES;
self.rateView.maxRating = 5;
self.rateView.delegate = self;
if (self.detailItem) {
self.titleField.text = self.detailItem.data.title;
self.rateView.rating = self.detailItem.data.rating;
self.imageView.image = self.detailItem.fullImage;
}
}
- (IBAction)titleFieldTextChanged:(id)sender
{
self.detailItem.data.title = self.titleField.text;
}
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#pragma mark RWTRateViewDelegate
- (void)rateView:(RWTRateView *)rateView ratingDidChange:(float)rating
{
self.detailItem.data.rating = rating;
}
- (IBAction)addPictureTapped:(id)sender {
if (self.picker == nil) {
self.picker = [[UIImagePickerController alloc] init];
self.picker.delegate = self;
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.picker.allowsEditing = NO;
}
[self presentViewController:_picker animated:YES completion:nil];
}
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[self dismissViewControllerAnimated:YES completion:nil];
UIImage *fullImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *thumbImage = [fullImage imageByScalingAndCroppingForSize:CGSizeMake(44, 44)];
self.detailItem.fullImage = fullImage;
self.detailItem.thumbImage = thumbImage;
self.imageView.image = fullImage;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
- (BOOL)shouldAutorotateToInterfaceOrientation
{
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
When I move my #synthesize into the interface-declaration, I the the following error: "Illegal interface qualifier"
Can anyone help me?
Here is my .h-file:
#import <UIKit/UIKit.h>
#import "RWTRateView.h"
#interface RWTDetailViewController : UIViewController <UITextFieldDelegate, RWTRateViewDelegate, UIImagePickerControllerDelegate, UINavigationBarDelegate>
#property (strong, nonatomic) id detailItem;
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#property (weak, nonatomic) IBOutlet RWTRateView *rateView;
#property (weak, nonatomic) IBOutlet UITextField *titleField;
#property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
#property (strong, nonatomic) UIImagePickerController *picker;
- (IBAction)addPictureTapped:(id)sender;
- (IBAction)titleFieldTextChanged:(id)sender;
#end
Error description is self explanatory, you need to declare picker as a property in interface(.h) file before you move to implementation(.m) file and synthesize it. However you don't need to synthesize properties anymore but if you do that is also fine.
One more thing, you missed the part from tutorial in which writer has declared this property in .h file already. You can have a look again or add this line to RWTDetailViewController.h
#property (strong, nonatomic) UIImagePickerController *picker;
EDIT
For second error you are declaring detailItem as an object of type id, however writer is using a custom class RWTScaryBugDoc in which he should be having a property named data. That's why you are getting the error as property data doesn't belong to id type. You may want to download the sample code at the end of tutorial and cross check the missing points.
You just need to declare your property first. So in the interface (h file or top of your m file), add:
#property (nonatomic, strong)UIImagePickerController *picker;
The #synthetise need to stay in the implementation.
You declare self.detailItem as Id. Id is no class and so it has no attribute, but you try to access self.detailItem.data.... This is not possible.
I can't help you to fix this, because there are so many logical erros in your code, that 99% of it makes no sense for me.
I haven't found a similar question that could answer my question.
My Question is: Why can't I access a UILabel from another class after the dissmissViewController?
Here is my Code:
ClassA.h:
#interface ClassA : UIViewController {
UILabel *_ErrorLabel;
UIActivityIndicatorView *_acIn1;
}
#property (weak, nonatomic) IBOutlet UILabel *ErrorLabel;
#property (weak, nonatomic) IBOutlet UIActivityIndicatorView *acIn1;
ClassA.m:
shouldPerformSegue, prepareForSegue and statusBarStyle Methods
ClassB.h:
- (IBAction)dismiss;
ClassB.m:
- (IBAction)dismiss
{
[self dismissViewControllerAnimated:YES completion:^{
ClassA *login = [[ClassA alloc] init];
[[login ErrorLabel] setText:#"Please use login."];
[[login acIn1] stopAnimating];
[[login acIn1] setHidesWhenStopped:YES];
[[login acIn1] setHidden:YES];
}];
}
Here is my Code I really hope somebody can help me: I AM ABOUT TO GIVE UP I DON'T KNOW WHY THIS WON'T WORK!
Thanks for your help.
~Markus
Edit1:
I have a ViewController ClassA that contains two text fields and when you click on login you come to a TabBarController where one tab contains the ClassB ViewController and in the ClassB ViewController there is a logout button --> dismiss and when you click this button you should come to the ClassA ViewController AND the ErrorLabel Text should change.
Complete Class: A --> LoginViewControler.h
#import <UIKit/UIKit.h>
#import "ShowProfileViewController.h"
#interface LoginViewController : UIViewController <ShowProfileViewControllerDelegate> {
UILabel *_ErrorLabel;
UIActivityIndicatorView *_acIn1;
}
#property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
#property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
#property (weak, nonatomic) IBOutlet UILabel *ErrorLabel;
#property (weak, nonatomic) IBOutlet UIActivityIndicatorView *acIn1;
#end
Complete Class: A --> LoginViewController.m
#import "LoginViewController.h"
#import "NewsNavigationController.h"
#import "TabViewController.h"
#interface LoginViewController () <UITextFieldDelegate>
#end
#implementation LoginViewController
#synthesize usernameTextField;
#synthesize passwordTextField;
#synthesize ErrorLabel;
#synthesize acIn1;
- (void)viewDidLoad
{
[super viewDidLoad];
[usernameTextField setDelegate:self];
[passwordTextField setDelegate:self];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
if([identifier isEqualToString:#"login"])
{
[acIn1 startAnimating];
[acIn1 setHidden:NO];
if([self login]){
return YES;
} else {
[self showErrorMessage:#"Data not correct!"];
[acIn1 stopAnimating];
[acIn1 setHidesWhenStopped:YES];
[acIn1 setHidden:YES];
return NO;
}
}
else {
[acIn1 stopAnimating];
[acIn1 setHidesWhenStopped:YES];
[acIn1 setHidden:YES];
return NO;
}
}
- (void)showErrorMessage:(NSString *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!"
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (BOOL)login
{
NSString *usernameS = usernameTextField.text;
NSString *passwordS = passwordTextField.text;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://localhost:8888/login.php?username=%#&password=%#", usernameS, passwordS]]];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *loginDic = [jsonDictionary objectForKey:#"login"];
NSString *ErrorString = [loginDic objectForKey:#"returnString"];
NSLog(#"[+] Login: %#", ErrorString);
if ([ErrorString isEqualToString:#"Success"]){
ErrorLabel.text = #"Login";
return YES;
}
else {
ErrorLabel.text = ErrorString;
return NO;
}
}
- (void)didDismissViewController
{
[ErrorLabel setText:#"Bitte benutzen Sie den Login."];
[acIn1 stopAnimating];
[acIn1 setHidesWhenStopped:YES];
[acIn1 setHidden:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)inSegue sender:(id)inSender
{
if([inSegue.identifier isEqualToString:#"login"])
{
ShowProfileViewController *vc = [[ShowProfileViewController alloc] init];
vc.delegate = self;
TabViewController *tabViewController = inSegue.destinationViewController;
NewsNavigationController *theController = [[tabViewController viewControllers] objectAtIndex:0];
[self presentViewController:vc animated:YES completion:nil];
}
}
#end
Complete Class: B --> ShowProfileViewController.h
#import <UIKit/UIKit.h>
#protocol ShowProfileViewControllerDelegate
- (void)didDismissViewController;
#end
#interface ShowProfileViewController : UIViewController
#property (nonatomic, assign) id<ShowProfileViewControllerDelegate> delegate;
- (IBAction)dismiss;
#end
Complete Class: B --> ShowProfileViewController.m
#import "ShowProfileViewController.h"
#import "LoginViewController.h"
#interface ShowProfileViewController ()
#end
#implementation ShowProfileViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)viewWillAppear:(BOOL)inAnimated
{
[super viewWillAppear:inAnimated];
}
- (IBAction)dismiss
{
[self dismissViewControllerAnimated:YES completion:^{
[self.delegate didDismissViewController];
}];
}
#end
This doesn't work because inside your completion block, you're creating a new instance of your LoginViewController, and setting its text. What you should be actually doing is setting the text of the existing LoginViewController, that should appear after dismissing ShowProfileViewController
In order to achieve your desired behaviour, you can use the delegation pattern. If you're not familiar with this technique, it'd be very important to learn. It's is used all over the place in iOS and Mac OS X development.
The code below might require some tweaking on your side.
In ShowProfileViewController.h, add before #interface:
#protocol ShowProfileViewControllerDelegate
- (void)didDismissViewController
#end
Also, add the following property declaration to ShowProfileViewController:
#property (nonatomic, assign) id<ShowProfileViewControllerDelegate> delegate;
Then, change LoginViewController.h so it looks like
#import "ShowProfileViewController.h"
#interface LoginViewController : UIViewController <ShowProfileViewControllerDelegate> {
UILabel *_ErrorLabel;
UIActivityIndicatorView *_acIn1;
}
#property (weak, nonatomic) IBOutlet UILabel *ErrorLabel;
#property (weak, nonatomic) IBOutlet UIActivityIndicatorView *acIn1;
Now, in ShowProfileViewController.m, replace the code in the dismiss method so it looks like the following:
- (IBAction)dismiss
{
[self dismissViewControllerAnimated:YES completion:^{
[self.delegate didDismissViewController];
}];
}
In LoginViewController.m, add the following method:
- (void)didDismissViewController
{
[[self ErrorLabel] setText:#"Please use login."];
[[self acIn1] stopAnimating];
[[self acIn1] setHidesWhenStopped:YES];
[[self acIn1] setHidden:YES];
}
And finally, you need to set the delegate property in you ShowProfileViewController to point to the LoginViewController instance. Find in LoginViewController.m in which part of your code you create and present the ShowProfileViewController View Controller and set the delegate property to self. If you're using storyboards, you should do it inside prepareForSegue:.
ClassA *login = [[ClassA alloc] init];
is creating a completly new instance.Not the one you used for coming to class B
I have a project that displays a feed of statuses similar to other social networks. Each feed item has several button that do different things. 1 of the buttons opens a new viewcontroller that displays the comments that have been posted on a particular status. When this button is clicked and the view controller is opened i would like it to be a push segue so that their is a back button and the user can navigate back to the feed.
When this button is clicked and the new vc is launched some unique data about the particular status/cell being clicked needs to be sent to the "comments vc ". Where would the code for doing this go?
CUSTOM CELL .H
#import <UIKit/UIKit.h>
#interface FeedItemCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *DefaultImg;
#property (weak, nonatomic) IBOutlet UILabel *NameLabel;
#property (weak, nonatomic) IBOutlet UILabel *StatusLabel;
#property (weak, nonatomic) IBOutlet UILabel *timeLabel;
#property (nonatomic, copy) NSString *msg_id;
#property (nonatomic, copy) NSString *status;
#property (nonatomic, weak) IBOutlet UIButton* commentButton;
#property (nonatomic, weak) IBOutlet UIButton* bumpButton;
#property (strong, nonatomic) id delegate;
-(IBAction)viewComments:(id)sender;
-(IBAction)bump:(id)sender;
#end
#protocol CustomCellProtocol <NSObject>
- (void)EBCellPressed:(NSString *)cellName;
CUSTOM CELL .M
#import "FeedItemCell.h"
#import "CommentsViewController.h"
#import "NSDate+TimeAgo.h"
#interface FeedItemCell() <WYPopoverControllerDelegate>
{
}
- (IBAction)open:(id)sender;
- (void)close:(id)sender;
#end
#implementation FeedItemCell
#synthesize commentButton;
- (instancetype)initWithDelegate:(id)delegate {
self = [super init];
if (self) {
self.delegate = delegate;
// Initialization code
}
return self;
}
-(IBAction)bump:(id)sender{
[self.delegate EBCellPressed:#"NAME"];
}
- (IBAction)open:(id)sender
{
}
#end
publicFeed . M
#import "PublicFeedViewController.h"
#import "FeedItemCell.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "InboxDetailViewController.h"
#import "SWRevealViewController.h"
#import "CommentsViewController.h"
#import "NSDate+TimeAgo.h"
#interface PublicFeedViewController (){
NSArray *NameLabel;
NSArray *StatusLabel;
NSMutableArray *feedArray;
}
#end
#implementation PublicFeedViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//The below code prompts the user for push notifications. If allowed, code in AppDelegate takes over and stores the token.
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
// Do any additional setup after loading the view.
self.FeedTable.dataSource=self;
self.FeedTable.delegate=self;
// Set the side bar button action. When it's tapped, it'll show up the sidebar.
_sidebarButton.target = self.revealViewController;
_sidebarButton.action = #selector(revealToggle:);
// Set the gesture
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
[manager POST:#"www" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(#"JSON: %#", responseObject);
self->feedArray = [responseObject objectForKey:#"feed"];
[self.FeedTable reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return feedArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *CellIdentifier=#"Cell";
FeedItemCell *Cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!Cell){
Cell = [[FeedItemCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSLog(#"FEED ARRAY: %#", self->feedArray);
NSDictionary *tempDictionary= [self->feedArray objectAtIndex:indexPath.row];
// Display recipe in the table cell
NSString *thumb_img = [tempDictionary objectForKey:#"thumb_img"];
NSString *thumb_path=#"http://buhzhyve.com/CI_REST_LOGIN/UPLOADS/thumbs/";
NSString *thumb_url = [thumb_path stringByAppendingString:thumb_img];
Cell.NameLabel.text=[tempDictionary objectForKey:#"first_name"];
Cell.StatusLabel.text=[tempDictionary objectForKey:#"message"];
Cell.msg_id=[tempDictionary objectForKey:#"msg_id"];
//Cell.status=[tempDictionary objectForKey:#"message"];
Cell.StatusLabel.lineBreakMode=0;
Cell.StatusLabel.numberOfLines=0;
NSString *commentCount = [tempDictionary objectForKey:#"comment_count"];
NSString *commentButtonText =[NSString stringWithFormat:#"Comments ( %# )",commentCount];
[Cell.commentButton setTitle:commentButtonText forState: UIControlStateNormal];
NSString *bumpCount = [tempDictionary objectForKey:#"bump_count"];
NSString *bumpButtonText =[NSString stringWithFormat:#"Bumps ( %# )",bumpCount];
[Cell.bumpButton setTitle:bumpButtonText forState: UIControlStateNormal];
//[Cell.StatusLabel sizeToFit];
NSString *created_string=[tempDictionary objectForKey:#"created"];
double created_double = created_string.doubleValue;
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:created_double];
NSString *ago = [date timeAgo];
Cell.timeLabel.text=ago;
//Cell.DefaultImg.image = [UIImage imageNamed:#"buhz_mini_logo.png"];
[Cell.DefaultImg setImageWithURL:[NSURL URLWithString:thumb_url]
placeholderImage:[UIImage imageNamed:#"buhz_mini_logo.png"]];
return Cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Ideally you should do lazy loading so that instead of creating a new textView each time, you just reuse the same one.
UITextView *temp = [[UITextView alloc] initWithFrame:CGRectMake(82, 26, self.FeedTable.frame.size.width, 18)]; //This initial size doesn't matter
NSDictionary *tempDictionary= [self->feedArray objectAtIndex:indexPath.row];
NSString *status = [tempDictionary objectForKey:#"message"];
temp.font =[UIFont fontWithName:#"System" size:12];
temp.text = status;
CGFloat textViewWidth = 218;
CGRect tempFrame = CGRectMake(82,26,textViewWidth,18); //The height of this frame doesn't matter.
CGSize tvsize = [temp sizeThatFits:CGSizeMake(tempFrame.size.width, tempFrame.size.height)]; //This calculates the necessary size so that all the text fits in the necessary width.
//Add the height of the other UI elements inside your cell
return tvsize.height + 70;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"commentSegue"]) {
}
}
#end
publicfeed .h
#import <UIKit/UIKit.h>
#interface PublicFeedViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *FeedTable;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;
- (IBAction)addItem;
#end
So assuming that you're creating this button in code, this is how you could handle this.
This first line tells the button that when it's pressed, it needs to call this specific selector/method sent as the action.
[button addTarget:self action:#selector(showNextViewController) forControlEvents:UIControlEventTouchUpInside];
Then you would create this method in the same class.
- (void) showNextViewController
{
NewViewController *newViewController = [[NewViewController alloc] init]; //Edit this line of course to fit for your situation. I'm not sure if you're loading from an XIB or from a Storyboard, or neither.
newViewController.someVariable = someVariable;
newViewController.someOtherVariable = someOtherVariable;
[[[[[UIApplication sharedApplication] delegate] window] rootViewController].navigationController pushViewController:view animated:YES];
}
This will send the necessary data to the new view controller, and it will also display the new view on the screen with a back button.
Hope this works!
1. Ok so lets pretend this is your custom cell class.
in your .h file of the custom cell you need to add a protocol.
#import <UIKit/UIKit.h>
#interface CustomCell : UIView
#property (strong, nonatomic) id delegate; //this is used for sending messages out of the custom cell
//init
- (id)initWithFrame:(CGRect)frame andCatName:(NSString *)name andDelegate:(id)delegate;
#end
#protocol CustomCellProtocol <NSObject>
-(void)customCellSelected:(NSString *)cellName;
#end
what we actually did is something like creating a custom event that the class can throw out and everyone who subscribes to that can run a method when customCellSelected is thrown.
2. now when you create each custom cell with the init method you need to provide a delegate which kind of points to which class should the custom cell transfer the call to customCellSelected so in the init method you set that delegate.
- (id)initWithFrame:(CGRect)frame andDelegate:(id)delegate {
self = [super initWithFrame:frame];
if (self) {
self.delegate = delegate; //setting which class should be called when calling protocol methods.
// Your initialization code
}
return self;
}
3. now in your .m file of the custom cell, when the user presses your button and you enter your method , let it be buttonPressed
- (IBAction) buttonPressed:(id)sender {
[self.delegate customCellSelected:#"THE CELL'S NAME"]; // calling the protocol method.
}
now the call to the delegate method should be transferred to the vc because when you create the custom cell you use initWithFrame:(CGRect)frame andDelegate:(id)delegate and you transfer self as the delegate , so when [self.delegate customCellSelected:#"THE CELL'S NAME"]; is called it is actually called on the vc.
4. this is how you create the custom cell in the vc:
customCell *tempView = [[customCell alloc] initWithFrame:CGRectMake(X, Y, Width, Height) andDelegate:self]; // here you set the vc as the delegate
5.and now all you have to do is add the method customCellSelected to your vc code so it can called when the customCell is calling it.
- (void)customCellSelected:(NSString *)cellName {
self.selectedCell = cellName;
[self performSegueWithIdentifier:#"SelectedCell" sender:self];
}
6.then add this in the vc:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"SelectedCell"]) {
LevelSelectViewController *levelSelectViewController = (LevelSelectViewController *)segue.destinationViewController;
levelSelectViewController.cellName = self.selectedCell;
}
}
7.only thing you have to remember is to create a segue from your first vc to the second like this:
Can someone please see where I am going wrong with this?
I have a object called Object with a single NSString property.
I then have a MainViewController with a button on it. The button is created programatically and added at runtime.
When yo click this button, it is supposed to set the value of the Object proper to a String, and pass this to the next ViewController.
I manage to set the value of the Object property, but when I call that value to pass it, it is set to null. I have tried many different solutions but nothing seems to work. Can anyone see where my problem lies? I have added all the relevant code below
Object.h
#interface Object : NSObject
#property (nonatomic, strong) NSString *content;
Object.m
#import "Object.h"
#implementation Object
#synthesize content;
Then in MianViewController I create the button and set value of Object property
MainViewController.h
#interface MainViewController : UIViewController
#property (nonatomic, strong) UIButton *myButton;
MainViewController.m
#import "MainViewController.h"
#import "SecondaryViewController.h"
#import "Object.h"
.
.
#synthesize myButton;
- (void)viewDidLoad
{
[super viewDidLoad];
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.tag = 1;
myButton.frame = CGRectMake(20, 140, 280.f, 40.f);
UIImage *airButton = [UIImage imageNamed:#"gettingHereByAirButton.png"];
[myButton setBackgroundImage:airButton forState:UIControlStateNormal];
[self.view addSubview:myButton];
[myButton addTarget:self action:#selector(myButtonClicked) forControlEvents:UIControlEventTouchUpInside];
}
- (void) myButtonClicked
{
[self performSegueWithIdentifier:#"mySegue" sender:self];
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSLog(#"Getting Here...");
Object *object = [[Object alloc] init];
object.content = #"This is the content of the Object";
NSLog(#"Content of Object Set To: %#", object.content);
SecondaryViewController *vc;
vc.object = object;
NSLog(#"Object: %#", object);
NSLog(#"Object.content: %#", object.content);
NSLog(#"ViewController.object.content: %#", vc.object.content);
NSLog(#"Just Did Stuff...");
}
And the SecondaryViewController where the label should be set to that of the Object String
SecondaryViewController.h
#import "Object.h"
#interface SecondaryViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *contentLabel;
#property (nonatomic, strong) Object *object;
SecondaryViewController.m
#synthesize object;
#synthesize contentLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"Content of Object: %#", object.content);
self.contentLabel.text = object.content;
}
And finally a screen grab of my NSLog when the app is running HERE
SecondaryViewController *vc;
Should be
SecondaryViewController *vc = (SecondaryViewController *)segue.destinationViewController;