open link from UIWebView into Safari (iphone) - iphone

ok rather than try to explain my problem in text, watch this little video i recorded
http://www.youtube.com/watch?v=fwb55jnZI6w
and here is the code for the detail view controller (the page where the webview is)
detailViewController.h
#import <UIKit/UIKit.h>
#import "MWFeedItem.h"
#interface DetailViewController : UIViewController <UIWebViewDelegate> {
MWFeedItem *item;
NSString *summaryString;
IBOutlet UILabel *titleLabel;
IBOutlet UIWebView *contentLabel;
//IBOutlet UILabel *dateLabel;
IBOutlet UIScrollView *textScroller;
}
#property (nonatomic, retain) MWFeedItem *item;
#property (nonatomic, retain) NSString *summaryString;
#property (nonatomic, retain) IBOutlet UILabel *titleLabel;
#property (nonatomic, retain) IBOutlet UIWebView *contentLabel;
#end
detailViewController.m
#import "DetailViewController.h"
#import "NSString+XMLEntities.h"
typedef enum { SectionHeader, SectionDetail } Sections;
typedef enum { SectionHeaderTitle, SectionHeaderDate, SectionHeaderURL } HeaderRows;
typedef enum { SectionDetailSummary } DetailRows;
#implementation DetailViewController
#synthesize item, summaryString, titleLabel, contentLabel;
- (BOOL)webView:(UIWebView *)contentLabel shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {
NSURL *requestURL = [ [ request URL ] retain ];
// Check to see what protocol/scheme the requested URL is.
return [ [ UIApplication sharedApplication ] openURL: [ requestURL autorelease ] ];
return NO;
// Auto release
[ requestURL release ];
// If request url is something other than http or https it will open
// in UIWebView. You could also check for the other following
// protocols: tel, mailto and sms
}
- (void)viewDidLoad {
[super viewDidLoad];
/*if (item.date) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
self.dateString = [formatter stringFromDate:item.date];
[formatter release];
}*/
if (item.summary) {
self.summaryString = [[[item.summary stringByStrippingTags] stringByRemovingNewLinesAndWhitespace] stringByDecodingXMLEntities];
}
titleLabel.text = item.title ? item.title : #"[No Title]";
[titleLabel setBackgroundColor:[UIColor clearColor]];
//dateLabel.text = dateString ? dateString : #"[No Date]";
// Summary
NSString *HTMLData = summaryString;
[contentLabel loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:#"http://www.feed43.com/1515171705611023.xml"]]];
//Calculate the expected size based on the font and linebreak mode of your label
//CGSize maximumLabelSize = CGSizeMake(280,9999);
//CGSize expectedLabelSize = [summaryString sizeWithFont:contentLabel.font
//constrainedToSize:maximumLabelSize
//lineBreakMode:contentLabel.lineBreakMode];
//adjust the label the the new height.
//CGRect newFrame = contentLabel.frame;
//newFrame.size.height = expectedLabelSize.height;
//contentLabel.frame = newFrame;
[textScroller setCanCancelContentTouches:NO];
[textScroller setContentSize:CGSizeMake(320, 500)];
textScroller.indicatorStyle = UIScrollViewIndicatorStyleBlack;
textScroller.scrollEnabled = YES;
textScroller.clipsToBounds = YES;
//return titleLabel;
//return dateLabel;
//return contentLabel;
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
//return (interfaceOrientation == UIInterfaceOrientationPortrait);
return NO;
}
- (void)dealloc {
[super dealloc];
}
#end
note: even though it says "contentLabel" it is a UIWebView. it is left over from old versions
Thanks!

Implement -(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
Then you can do something like this :
NSURL* url = [request URL];
if (UIWebViewNavigationTypeLinkClicked == navigationType)
{
[[UIApplication sharedApplication] openURL:url];
return NO;
}

Related

Pass string from UITableView to UIView in iOS

I want to pass 2 string selected from UITableview (CompleteView) to new UIView (DetailView)
This is my code:
In CompleteView.h()
#property (nonatomic, retain) NSString *memoString;
#property (nonatomic, retain) NSString *previewString;
In Completeview.m()
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
previewString = [PreviewArray objectAtIndex:indexPath.row];
NSLog(#"Preview string %#",previewString);
memoString = [MemoArray objectAtIndex:indexPath.row];
NSLog(#"Memo string %#",memoString);
DetailView *detailAlert = [[DetailView alloc] initWithFrame:CGRectMake(10, 40, 300, 300)];
detailAlert.strPreview =previewString ;
detailAlert.strMemo = memoString;
[self.view addSubview:detailAlert];
[detailAlert show];
[detailAlert release];
}
In DetailView()
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:strPreview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
return self;
}
In DetailView.h
#property (nonatomic, retain) NSString* strMemo;
#property (nonatomic, retain) NSString* strPreview;
When run, previewString not send to DetailView. I'm debug, when run strPreview and strMemo in DetailView is 0x00000. Thanks in advance
You can pass custom Initialisers like below . If you wish you can add one parameter
to custom Initialisers
In CompleteView.h()
#property (nonatomic, retain) NSString *memoString;
#property (nonatomic, retain) NSString *previewString;
In Completeview.m()
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
previewString = [PreviewArray objectAtIndex:indexPath.row];
NSLog(#"Preview string %#",previewString);
memoString = [MemoArray objectAtIndex:indexPath.row];
NSLog(#"Memo string %#",memoString);
DetailView *detailAlert = [[DetailView alloc] initWithFrame:CGRectMake(10, 40, 300, 300) andPreviewstring:previewString];
detailAlert.strPreview =previewString ;
detailAlert.strMemo = memoString;
[self.view addSubview:detailAlert];
[detailAlert show];
[detailAlert release];
}
In DetailView()
- (id)initWithFrame:(CGRect)frame andPreviewstring:(NSString *)stPreview
{
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:strPreview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
return self;
}
In DetailView.h
#property (nonatomic, retain) NSString* strMemo;
#property (nonatomic, retain) NSString* strPreview;
- (id)initWithFrame:(CGRect)frame andPreviewstring:(NSString *)stPreview;
try this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
previewString = [PreviewArray objectAtIndex:indexPath.row];
NSLog(#"Preview string %#",previewString);
memoString = [MemoArray objectAtIndex:indexPath.row];
NSLog(#"Memo string %#",memoString);
DetailView *detailAlert = [[DetailView alloc] initWithFrame:CGRectMake(10, 40, 300, 300)];
detailAlert.strPreview =previewString ;
detailAlert.strMemo = memoString;
[detailAlert createWebView];
[self.view addSubview:detailAlert];
[detailAlert show];
[detailAlert release];
}
write code for string allocation
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
//add following two lines
strPreview = [[NSString alloc] init];
strMemo = [[NSString alloc] init];
//........
return self;
}
-(void) createWebView {
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:strPreview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
}
The problem here is you are setting two properties in detail view after initializing DetailView. But you are trying to use a property values within the initializer which are yet to be set.
As I can see there are two options you can try out.
Write another initializer which accept these two properties. So that you can use those two properties in that initializer.
(id)initWithFrame:(CGRect)frame strMemo:(NSString *)memo strPreview:(NSString *)preview {
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:preview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
return self;
}
Or else you can extract the logic in the current initializer and put them in to a separate method which you can called after setting two properties from the CompleteView.

How to copy an array to appdelegate array and then retrieve it again elsewhere?

I want to store the array of urls in my appdelegate array i.e. logoArray from myMutableArray and then use it in other viewcontroller, but i am uable to copy as may be i am doing shallow copy, i have tried othes ways also like initwithArray:copyItems.
code:-
#class FirstViewController;
#interface AppDelegate_iPhone : NSObject <UIApplicationDelegate> {
UIWindow *window;
FirstViewController *viewController;
NSMutableArray *logoArray;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) NSMutableArray *logoArray;
#end
// NO initialization of logoArra is done in .M file
#class AppDelegate_iPhone;
#interface FirstViewController : UIViewController {
NSMutableArray *array;
NSString *logoString;
AppDelegate_iPhone *appDelegate;
}
#end
#implementation FirstViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
int x=5,y=10;
UIApplication *app = [UIApplication sharedApplication];
appDelegate=app.delegate;
NSLog(#" Array ====== %d",[appDelegate.logoArray count]);
array = [[NSMutableArray alloc]initWithArray:appDelegate.logoArray];
NSLog(#"array at 0 ===== %#",[array objectAtIndex:0]);
for (int i=0; i<[array count]; i++) {
logoString = [array objectAtIndex:i];
NSLog(#"%#",logoString);
UIImage *imageFromUrl = [UIImage imageWithContentsOfFile:[NSURL fileURLWithPath:logoString]];
UIImageView *imgView = [[UIImageView alloc] initWithImage:imageFromUrl];
[imgView setFrame:CGRectMake(x, y, 196, 90)];
[self.view addSubview:imgView];
// UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onTapImage)];
// [imgView addGestureRecognizer:tgr];
// [tgr release];
//Do the rest of your operations here, don't forget to release the UIImageView
x = x + 200;
// [imgView release];
}
}
#class Litofinter,AppDelegate_iPhone;
#interface ParsingViewController : NSObject<NSXMLParserDelegate> {
NSString *myString;
NSMutableArray *myMutableArray;
Litofinter *obj;
NSString *currentElement;
AppDelegate_iPhone *appDelegate;
}
#property(nonatomic, retain) NSString *myString;
#property(nonatomic, retain) NSArray *myMutableArray;
#end
#import "ParsingViewController.h"
#import "Litofinter.h"
#import "AppDelegate_iPhone.h"
#implementation ParsingViewController
#synthesize myMutableArray, myString;
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
myMutableArray = [[NSMutableArray alloc]init];
}
// I have parsed here my XML and array gets stored in myMutableArray
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
UIApplication *app = [UIApplication sharedApplication];
appDelegate=app.delegate;
appDelegate.logoArray = [[NSMutableArray alloc]initWithArray:myMutableArray];
// NSLog(#"appDelegate.logoArray count %d",[appDelegate.logoArray count]);
for (Litofinter *lito in appDelegate.logoArray) {
NSLog(#"Array Elements :----- %#",lito.cLogo);
}
}
Personally I wouldn't create an array in a viewcontroller and then store it in the appdelegate. I'd be more inclined to create a model for the data ( a class that gets and stores the data and provides it to the view controllers).
this thread may help:
iPhone: Using a NSMutableArry in the AppDelegate as a Global Variable

When manual reload viewDidLoad how clear memory and using viewDidUnload

Help find out how to solve the problem using the memory in my application, may have another way to implement my task.
Have the following code:
Constants.h
#import <Foundation/Foundation.h>
extern NSString * const ITEM;
extern NSString * const TITLE;
extern NSString * const IMAGE;
extern NSString * const DESCRIPTION;
extern NSString * const TEXT;
#interface Constants : NSObject
{
}
#end
Constants.m
#import "Constants.h"
#implementation Constants
NSString * const ITEM = #"item";
NSString * const TITLE = #"title";
NSString * const IMAGE = #"image";
NSString * const DESCRIPTION = #"description";
NSString * const TEXT = #"text";
- (void)dealloc
{
[super dealloc];
}
#end
myNews.h
#import <Foundation/Foundation.h>
#interface myNews : NSObject
{
NSString *itemTitle;
NSString *itemImageUrl;
NSString *itemDescription;
NSString *itemText;
}
#property (nonatomic, retain) NSString *itemTitle;
#property (nonatomic, retain) NSString *itemImageUrl;
#property (nonatomic, retain) NSString *itemDescription;
#property (nonatomic, retain) NSString *itemText;
#end
myNews.m
#import "myNews.h"
#implementation myNews
#synthesize itemTitle;
#synthesize itemImageUrl;
#synthesize itemDescription;
#synthesize itemText;
#end
XMLController.h
#import <Foundation/Foundation.h>
#class Constants;
#class myNews;
#interface XMLController : NSObject
{
NSMutableString *currentNodeContent;
NSMutableArray *newsArray;
NSXMLParser *parser;
myNews *currentNew;
}
#property (readonly, retain) NSMutableArray *newsArray;
-(id)loadXMLByURL:(NSString *)urlString;
#end
XMLController.m
#import "XMLController.h"
#import "Constants.h"
#import "myNews.h"
#implementation XMLController
#synthesize newsArray;
-(id)loadXMLByURL:(NSString *)urlString
{
newsArray = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString: urlString];
parser = [[NSXMLParser alloc] initWithContentsOfURL: url];
[parser setDelegate:(id)self];
[parser parse];
return self;
}
-(void) parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString: ITEM])
{
currentNew = [myNews alloc];
currentNodeContent = [[NSMutableArray alloc] init];
}
}
-(void) parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString: TITLE])
{
currentNew.itemTitle = currentNodeContent;
}
if ([elementName isEqualToString: IMAGE])
{
currentNew.itemImageUrl = currentNodeContent;
}
if ([elementName isEqualToString: DESCRIPTION])
{
currentNew.itemDescription = currentNodeContent;
}
if ([elementName isEqualToString: TEXT])
{
currentNew.itemText = currentNodeContent;
}
if ([elementName isEqualToString: ITEM])
{
[newsArray addObject:currentNew];
[currentNew release];
currentNew = nil;
[currentNodeContent release];
currentNodeContent = nil;
}
}
-(void) parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
{
currentNodeContent = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#end
myAppDelegate.h
#import <UIKit/UIKit.h>
#import "MainViewController.h"
#import "DetailViewController.h"
#class MainViewController;
#class DetailViewController;
#interface myAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *myNavigationController;
MainViewController *myMainViewController;
DetailViewController *myDetailViewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UINavigationController *myNavigationController;
#property (nonatomic, retain) IBOutlet MainViewController *myMainViewController;
#property (nonatomic, retain) IBOutlet DetailViewController *myDetailViewController;
#end
myAppDelegate.m
#import "myAppDelegate.h"
#import "myNews.h"
#import "MainViewController.h"
#import "DetailViewController.h"
#implementation myAppDelegate
#synthesize window;
#synthesize myNavigationController;
#synthesize myMainViewController;
#synthesize myDetailViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[window addSubview:myNavigationController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)dealloc
{
[window release];
[myNavigationController release];
[myMainViewController release];
[myDetailViewController release];
[super dealloc];
}
#end
MainViewController.h
#import <UIKit/UIKit.h>
#import "XMLController.h"
#interface MainViewController : UIViewController
{
XMLController *xmlcont;
UILabel *myTitleLabel;
// declared here some 10 objects
}
#property (nonatomic, retain) UILabel *myTitleLabel;
#end
MainViewController.m
#import "MainViewController.h"
#import "myNews.h"
#implementation MainViewController
#synthesize myTitleLabel;
- (void)completeRefresh
{
[myMainViewController viewDidLoad];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *myRefreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 35.0f, 23.0f)];
[myRefreshButton setImage:[UIImage imageNamed:#"ButtonRefresh.png"] forState:UIControlStateNormal];
[myRefreshButton addTarget:self
action:#selector(completeRefresh)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *myRefreshBarButton = [[[UIBarButtonItem alloc] initWithCustomView:myRefreshButton] autorelease];
[self.navigationItem setRightBarButtonItem: myRefreshBarButton];
[myRefreshButton release];
xmlcont = [[XMLController alloc] loadXMLByURL:#"http://link_to_XML_file.xml"];
NSLog(#"array = %#", [xmlcont newsArray]);
for (myNews *oneNew in [xmlcont newsArray]) {
CGRect frameTitleLabel = CGRectMake(0.0f, 200.0f, 320.0f, 60.0f);
myTitleLabel = [[UILabel alloc] initWithFrame:frameTitleLabel];
myTitleLabel.backgroundColor = [UIColor blackColor];
myTitleLabel.text = [myOneNew itemTitle];
myTitleLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size: 17.0];
myTitleLabel.textColor = [UIColor whiteColor];
[self.view addSubview:myTitleLabel];
[myTitleLabel release];
}
}
- (void)viewDidUnload
{
self.myTitleLabel = nil;
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc
{
[myTitleLabel release];
[super dealloc];
}
#end
During the test the application using the Instruments: Activity Monitor shows that when you click refresh and call 'completeRefresh' memory (Real Mem) is not cleared when reload viewDidLoad, and accumulates with every touch and calling 'completeRefresh'
Maybe someone has a possible solution?
To avoid leaking memory you need to release your retained ivars/properties in dealloc. For example:
myNews.m
- (void)dealloc {
// Setting these properties to nil releases them because they're (nonatomic, retain)
self.itemTitle = nil;
self.itemImageUrl = nil;
self.itemDescription = nil;
self.itemText = nil;
[super dealloc];
}
XMLController.m
- (void)dealloc {
self.newsArray = nil;
// These ivars aren't properties so you just have to call release on them
[currentNodeContent release];
[parser release];
[currentNew release];
[super dealloc];
}
etc. Do this for all your classes.

Debugger message

I do webservice requests with a UISegmentedControl, when I change segmentedItem and request fast the application crashes with this message:
[Session started at 2011-05-12
10:58:50 +0200.] Terminating in
response to SpringBoard's termination.
[Session started at 2011-05-12
11:06:31 +0200.] GNU gdb
6.3.50-20050815 (Apple version gdb-1516) (Fri Feb 11 06:19:43 UTC
2011) Copyright 2004 Free Software
Foundation, Inc. GDB is free software,
covered by the GNU General Public
License, and you are welcome to change
it and/or distribute copies of it
under certain conditions. Type "show
copying" to see the conditions. There
is absolutely no warranty for GDB.
Type "show warranty" for details. This
GDB was configured as
"--host=i386-apple-darwin
--target=arm-apple-darwin".tty /dev/ttys001 Loading program into
debugger… Program loaded. target
remote-mobile
/tmp/.XcodeGDBRemote-239-58 Switching
to remote-macosx protocol mem 0x1000
0x3fffffff cache mem 0x40000000
0xffffffff none mem 0x00000000 0x0fff
none run Running… [Switching to thread
11779] [Switching to thread 11779]
sharedlibrary apply-load-rules all
continue Program received signal:
“SIGKILL”. warning: Unable to read
symbols for
/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3
(8J2)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib
(file not found). kill quit
The Debugger has exited with status
0.(gdb)
Does anybody have an idea of how can I fix this?
Is this a problem because I'm not using NSOperationQueue?
And if so any suggestions how I can fix this would be very welcomed.
I can not find any memory leaks when running.
Next time I ran it this message got logged:
Program received signal: “EXC_BAD_ACCESS”.
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3 (8J2)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
(gdb)
Here is the code for starting the connection:
Class header ServiceGetChildren:
#import <Foundation/Foundation.h>
#class Authentication;
#class AttendanceReportViewController;
#interface ServiceGetChildren : NSObject {
Authentication *authentication;
AttendanceReportViewController *attendanceReportViewController;
NSString *username;
NSString *password;
NSMutableString *authenticationString;
NSString *encodedLoginData;
NSMutableData *responseData;
NSMutableArray *childrensArray;
}
#property (nonatomic, retain) NSString *username;
#property (nonatomic, retain) NSString *password;
#property (nonatomic, retain) NSMutableString *authenticationString;
#property (nonatomic, retain) NSString *encodedLoginData;
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *childrensArray;
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller;
#end
Class handling the request:
#import "ServiceGetChildren.h"
#import "JSON.h"
#import "Base64.h"
#import "AttendanceReportViewController.h"
#import "Authentication.h"
#implementation ServiceGetChildren
#synthesize appDelegate;
#synthesize username;
#synthesize password;
#synthesize authenticationString;
#synthesize encodedLoginData;
#synthesize responseData;
#synthesize childrensArray;
- (id) init {
if ((self = [super init])) {
}
return self;
}
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller {
username = appDelegate.username;
password = appDelegate.password;
attendanceReportViewController = (AttendanceReportViewController *)controller;
Authentication *auth = [[Authentication alloc] init];
authenticationString = (NSMutableString*)[#"" stringByAppendingFormat:#"%#:%#", username, password];
encodedLoginData = [auth encodedAuthentication:authenticationString];
[auth release];
// Setup up the request with the url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 20.0];
[request setHTTPMethod:method];
[request setValue:[NSString stringWithFormat:#"Basic %#", encodedLoginData] forHTTPHeaderField:#"Authorization"];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
// Display the network indicator when the connection request started
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Check that the NSURLConnection was successful and then initialize the responseData
if(connection) {
NSLog(#"Connection made");
responseData = [[NSMutableData data] retain];
}
else {
NSLog(#"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Connection finished loading.");
// Dismiss the network indicator when connection finished loading
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// Parse the responseData of json objects retrieved from the service
SBJSON *parser = [[SBJSON alloc] init];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parser objectWithString:jsonString error:nil];
NSMutableArray *array = [jsonData objectForKey:#"Children"];
childrensArray = [NSMutableArray arrayWithArray:array];
// Callback to AttendanceReportViewController that the responseData finished loading
[attendanceReportViewController loadChildren];
[connection release];
[responseData release];
[jsonString release];
[parser release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failure.");
NSLog(#"ERROR%#", error);
// Dismiss the network indicator when connection failure occurred
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
// Inform the user that the server was unavailable
}
- (void) dealloc {
[attendanceReportViewController release];
[super dealloc];
}
Class header for AttendanceReportViewController:
#import <UIKit/UIKit.h>
#class ServiceGetGroups;
#class ServiceGetChildren;
#class DetailViewController;
#interface AttendanceReportViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
ServiceGetGroups *serviceGetGroups;
ServiceGetChildren *serviceGetChildren;
DetailViewController *detailViewController;
UISegmentedControl *segmentedControl;
IBOutlet UIToolbar *groupsToolbar;
NSMutableArray *btnArray;
NSInteger index;
IBOutlet UITableView *theTableView;
IBOutlet UILabel *attendanceLabel;
IBOutlet UILabel *abscentLabel;
IBOutlet UILabel *totalLabel;
NSMutableDictionary *selectRequestDictionary;
NSMutableDictionary *selectNameDictionary;
NSMutableArray *groupsArray;
NSMutableArray *childrensArray;
NSDictionary *childrensDictionary;
NSURL *url;
}
#property (nonatomic, retain) ServiceGetGroups *serviceGetGroups;
#property (nonatomic, retain) ServiceGetChildren *serviceGetChildren;
#property (nonatomic, retain) DetailViewController *detailViewController;
#property (nonatomic, retain) IBOutlet UIToolbar *groupsToolbar;
#property (nonatomic, retain) IBOutlet UITableView *theTableView;
#property (nonatomic, retain) IBOutlet UILabel *attendanceLabel;
#property (nonatomic, retain) IBOutlet UILabel *abscentLabel;
#property (nonatomic, retain) IBOutlet UILabel *totalLabel;
#property (nonatomic, retain) UISegmentedControl *segmentedControl;
#property (nonatomic) NSInteger index;
#property (nonatomic, retain) NSMutableArray *btnArray;
#property (nonatomic, retain) NSMutableDictionary *selectRequestDictionary;
#property (nonatomic, retain) NSMutableDictionary *selectNameDictionary;
#property (nonatomic, retain) NSMutableArray *groupsArray;
#property (nonatomic, retain) NSMutableArray *childrensArray;
#property (nonatomic, retain) NSDictionary *childrensDictionary;
#property (nonatomic, retain) NSURL *url;
- (void)setupSegmentedControl;
- (void)requestGroups;
- (void)requestChildren:(NSNumber *)groupId;
- (void)loadGroups;
- (void)loadChildren;
#end
Class that the Uses the UISegmentedControl:
#import "JSON.h"
#import "AttendanceReportViewController.h"
#import "CustomCellViewController.h"
#import "DetailViewController.h"
#import "ServiceGetGroups.h"
#import "ServiceGetChildren.h"
#import "Group.h"
#import "Child.h"
#implementation AttendanceReportViewController
#synthesize serviceGetGroups;
#synthesize serviceGetChildren;
#synthesize detailViewController;
#synthesize segmentedControl;
#synthesize groupsToolbar;
#synthesize index;
#synthesize btnArray;
#synthesize theTableView;
#synthesize attendanceLabel;
#synthesize abscentLabel;
#synthesize totalLabel;
#synthesize selectRequestDictionary;
#synthesize selectNameDictionary;
#synthesize groupsArray;
#synthesize childrensArray;
#synthesize childrensDictionary;
#synthesize url;
#pragma mark -
#pragma mark View lifecycle
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
- (void)requestGroups {
NSURL *groupsURL = [NSURL URLWithString:#"http://services/groups"];
[serviceGetGroups startService:groupsURL :#"GET" withParent:self];
}
- (void)requestChildren:(NSNumber *)groupId {
NSLog(#"%#", groupId);
NSString *baseURL = #"http://services/group/";
NSString *method = [NSString stringWithFormat:#"%#%#", groupId, #"/children"];
NSString *theURL = [NSString stringWithFormat:#"%#%#", baseURL, method];
self.url = [NSURL URLWithString:theURL];
NSLog(#"%#", self.url);
[serviceGetChildren startService:self.url :#"GET" withParent:self];
}
- (void)loadGroups {
// Retrieve a array with dictionaries of groups from ServiceGetGroups
self.groupsArray = [[serviceGetGroups.groupsArray copy] autorelease];
// The array to hold segmentedItems for the segmentedControl, representing groups buttons
btnArray = [NSMutableArray arrayWithObjects: #"Alla", nil];
for (NSDictionary *groupDict in groupsArray) {
// Add each groups name to the btnArray as segmentedItems for the segmentedControl
[btnArray addObject:[groupDict objectForKey:#"Name"]];
}
// Create a new NSMutableDictionary with group names as keys and group id´s as values
// used for reference to segementedControl items to make request to serviceGetChildren
self.selectRequestDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *dict in groupsArray) {
[selectRequestDictionary setObject:[dict objectForKey:#"Id"] forKey:[dict objectForKey:#"Name"]];
}
// Create a new NSMutableDictionary with group id´s as keys and group names as values
// used for retrieving a groupName from a passed id
self.selectNameDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *dict in groupsArray) {
[selectNameDictionary setObject:[dict objectForKey:#"Name"] forKey:[dict objectForKey:#"Id"]];
}
[self setupSegmentedControl];
}
- (void)setupSegmentedControl {
// Setup the UISegmentedControl as groups buttons
segmentedControl = nil;
segmentedControl = [[UISegmentedControl alloc] initWithItems:btnArray];
segmentedControl.tintColor = [UIColor darkGrayColor];
segmentedControl.selectedSegmentIndex = 0;
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(0, 0, 300, 30);
// Setup the target and actions for the segmentedControl
[segmentedControl addTarget:self
action:#selector(selectGroup:)
forControlEvents:UIControlEventValueChanged];
// Add the UISegmentedControl as a UIBarButtonItem subview to the UIToolbar
UIBarButtonItem *segmentedItem = [[[UIBarButtonItem alloc] initWithCustomView:segmentedControl] autorelease];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSArray *groupsButtons = [NSArray arrayWithObjects:flexSpace, segmentedItem, flexSpace, nil];
[groupsToolbar setItems:groupsButtons];
[flexSpace release];
}
- (void)loadChildren {
// Retrieve a array with dictionaries of children from ServiceGetChildren
self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];
// TODO create seperate method - Setup compilation bar values
int total = [childrensArray count];
totalLabel.text = [NSString stringWithFormat:#"%d", total];
[theTableView reloadData];
}
// Handles UIControlEventValueChanged for UISegmentedControl, retreives the name and id for a selected group
- (void)selectGroup:(UISegmentedControl *)theSegmentedControl {
NSString *selectedGroup = [segmentedControl titleForSegmentAtIndex: [segmentedControl selectedSegmentIndex]];
NSNumber *selectedId = [selectRequestDictionary objectForKey:selectedGroup];
// Persist the selectedSegmentIndex when view switches to detaildView
index = [segmentedControl selectedSegmentIndex];
// Request children based on the selected groupId
[self requestChildren:selectedId];
}
- (void)viewDidLoad {
[self requestGroups];
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [childrensArray count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
// Load from nib
CustomCellViewController *cell = (CustomCellViewController *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:#"CustomCellView"
owner:nil
options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (CustomCellViewController *) currentObject;
break;
}
}
}
// Set up a children dictionary for easy retrieving specific values to display in the UITableView
childrensDictionary = [childrensArray objectAtIndex:indexPath.row];
NSNumber *idForName = [childrensDictionary valueForKey:#"GroupId"];
NSString *name = [NSString stringWithFormat:#"%# %#",
[childrensDictionary valueForKey:#"Firstname"],
[childrensDictionary valueForKey:#"Surname"]];
NSString *group = [NSString stringWithFormat:#"%#",
[selectNameDictionary objectForKey:idForName]];
cell.childNameLabel.text = name;
cell.groupNameLabel.text = group;
cell.scheduleLabel.text = #"Schema";
cell.deviationLabel.text = #"Avvikelse";
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push the detailedViewController.
if (detailViewController == nil) {
DetailViewController *_detailViewcontroller = [[DetailViewController alloc]
initWithNibName:#"DetailView" bundle:nil];
self.detailViewController = _detailViewcontroller;
[_detailViewcontroller release];
}
childrensDictionary = [childrensArray objectAtIndex:indexPath.row];
NSNumber *idForName = [childrensDictionary valueForKey:#"GroupId"];
NSString *group = [NSString stringWithFormat:#"%#",
[selectNameDictionary objectForKey:idForName]];
[self.detailViewController initWithDetailsSelected:childrensDictionary:group];
[self.navigationController pushViewController:detailViewController animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
segmentedControl = nil;
}
- (void)dealloc {
[segmentedControl release];
[groupsArray release];
[childrensArray release];
[detailViewController release];
[super dealloc];
}
#end
OK here we go. First of all, I could not test the code, so I need your feedback.
The main problem with this class is, you only have one instance, which you reuse every time you hit the segmented control. This leads to creation of new instances of the NSURLConnection. So let's correct a bit in the header. I changed the NSString properties to copy. Have a look at this Q&A to know why, however this is not important for the improvement, just wanted to let you know.
I've removed Authentication *authentication; looked like you don't use it.
Added NSURLConnection as property so we keep a reference on it.
Header file
#class Authentication;
#class AttendanceReportViewController;
#interface ServiceGetChildren : NSObject {
AttendanceReportViewController *attendanceReportViewController;
NSString *username;
NSString *password;
NSMutableString *authenticationString;
NSString *encodedLoginData;
NSMutableData *responseData;
NSMutableArray *childrensArray;
NSURLConnection *connection;
}
#property (nonatomic, copy) NSString *username;
#property (nonatomic, copy) NSString *password;
#property (nonatomic, retain) NSMutableString *authenticationString;
#property (nonatomic, copy) NSString *encodedLoginData;
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *childrensArray;
#property (nonatomic, retain) NSURLConnection *connection
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller;
#end
Next comes the Implementation file. I only altered the startService method and dealloc.
If you declare properties, use them :) Have a look at this Q&A for some explanations on synthesized properties.
Always release what you own, so I added release code in the dealloc.
Cancel the previous request!!! If there is none, the message is sent to nil, which causes no harm.
Implementation file
- (void)startService:(NSURL *)url:(NSString *)method withParent:(UIViewController *)controller
{
self.username = appDelegate.username;
self.password = appDelegate.password;
[connection cancel];
attendanceReportViewController = (AttendanceReportViewController *)controller;
Authentication *auth = [[Authentication alloc] init];
authenticationString = (NSMutableString *)[#"" stringByAppendingFormat:#"%#:%#", username, password];
self.encodedLoginData = [auth encodedAuthentication:authenticationString];
[auth release];
// Setup up the request with the url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:20.0];
[request setHTTPMethod:method];
[request setValue:[NSString stringWithFormat:#"Basic %#", encodedLoginData] forHTTPHeaderField:#"Authorization"];
self.connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
// Display the network indicator when the connection request started
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Check that the NSURLConnection was successful and then initialize the responseData
if (connection) {
NSLog(#"Connection made");
self.responseData = [NSMutableData data];
} else {
NSLog(#"Connection could not be made");
}
}
...
- (void) dealloc
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection cancel];
[connection release];
[appDelegate release];
[responseData release];
[username release];
[password release];
[authenticationString release];
[encodedLoginData release];
[responseData release];
[childrensArray release];
[super dealloc];
}
Hope this helps for the next steps. However I think we will have to work a bit on the solution until it's final.

Passing a Value Through a Navigation Controller

I'm looking to pass a user chosen value from one view to the next so it can be submitted to Twitter, Facebook, etc.
Would a global variable be best to implement? I don't want the value to be stored or saved anywhere.. just to make it through the end of the navigation controller (submission to Facebook, Twitter, etc.)
Any suggestions? Thanks in advance.
Header File
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "ShareViewController.h"
#include "TwitterRushViewController.h"
#interface KindViewController : UIViewController <UIPickerViewDelegate, UIScrollViewDelegate, CLLocationManagerDelegate> {
IBOutlet UIScrollView *scrollView;
IBOutlet UIPageControl *pageControl;
BOOL pageControlIsChangingPage;
CLLocationManager *locationManager;
NSString *finalCoordinates;
NSString *finalChoice;
}
#property (nonatomic, retain) UIView *scrollView;
#property (nonatomic, retain) UIPageControl *pageControl;
#property (nonatomic, retain) CLLocationManager *locationManager;
#property (retain) NSString *finalCoordinates;
#property (nonatomic, copy) NSString *finalChoice;
-(IBAction)changePage:(id)sender;
-(IBAction)submitChoice:(id)sender;
-(void)setupPage;
#end
Implementation File
#import "KindViewController.h"
#import "JSON/JSON.h"
#implementation KindViewController
#synthesize scrollView;
#synthesize pageControl;
#synthesize locationManager;
#synthesize finalCoordinates;
#synthesize finalChoice;
#pragma mark -
#pragma mark UIView boilerplate
- (void)viewDidLoad {
[self setupPage];
[super viewDidLoad];
// Alert the User on Location Access
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
-(void)viewWillAppear:(BOOL)animated {
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocation *location = newLocation;
NSLog(#"Our current Latitude is %f", location.coordinate.latitude);
NSLog(#"Our current Longitude is %f", location.coordinate.longitude);
NSString *Coordinates = [[NSString alloc] initWithFormat: #"Longitude=%f&Latitude=%f", location.coordinate.longitude, location.coordinate.latitude ];
NSLog(#"Test: %#", Coordinates);
finalCoordinates = Coordinates;
[locationManager stopUpdatingLocation];
}
#pragma mark -
#pragma mark The Guts
- (void)setupPage {
scrollView.delegate = self;
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = YES;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
NSUInteger nimages = 0;
CGFloat cx = 0;
for (; ; nimages++) {
NSString *imageName = [NSString stringWithFormat:#"choice%d.png", (nimages + 1)];
UIImage *image = [UIImage imageNamed:imageName];
if (image == nil) {
break;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = image.size.height;
rect.size.width = image.size.width;
rect.origin.x = ((scrollView.frame.size.width - image.size.width) / 2) + cx;
rect.origin.y = ((scrollView.frame.size.height - image.size.height) / 2);
imageView.frame = rect;
[scrollView addSubview:imageView];
[imageView release];
cx += scrollView.frame.size.width;
}
self.pageControl.numberOfPages = nimages;
[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
}
#pragma mark -
#pragma mark UIScrollViewDelegate stuff
- (void)scrollViewDidScroll:(UIScrollView *)_scrollView {
if (pageControlIsChangingPage) {
return;
}
CGFloat pageWidth = _scrollView.frame.size.width;
int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView {
pageControlIsChangingPage = NO;
}
#pragma mark -
#pragma mark PageControl stuff
- (IBAction)changePage:(id)sender {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * pageControl.currentPage;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
pageControlIsChangingPage = YES;
}
-(IBAction)submitChoice:(id)sender; {
// Spinner
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(135,140,50,50)];
[spinner startAnimating];
[self.view addSubview:spinner];
// Find the Date
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"MMM dd, yyyy HH:mm"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
// Echo Everything
NSLog(#"Type is %f.", scrollView.contentOffset.x);
NSLog(#"Date is %#", dateString);
NSLog(#"Coordinates are %#", finalCoordinates);
NSString *completeURL = [[NSString alloc] initWithFormat: #"http://www.example.com/insert.php?Type=%f&Time=%#&%#", scrollView.contentOffset.x, dateString, finalCoordinates];
NSString *escapedUrl = [completeURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"URL is %#.", escapedUrl);
// Post to Web Server
NSURL *urlToSend = [[NSURL alloc] initWithString:escapedUrl];
NSLog(#"NSURL is %#.", urlToSend);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlToSend cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
// Do the Button Action
ShareViewController *shareViewController = [[ShareViewController alloc] initWithNibName:#"ShareViewController" bundle:nil];
shareViewController.finalChoice = #"Facebook Property";
[self.navigationController pushViewController:shareViewController animated:YES];
[shareViewController release];
[urlToSend release];
[completeURL release];
[spinner release];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"There is an error updating the location");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
[pageControl release];
}
- (void)dealloc {
[super dealloc];
}
#end
ShareViewController.h
#import <UIKit/UIKit.h>
#import "MapViewController.h"
#import "SA_OAuthTwitterController.h"
#import "FBConnect/FBConnect.h"
#import "TwitterRushViewController.h"
#import "oAuth2TestViewController.h"
#class SA_OAuthTwitterEngine;
#interface ShareViewController : UIViewController <UITextFieldDelegate, SA_OAuthTwitterControllerDelegate> {
}
#property (nonatomic, retain) IBOutlet UIButton *shareFacebookBTN;
#property (nonatomic, retain) IBOutlet UIButton *shareTwitterBTN;
#property (nonatomic, retain) KindViewController finalChoice;
/* Submissions */
- (IBAction)shareNoThanks:(id)sender;
- (IBAction)shareFacebook:(id)sender;
- (IBAction)shareTwitter:(id)sender;
#end
Just setting a property on the next UIViewController when you push it would probably be the easiest thing to do.
SomeViewController *someViewController = [[SomeViewController alloc] init];
someViewController.facebookProperty = #"Facebook Property";
someViewController.twitterProperty = #"Twitter Property";
[self.navigationController pushViewController:someViewController animated:YES];
[someViewController release];
Ok there are a few things wrong with ShareViewController.h. First if you have a property you also need to have an instance variable for that property. Next you are assigning a string to finalChoice but you have declared its type as KindViewController it should be NSString.
In ShareViewController.h
#interface ShareViewController : UIViewController <UITextFieldDelegate, SA_OAuthTwitterControllerDelegate> {
NSString *finalChoice;
}
#property (nonatomic, retain) IBOutlet UIButton *shareFacebookBTN;
#property (nonatomic, retain) IBOutlet UIButton *shareTwitterBTN;
#property (nonatomic, copy) NSString *finalChoice;
And make sure you #synthesize finalChoice in your implementation file.
Without knowing any of the specifics, I would avoid a global variable or tightly coupling the two views together.
Depending on your needs and implementation, delegation or notifications may a better choice to pass a variable between views.
There's a good discussion on the more general problem of how best to communicate between view controllers over here. The top-voted answer is pretty good.
The tl;dr version is basically:
Global variables and singleton classes are rarely the right answer.
Read up on the "dependency injection" design pattern.
Hope that helps.