How to save/retrieve UIButton state? - iphone

and this is my first question here !
I use UIButton with UISwitch functionality and i want to save/retrieve state of UIButton.
Pls HELP!
Resolved!
Thanks Kalle and aBitObvious !
code i use :
.h
#interface RetinaViewController : UIViewController {
IBOutlet UIButton *mybutton;
}
-(IBAction) toggleUIButtonImage:(id)sender;
#end
.m
#implementation RetinaViewController
-(IBAction) toggleUIButtonImage:(id)sender{
NSString *value = #"ON";
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
UIImage *unselectedImage = [UIImage imageNamed: #"OFFa.png"];
UIImage *selectedImage = [UIImage imageNamed:#"ONa.png"];
if ([sender isSelected]) {
[sender setImage:unselectedImage forState:UIControlStateNormal];
[sender setSelected:NO];
value = #"OFF";
[userPreferences setObject:value forKey:#"stateOfButton"];
}else {
[sender setImage:selectedImage forState:UIControlStateSelected];
[sender setSelected:YES];
value = #"ON";
[userPreferences setObject:value forKey:#"stateOfButton"];
}
[userPreferences synchronize];
}
- (void)viewDidLoad {
NSString *value = [[NSUserDefaults standardUserDefaults] stringForKey:#"stateOfButton"];
// If value is nil - disable the switch
if (value == nil) {
mybutton.selected = NO;
}
// If value is equal to ON
else if ([value compare:#"ON"] == NSOrderedSame) {
//NSLog(#"the switch is on");
// Set the switch to ON
mybutton.selected = YES;
} else {
//NSLog(#"the switch is off");
// Set the switch to OFF
mybutton.selected = NO;
}
[super viewDidLoad];
}

In the viewDidLoad of the view controller, put something like this:
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
NSString *stateOfButton = [userPreferences stringForKey:#"stateOfButton"];
if ([stateOfButton isEqualToString:#"ON"])
{
//set button state to "selected"
}
else
{
//set button state to "not selected"
}

Related

NSUserDefaults not getting stored string value

I have UIWebView for reading content. After that i select some text from content stores in string using NSUserDefaults in Viewcontroller. Then i retrieve this string value and displays in UITextView to viewcontroller1. But the UITextView is not updating text from viewcontroller. The NSUserDefaults also not getting updating text. Im using [self.navigationController pushViewController:viewcontroller1 animated:YES]; for switch to viewcontroller1.
viewcontroller:
[wbCont loadHTMLString:webString baseURL:nil];
[self.view addSubview:wbCont];
NSMutableArray *items = [[[UIMenuController sharedMenuController] menuItems] mutableCopy];
if (!items) items = [[NSMutableArray alloc] init];
UIMenuItem *menuItem;
menuItem = [[UIMenuItem alloc] initWithTitle:#"BookMark" action:#selector(save:)];
[items addObject:menuItem];
[menuItem release];
menuItem = [[UIMenuItem alloc] initWithTitle:#"Note" action:#selector(note:)];
[items addObject:menuItem];
[menuItem release];
[[UIMenuController sharedMenuController] setMenuItems:items];
[items release];
- (BOOL) canPerformAction:(SEL)action withSender:(id)sender
{
if (action == #selector(save:))
{
return YES;
}
else if (action == #selector(note:))
{
return YES;
}
else if (action == #selector(copy:))
{
return NO;
}
return [super canPerformAction:action withSender:sender];
}
-(void)save:(id)sender{
NSString *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSLog(#"selection is %#",selection);
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:selection forKey:#"preferenceName"];
[userData1 synchronize];
[self.navigationController pushViewController:note animated:YES];
}
viewcontroller1:
textView = [[UITextView alloc]initWithFrame:CGRectMake(0,0,320,400)];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedValue = [prefs stringForKey:#"preferenceName"];
NSLog(#"saved is %#", savedValue);
textView.text = [NSString stringWithFormat:#"%#", savedValue];
Allocation of textView is in viewDidLoad.
Updating of textView is in viewWillAppear.
-(void) viewWillAppear:(BOOL)animated
[super viewWillAppear:animated];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedValue = [prefs stringForKey:#"preferenceName"];
NSLog(#"saved is %#", savedValue);
textView.text = [NSString stringWithFormat:#"%#", savedValue];
}
I was checked your code just change NSSTring to NSString like below it will working.
-(void)save:(id)sender{
// NSSTring *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSString *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSLog(#"selection is %#",selection);
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:selection forKey:#"preferenceName"];
[userData1 synchronize];
[self.navigationController pushViewController:note animated:YES];
}

Image doesn't change returning to view between UIControlState

I can change image but when I come back on this view then it shows same image as UIControlStateNormal from whenever I was on UIControlStateSelected.
-(IBAction) favorateImage:(UIButton*)sender{
AppDelegate *obj=[[UIApplication sharedApplication]delegate];
if ([sender isSelected]) {
[sender setImage:[UIImage imageNamed:#"favrtes_uncheck.png"] forState:UIControlStateNormal];
[sender setSelected:NO];
NSMutableArray* array = [[[NSUserDefaults standardUserDefaults] objectForKey:#"favoriteItems"] mutableCopy];
[array removeObject:[NSNumber numberWithInt:self.number]];
[[NSUserDefaults standardUserDefaults] setObject:array forKey:#"favoriteItems"];
NSLog(#"%#", array);
obj.country_main= array;
} else
{
[sender setImage:[UIImage imageNamed:#"favrtes_detail.png"] forState:UIControlStateSelected];
[sender setSelected:YES];
NSMutableArray* array= [[[NSUserDefaults standardUserDefaults] objectForKey:#"favoriteItems"] mutableCopy];
[array addObject:[NSNumber numberWithInt:self.number]];
[[NSUserDefaults standardUserDefaults] setObject:array forKey:#"favoriteItems"];
NSLog(#"%#", array);
obj.country_main= array;
}
}
You can use UIControlStateHighlighted for this.
[sender setImage:[UIImage imageNamed:#"favrtes_detail.png"] forState:UIControlStateHighlighted];
You can also set this from interface builder by setting the image for highlighted state.

Facebook Loginbutton issues

I have a reader application which can post text to Facebook .I already done that,i have a login-button as same as the facebook-login button,the user can login there and i retrieve the username from the Facebook and display instead of loge-out button,that means when the user login and came back the login-button title changes to loge-out thats the default behavior of the Facebook connect button,but i changed a little and set the title as username of the correspondent user.My problem is after login to the Facebook the the title of the button changes to username,but after redirected to some other page of the application and comes back it doesn't show the username the button title shows login.I tried a lot to solve this i even uses the NSUserDefault but no luck my entire code for this is
- (IBAction)loginButtonTapped:(id)sender
{
NSString *appId = #"HIDDEN1234";
NSString *permissions = #"publish_stream";
if (_loginDialog == nil) {
self.loginDialog = [[[FBFunLoginDialog alloc] initWithAppId:appId requestedPermissions:permissions delegate:self] autorelease];
self.loginDialogView = _loginDialog.view;
}
if (_loginState == LoginStateStartup || _loginState == LoginStateLoggedOut) {
_loginState = LoginStateLoggingIn;
[_loginDialog login];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"FB_logged"];
} else if (_loginState == LoginStateLoggedIn) {
_loginState = LoginStateLoggedOut;
_btnFacebookmain.enabled =NO;
[_loginDialog logout];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"FB_logged"];
}
[self refresh];
}
-(IBAction)_clickbtnFaacbukMain:(id)sender
{
StatusViewController *detailViewController = [[StatusViewController alloc] initWithNibName:#"StatusViewController" bundle:nil];
detailViewController.yourStringProperty = localStringValue;
detailViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:detailViewController animated:YES];
[UIView commitAnimations];
[detailViewController release];
UIView *popView = (UIView *)[self.view viewWithTag:106];
//ViewWithTag Number should be same as used while allocating
[popView removeFromSuperview];
}
- (void)refresh {
if (_loginState == LoginStateStartup || _loginState == LoginStateLoggedOut) {
_loginStatusLabel.text = #"Not connected to Facebook";
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"FB_logged"];
[_loginButton setTitle:#"" forState:UIControlStateNormal];
UIImage *buttonImage = [UIImage imageNamed:#"settings_connect1-facebook-icon"];
[_loginButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
//[[NSUserDefaults standardUserDefaults]removeObjectForKey:#"FB_LOGIN_STATUS"];
_loginButton.hidden = NO;
} else if (_loginState == LoginStateLoggingIn) {
_loginStatusLabel.text = #"Connecting to Facebook...";
_loginButton.hidden = YES;
UIImage *buttonImage = [UIImage imageNamed:#"settings_connect1-facebook-icon"];
[_loginButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
} else if (_loginState == LoginStateLoggedIn) {
_loginStatusLabel.text = #"Connected to Facebook";
NSString *username = [_loginButton titleForState:UIControlStateNormal];
[_loginButton setTitle:username forState:UIControlStateNormal];
[_loginButton setBackgroundImage:nil forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"FB_logged"];
_loginButton.hidden = NO;
}
}
- (void)getFacebookProfile {
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#", [_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDidFinishSelector:#selector(getFacebookProfileFinished:)];
[request setDelegate:self];
[request startAsynchronous];
}
#pragma mark FB Responses
- (void)getFacebookProfileFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"Got Facebook Profile: %#", responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *username;
NSString *firstName = [responseJSON objectForKey:#"first_name"];
NSString *lastName = [responseJSON objectForKey:#"last_name"];
if (firstName && lastName) {
username = [NSString stringWithFormat:#"%# %#", firstName, lastName];
} else {
username = #"mysterious user";
}
//[[NSUserDefaults standardUserDefaults] setObject:#"username" forKey:#"FB_LOGIN_STATUS"];
[_loginButton setTitle:username forState:UIControlStateNormal];
[self refresh];
}
#pragma mark FBFunLoginDialogDelegate
- (void)accessTokenFound:(NSString *)accessToken {
NSLog(#"Access token found: %#", accessToken);
self.accessToken = accessToken;
_loginState = LoginStateLoggedIn;
[self dismissModalViewControllerAnimated:YES];
[self getFacebookProfile];
[self refresh];
}
- (void)displayRequired {
[self presentModalViewController:_loginDialog animated:YES];
}
- (void)closeTapped {
[self dismissModalViewControllerAnimated:YES];
_loginState = LoginStateLoggedOut;
[_loginDialog logout];
[self refresh];
}
and in viewwillapper method
BOOL loggedd = [[NSUserDefaults standardUserDefaults] boolForKey:#"FB_logged"];
if (loggedd == YES) {
_btnFacebookmain.enabled = YES;
NSString *username = [_loginButton titleForState:UIControlStateNormal];
[_loginButton setTitle:username forState:UIControlStateNormal];
//[self refresh];
}
else
{
[_loginButton setTitle:#"" forState:UIControlStateNormal];
_btnFacebookmain.enabled =NO;
/* UIImage *buttonImage = [UIImage imageNamed:#"settings_connect1-facebook-icon"];
[_loginButton setBackgroundImage:buttonImage forState:UIControlStateNormal];*/
}
please look into this code and help me to solve this.
Thanks in advance.

AlAssetsLibrary issue, code works in 4.3 but not 5.0

Here's my issue, if I access this class with iOS 4.X, the code works fine.... however whenever I try to access it with iOS 5.0, I get nil values for the groups & assets. What's the best way to get this to work? I'm posting the entire class for a reference...
.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "DejViewController.h"
#class Event, Venue;
#interface SelectMediaViewController : DejViewController <UITableViewDelegate, UITableViewDataSource> {
Event *event;
Venue *venue;
UITableView *tableView;
NSMutableArray *selectedAssets;
NSMutableArray *allMedia;
ALAssetsLibrary *library;
NSMutableArray *assetGroups;
}
#property (nonatomic, retain) Event *event;
#property (nonatomic, retain) Venue *venue;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSMutableArray *allMedia;
#property (nonatomic, retain) NSMutableArray *assetGroups;
- (IBAction)continuePressed:(id)sender;
#end
.m
#import <ImageIO/ImageIO.h>
#import "SelectMediaViewController.h"
#import "CaptionAllMediaViewController.h"
#import "MediaItem.h"
#import "CLValueButton.h"
#import "SelectMediaTableViewCell.h"
#define kMediaGridSize 75
#define kMediaGridPadding 4
#define kSelectImageTag 828
#interface SelectMediaViewController(Private)
- (void)setContentForButton:(CLValueButton *)button withAsset:(ALAsset *)asset;
- (void)loadData;
#end
#implementation SelectMediaViewController
#synthesize event, venue;
#synthesize tableView;
#synthesize allMedia,assetGroups;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
selectedAssets = [[NSMutableArray alloc] init];
showNextButton = YES;
}
return self;
}
- (void)dealloc {
[tableView release];
[event release];
[venue release];
[library release];
[allMedia release];
[selectedAssets release];
[assetGroups release];
[super dealloc];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"SelectMediaViewController - viewDidLoad");
}
- (void)viewDidUnload {
NSLog(#"SelectMediaViewController - viewDidUnload");
[self setTableView:nil];
[super viewDidUnload];
}
- (void)viewDidAppear:(BOOL)animated {
NSLog(#"SelectMediaViewController - viewDidAppear");
[super viewDidAppear:animated];
[self setNavTitle:#"Select Media"];
[self loadData];
[self.tableView reloadData];
float contentOffset = self.tableView.contentSize.height - self.tableView.frame.size.height;
if (contentOffset < 0) contentOffset = 0;
[self.tableView setContentOffset:CGPointMake(0, contentOffset) animated:NO];
}
- (void)viewDidDisappear:(BOOL)animated {
NSLog(#"SelectMediaViewController - viewDidDisappear");
self.allMedia = nil;
[selectedAssets removeAllObjects];
[self.tableView reloadData];
}
- (void)loadData {
NSMutableArray *tempArray = [[NSMutableArray array] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != NULL) {
NSLog(#"See Asset: %#", result);
[tempArray addObject:result];
NSLog(#"assets count: %i", tempArray.count);
}
else {
NSLog(#"result nil or end of list");
}
};
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
NSLog(#"group: %#",group);
}
else {
NSLog(#"group nil or end of list");
}
if (stop) {
self.allMedia = [NSMutableArray arrayWithCapacity:[tempArray count]];
self.allMedia = tempArray;
NSLog(#"Loaded data: %d & %d", [tempArray count], [self.allMedia count]);
}
};
//ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {
}];
//[library release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)continuePressed:(id)sender {
if ([selectedAssets count] > 0) {
CaptionAllMediaViewController *captionVC = [[CaptionAllMediaViewController alloc] initWithNibName:nil bundle:nil];
captionVC.event = self.event;
captionVC.venue = self.venue;
// Create media items
NSMutableArray *mediaItems = [NSMutableArray arrayWithCapacity:[selectedAssets count]];
for (ALAsset *asset in selectedAssets) {
MediaItem *item = [[MediaItem alloc] init];
item.asset = asset;
NSDictionary *metadata = [[asset defaultRepresentation] metadata];
NSDictionary *gpsMeta = [metadata objectForKey:#"{GPS}"];
if (gpsMeta) {
float latitude = [[gpsMeta objectForKey:#"Latitude"] floatValue];
if ([[gpsMeta objectForKey:#"LatitudeRef"] isEqualToString:#"S"]) latitude = latitude * -1;
float longitude = [[gpsMeta objectForKey:#"Longitude"] floatValue];
if ([[gpsMeta objectForKey:#"LongitudeRef"] isEqualToString:#"W"]) longitude = longitude * -1;
item.location = CLLocationCoordinate2DMake(latitude, longitude);
}
[mediaItems addObject:item];
[item release];
}
captionVC.media = mediaItems;
[self.navigationController pushViewController:captionVC animated:YES];
[captionVC release];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Images Selected"
message:#"Please select at least one image to continue."
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
- (void)imagePressed:(CLValueButton *)sender {
BOOL currentlySelected = [selectedAssets containsObject:sender.valueObject];
UIImageView *imageView = (UIImageView *)[sender viewWithTag:kSelectImageTag];
if (!currentlySelected) {
[imageView setImage:[UIImage imageNamed:#"image-select-active.png"]];
[selectedAssets addObject:sender.valueObject];
} else {
[imageView setImage:[UIImage imageNamed:#"image-select.png"]];
[selectedAssets removeObject:sender.valueObject];
}
}
#pragma Table view methods
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"Getting table view count: %d", [self.allMedia count]);
if ([self.allMedia count] == 0) return 0;
return ceil([self.allMedia count] / 4.0);
}
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 83;
NSLog(#"return83");
}
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
SelectMediaTableViewCell *cell = (SelectMediaTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:#"MEDIA_CELL"];
if (!cell) {
cell = [[[NSBundle mainBundle] loadNibNamed:#"SelectMediaTableViewCell" owner:nil options:nil] objectAtIndex:0];
// wire up selectors
[cell.image1 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image2 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image3 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image4 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
}
int startIndex = indexPath.row * 4;
for (int i = 0; i < 4; i++) {
ALAsset *thisAsset = (startIndex + i) < [self.allMedia count] ? [self.allMedia objectAtIndex:startIndex + i] : nil;
CLValueButton *button = nil;
switch (i) {
case 0:
button = cell.image1;
break;
case 1:
button = cell.image2;
break;
case 2:
button = cell.image3;
break;
case 3:
button = cell.image4;
break;
default:
break;
}
[self setContentForButton:button withAsset:thisAsset];
UIImageView *imageView = (UIImageView *)[button viewWithTag:kSelectImageTag];
// letse see if it's selected or not...
if ([selectedAssets containsObject:button.valueObject]) {
[imageView setImage:[UIImage imageNamed:#"image-select-active.png"]];
} else {
[imageView setImage:[UIImage imageNamed:#"image-select.png"]];
}
}
return cell;
}
- (void)setContentForButton:(CLValueButton *)button withAsset:(ALAsset *)asset {
button.hidden = asset == nil;
if (asset) {
CGImageRef image = [asset thumbnail];
[button setImage:[UIImage imageWithCGImage:image] forState:UIControlStateNormal];
}
[button setValueObject:asset];
}
#pragma -
#end
Any help would be much appreciated, I've been trying to figure this out for 3 days...
The ALAssetsLibrary page in the online documentation now says "The lifetimes of objects you get back from a library instance are tied to the lifetime of the library instance."

Open URL with UIButton

I hope You are well, I've been working a few weeks on iphone and at the moment I have a problem try to open a safari with a url, I have a json file that come a url which is dinamic.
here I leave the code.
- (void) loadFiles {
NSArray *_json = [[[self getDataFromJson] objectAtIndex:0] retain];
if ([_json count] > 0)
{
for (int i = 0; i < [_json count]; i++)
{
NSDictionary *file = [_json objectAtIndex:i];
UIImage *buttonImage = [UIImage imageNamed:#"btn.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
[button addTarget:self action:#selector(openBrowser:) forControlEvents:UIControlEventTouchUpInside];
//works but i have warnings
button.tag = [file objectForKey:#"linkURL"] ;
CGRect frame = CGRectZero;
frame.size = buttonImage.size;
button.frame = frame;
NSString *name = [file objectForKey:#"name"];
NSString *description = [file objectForKey:#"description"];
//Create Box
}
}
}
- (void) openBrowser:(id)sender
{
NSString *url = ((UIControl *) sender).tag;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] ];
}
I need to open from the UIButtom an URL without complaint .
Any suggestion or help thank you.
Cheers
Subclass UIButton and add a property to store the URL.
// MyButton.h
#interface MyButton : UIButton {
NSString *urlString_;
}
#property (nonatomic, retain) NSString *urlString;
#end
// MyButton.m
#import "MyButton.h"
#implementation MyButton
#synthesize urlString = urlString_;
- (void)dealloc {
[self setUrlString:nil];
[super dealloc];
}
#end
and then you continue with your code:
#import "MyButton.h"
.
.
.
- (void) loadFiles {
NSArray *_json = [[[self getDataFromJson] objectAtIndex:0] retain];
if ([_json count] > 0)
{
for (int i = 0; i < [_json count]; i++)
{
NSDictionary *file = [_json objectAtIndex:i];
UIImage *buttonImage = [UIImage imageNamed:#"btn.png"];
MyButton *button = [MyButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
[button addTarget:self action:#selector(openBrowser:) forControlEvents:UIControlEventTouchUpInside];
//works but i have warnings
button.urlString = [file objectForKey:#"linkURL"] ;
CGRect frame = CGRectZero;
frame.size = buttonImage.size;
button.frame = frame;
NSString *name = [file objectForKey:#"name"];
NSString *description = [file objectForKey:#"description"];
//Create Box
}
}
}
- (void) openBrowser:(id)sender {
if ([sender isKindOfClass:[MyButton class]]) {
[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[(MyButton *)sender urlString]]];
}
}
tag is an int type. So you cannot store NSString URL here. You need to store URLs in some other place, may be in a NSMutableArray. Store index i in button's tag and store URL in a NSMutableArray in position i. Then in button handler use the tag as the index to get URL from that NSMutableArray.
And not related with the question, you are not releasing _json NSArray. So you are leaking memory. And also you don't need to test if ([_json count] > 0). Your for loop is already handling that.