Presenting an Imagepicker in PopOver - iphone

Ive been searching about a multiple image picker, and I stumble to AGImagePickerController, but then, Im coding in iPad, how can I present the picker in a popoverController from a alertView? Is it possible? or should I shift in presenting it via normal UIButton? Please help.
AGImagePickerController *imagePickerController = [[AGImagePickerController alloc] initWithFailureBlock:^(NSError *error) {
NSLog(#"Fail. Error: %#", error);
if (error == nil) {
NSLog(#"User has cancelled.");
[self dismissModalViewControllerAnimated:YES];
} else {
// We need to wait for the view controller to appear first.
double delayInSeconds = 0.015;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self dismissModalViewControllerAnimated:YES];
});
}
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
} andSuccessBlock:^(NSArray *info) {
NSLog(#"Info: %#", info);
[self.selectedPhotos setArray:info];
}
[self dismissModalViewControllerAnimated:YES];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}];
// Show saved photos on top
imagePickerController.shouldShowSavedPhotosOnTop = YES;
imagePickerController.selection = self.selectedPhotos;
// Custom toolbar items
AGIPCToolbarItem *selectAll = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"+ Select All" style:UIBarButtonItemStyleBordered target:nil action:nil] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
return YES;
}];
AGIPCToolbarItem *flexible = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] andSelectionBlock:nil];
AGIPCToolbarItem *selectOdd = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"+ Select Odd" style:UIBarButtonItemStyleBordered target:nil action:nil] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
return !(index % 2);
}];
AGIPCToolbarItem *deselectAll = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"- Deselect All" style:UIBarButtonItemStyleBordered target:nil action:nil] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
return NO;
}];
imagePickerController.toolbarItemsForSelection = [NSArray arrayWithObjects:selectAll, flexible, selectOdd, flexible, deselectAll, nil];
// imagePickerController.toolbarItemsForSelection = [NSArray array];
imagePickerController.maximumNumberOfPhotos = 100;
[self presentModalViewController:imagePickerController animated:YES];
}

you should use this via Round Rect Button:
self.popoverController =
[[UIPopoverController alloc] initWithContentViewController:imagePickerController];
popoverController.delegate = self;
CGRect popoverRect = [self.view convertRect:[YOURBUTTON frame]
fromView:[YOURBUTTON superview]];
popoverRect.size.width = MIN(popoverRect.size.width, 100);
[self.popoverController
presentPopoverFromRect:popoverRect
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
[popoverController setPopoverContentSize:CGSizeMake(1024, 500)];

Related

ImageGallery image in black for ios 7

In my efforts to upgrade my application to support IOS7 I found out that ImageGallery don't load the images. in others iOS is ok.
In imageGalleryView:
- (void)initWithPhotos:(NSMutableArray *)photoURLStrings andCaptions:(NSArray *)myCaptions moveToPage:(int)page {
captions = [myCaptions copy];
photoUrls = [photoURLStrings copy];
NSLog(#"array---> %#", photoUrls);
photoLoaded = [[NSMutableArray alloc] init];
for (int i=0; i<[photoURLStrings count]; i++) {
[photoLoaded addObject:[NSNumber numberWithBool:FALSE]];
}
[pageControl setNumberOfPages:[photoUrls count]];
//scrollView= [[UIScrollView alloc] init];
scrollView.backgroundColor = [UIColor blackColor];
scrollView.pagingEnabled = TRUE;
scrollView.autoresizesSubviews = TRUE;
scrollView.contentSize = CGSizeMake(320 * [photoUrls count], scrollView.frame.size.height);
scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width*page, 0);
if (([captions objectAtIndex:page] == nil) || ([[captions objectAtIndex:page] isEqualToString:#""])) {
[textView setHidden:TRUE];
} else {
[textView setHidden:FALSE];
[textView setText:[captions objectAtIndex:page]];
}
[self showImages:page];}
- (void)showImages:(int)page {
AsyncImageViewController *asyncImageView;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
//NSLog(#"%#",[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]);
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
//NSLog(#"page:%i",page);
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
//[scrollView setBackgroundColor:[UIColor colorWithPatternImage:asyncImageView.image]];
[scrollView addSubview:asyncImageView];
[asyncImageView release];
}
}
page = page - 1;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
[scrollView addSubview:asyncImageView];
[asyncImageView release];
}
}
page = page + 2;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
[scrollView addSubview:asyncImageView];
//[scrollView setBackgroundColor:[UIColor colorWithPatternImage:asyncImageView.image]];
[asyncImageView release];}}}
In the asyncimageview:
- (void)loadImageFromURL:(NSURL*)url pos:(int) posicio {
if (connection!=nil) { [connection release]; }
if (data!=nil) { [data release]; }
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
if (posicio == 0) {
loading.center = CGPointMake(75/2,75/2);
}else {
loading.center = CGPointMake(160,210);
}
[loading startAnimating];
[self addSubview:loading];
[loading release];}//the URL connection calls this repeatedly as data arrives- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
[data appendData:incrementalData];}//the URL connection calls this once all the data has downloaded- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
//so self data now has the complete image
[connection release];
connection=nil;
if ([[self subviews] count]>0) {
//then this must be another image, the old one is still in subviews
[[[self subviews] objectAtIndex:0] removeFromSuperview]; //so remove it (releases it also)
}//make an image view for the image
imageView = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
//make sizing choices based on your needs, experiment with these. maybe not all the calls below are needed.
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight );
//[self setBackgroundColor:[UIColor colorWithPatternImage:imageView]];
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout];
[self setNeedsLayout];
[loading stopAnimating];
[data release]; //don't need this any more, its in the UIImageView now
data=nil;}
//just in case you want to get the image directly, here it is in subviews- (UIImage*) image {
UIImageView* iv = [[self subviews] objectAtIndex:0];
return [iv image];}
I checked all and saw that it is UIView instead of UIImageView. probably Apple changed something. But xCode don't throw any errors.
Any idea how to fix it?

Selected text/string not firing

Am using UIMenuController for showing up wikipedia, dictionary and highlighting the text. I did the following,
- (void)viewDidLoad
{
UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(handleLongPress)];
longPressGestureRecognizer.minimumPressDuration =0.4;
longPressGestureRecognizer.delegate=self;
[webView addGestureRecognizer:longPressGestureRecognizer];
[longPressGestureRecognizer release];
}
- (void)handleLongPress//:(id)sender
{
//location = [recognizer locationInView:self.view];
//
// NSLog(#"location :%d",location);
UIMenuController *menuController = [UIMenuController sharedMenuController];
[self becomeFirstResponder];
UIMenuItem *item = [[[UIMenuItem alloc] initWithTitle: #"Wikipedia"
action: #selector(wiki:)] autorelease];
UIMenuItem *item1 = [[[UIMenuItem alloc] initWithTitle: #"Dictionary"
action: #selector(dict:)] autorelease];
UIMenuItem *item2 = [[[UIMenuItem alloc] initWithTitle: #"Highlight"
action: #selector(highlighting:)] autorelease];
[menuController setTargetRect:CGRectMake(100, 100, 320, 100) inView:webView];
[menuController setMenuVisible:YES animated:YES];
[menuController setMenuItems: [NSArray arrayWithObjects: item,item1,item2,nil]];
}
-(BOOL)canBecomeFirstResponder
{
return YES;
}
- (BOOL) canPerformAction:(SEL)action withSender:(id)sender
{
if (action == #selector( wiki:))
{
return YES; // logic here for context menu show/hide
}
if (action == #selector( dict:))
{
return YES; // logic here for context menu show/hide
}
if (action == #selector(highlighting:))
{
// turn off copy: if you like:
return YES;
}
return [super canPerformAction: action withSender: sender];
}
- (void)wiki: (id) sender
{
NSString *shareUrlString = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/%#",[self selectedText]];
NSLog(#"selectedText Wiki: %#",[self selectedText]);
//Create the URL string which will tell Facebook you want to share that specific page
NSURL *url = [ [ NSURL alloc ] initWithString:shareUrlString ];
//Create the URL object
[[UIApplication sharedApplication] openURL:url];
//Launch Safari with the URL you created
[url release];
}
- (NSString *)selectedText
{
return [webView stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
}
Am able to get the wikipedia website but not with the selected text/word. What's the problem in the above code? Thanks in advance.

toggle between UIBarButtonSystemItemPlay and UIBarButtonSystemItemPause

Have two UIBarButtonItems want to make it as one UIBarButtonItem and toggle between them
UIBarButtonItem *systemItem1 = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemPlay
target:self
action:#selector(playaudio:)];
systemItem1.style = UIBarButtonItemStyleBordered;
UIBarButtonItem *systemItem2 = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemPause
target:self
action:#selector(pause:)];
systemItem2.style = UIBarButtonItemStyleBordered;
// flex item used to put space in between buttons
UIBarButtonItem *flexItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
//Add buttons to the array
NSArray *toolbarItems = [NSArray arrayWithObjects: settingsButton, flexItem, systemItem, flexItem, systemItem1,flexItem, systemItem2, flexItem, systemItem3, flexItem, modalBarButtonItem, nil];
[toolbar setItems:toolbarItems];
[settingsButton release];
[systemItem release];
[systemItem1 release];
[systemItem2 release];
[systemItem3 release];
[modalBarButtonItem release];
[flexItem release];
-(void) playaudio: (id) sender {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"theme"
ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
audioPlayer.currentTime = 0;
[audioPlayer play];
[fileURL release];
}
- (void)pause: (id)sender {
if
([audioPlayer isPlaying])
{[audioPlayer pause];}
else
{[audioPlayer play];}
}
Any ideas how i can do that.
Essentially, every time the play/pause status is updated, you're going to want to run a method to update the toolbar. Something like this should work.
You can create a method like this:
-(void)playPause{
if(audioPlayer == nil){
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"theme" ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
audioPlayer.currentTime = 0;
[fileURL release];
}
UIBarButtonSystemItem buttontype = UIBarButtonSystemItemPlay;
if([audioPlayer isPlaying]){
[audioPlayer pause];
}
else {
[audioPlayer play];
buttontype = UIBarButtonSystemItemPause;
}
UIBarButtonSystemItem *item = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:buttontype
target:self
action:#selector(playPause)] autorelease];
self.toolbar.items = [NSArray arrayWithObject:item];
}
I had a much simpler solution to that issue:
- (void) setStartStopButton:(BOOL)startorstop
{
UIBarButtonItem *startStopButton = nil;
if (startorstop == YES) {
startStopButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:#selector(startStopAction:)];
}
else
{
startStopButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:#selector(startStopAction:)];
}
self.navigationItem.rightBarButtonItem = startStopButton;
[startStopButton release];
}
- (IBAction)startStopAction:(id)sender
{
if (task.isActive)
{
[task stopTask];
}
else
{
[task startTask];
}
[self setStartStopButton:task.isActive];
}
And then I call the first method to set the button in viewWillAppear as well to set the button before the view appears onscreen.

UIWebView controller troubles

guys. I have two view controllers with two uiwebviews.
Here is my code:
First controller:
#import "articleView.h"
#interface articleView (Private)
- (BOOL) string:(NSString *)string containsString:(NSString *) stringToFind;
#end
#implementation articleView
#synthesize item;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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];
center = loaderView.bounds;
loadingArticleContent = 0;
if ([item objectForKey:#"article"] == nil) {
[LoadingView showLoadingViewAddedTo:loaderView];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loaderView.alpha = 0.7;
[UIView commitAnimations];
NSString *link = [item objectForKey:#"link"];
currentArticleLoader *loader = [[currentArticleLoader alloc] init];
loader.link = link;
loader.delegate = self;
[loader load];
} else {
if (webView.loading == NO) {
[self loadWebView:(NSString *)[item objectForKey:#"article"]];
}
}
UIBarButtonItem *itemBar = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:#selector(showToolbar)];
self.navigationItem.rightBarButtonItem = itemBar;
[itemBar release];
self.title = (NSString *)[item objectForKey:#"title"];
self.navigationController.toolbar.tintColor = self.navigationController.navigationBar.tintColor;
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
favorited = [[[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"] mutableCopy];
if (favorited.count == 0) {
favorited = [[NSMutableArray alloc] init];
[[NSUserDefaults standardUserDefaults] setObject:favorited forKey:#"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
bought = [[NSUserDefaults standardUserDefaults] boolForKey:#"com.unnamed.habr.full"];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:#selector(share)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"28-star.png"] style:UIBarButtonItemStylePlain target:self action:#selector(addToFavorites)];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"71-compass.png"] style:UIBarButtonItemStylePlain target:self action:#selector(openInSafari)];
if (bought == NO) {
item2.enabled = NO;
}
if ([favorited containsObject:item] == NO) {
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item3, space, item2, nil]];
} else {
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item3, nil]];
}
[space release];
[item1 release];
[item2 release];
[item3 release];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController isToolbarHidden] == NO) {
[self.navigationController setToolbarHidden:YES animated:YES];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void) updated:(NSString *)string {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loaderView.bounds = CGRectMake(-90, 110, 110, 110);
loaderView.alpha = 0.5;
[UIView commitAnimations];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:item];
[dict setValue:string forKey:#"article"];
item = [[NSDictionary alloc] initWithDictionary:dict];
[self loadWebView:string];
[dict release];
}
- (void) loadWebView:(NSString *)body {
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString *title = [item objectForKey:#"title"];
NSString *blog = [item objectForKey:#"blog"];
NSString *bloglink = [item objectForKey:#"bloglink"];
NSString *author = [item objectForKey:#"author"];
NSString *html = [[NSString alloc] initWithFormat:#"<html><head></script><link rel=\"stylesheet\" href=\"mobile.css\" type=\"text/css\" media=\"all\" charset=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head><body><h3>%# → %# </h3> </br> %# </br> <div class=​\"m\">​Автор: %#</div></body></html>", bloglink, blog, title, body, author];
loadingArticleContent = 1;
[webView loadHTMLString:html baseURL:baseURL];
[html release];
}
- (void)addToFavorites {
[favorited addObject:item];
[[NSUserDefaults standardUserDefaults] setObject:favorited forKey:#"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"124-bullhorn.png"] style:UIBarButtonItemStylePlain target:self action:#selector(share)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"71-compass.png"] style:UIBarButtonItemStylePlain target:self action:#selector(openInSafari)];
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item2, nil]];
[space release];
[item1 release];
[item2 release];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSLog(#"Link: %#", [[request mainDocumentURL] absoluteString]);
if (bought == YES && loadingArticleContent == 0) {
if ([self string:[[request mainDocumentURL] absoluteString] containsString:#"m.habrahabr.ru/blog/"] ||[self string:[[request URL] absoluteString] containsString:#"m.habrahabr.ru/company/"]) {
ViewController *controller = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
controller.url = [request mainDocumentURL];
controller.title = [NSString stringWithFormat:#"%#", (NSString *)[item objectForKey:#"blog"]];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
} else {
webViewController *controller = [[webViewController alloc] initWithNibName:#"webViewController" bundle:nil];
controller.url = [request URL];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
}
} else {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"iHabr" message:#"Просмотр ссылок возможен только в полной версии программы, как и многие другие функции. Произвести покупку можно на вкладке \"Избранное\"" delegate:self cancelButtonTitle:#"Понятно :(" otherButtonTitles:nil] autorelease];
[alert show];
}
return NO;
} else if (loadingArticleContent == 1) {
loadingArticleContent = 0;
return YES;
}
return YES;
}
- (BOOL) string:(NSString *)string containsString:(NSString *) stringToFind {
NSRange rng = [string rangeOfString:stringToFind];
return rng.location != NSNotFound;
}
- (void) webViewDidFinishLoad:(UIWebView *)webView {
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"124-bullhorn.png"] style:UIBarButtonItemStylePlain target:self action:#selector(share)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"28-star.png"] style:UIBarButtonItemStylePlain target:self action:#selector(addToFavorites)];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"71-compass.png"] style:UIBarButtonItemStylePlain target:self action:#selector(openInSafari)];
if (bought == NO) {
item2.enabled = NO;
}
if ([favorited containsObject:item] == NO) {
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item3, space, item2, nil]];
} else {
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item3, nil]];
}
[space release];
[item1 release];
[item2 release];
[item3 release];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
loaderView.alpha = 0;
[UIView commitAnimations];
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"iHabr" message:[NSString stringWithFormat:#"Не удалось загрузить статью. %#", error] delegate:nil cancelButtonTitle:#"Понятно :(" otherButtonTitles: nil] autorelease];
[alert show];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loaderView.hidden = YES;
[UIView commitAnimations];
}
#end
Second controller:
#import "webViewController.h"
#implementation webViewController
#synthesize url;
- (void)viewDidLoad
{
[super viewDidLoad];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];
UIBarButtonItem *itemBar;
itemBar = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:#selector(showToolbar)];
self.navigationItem.rightBarButtonItem = itemBar;
[itemBar release];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[self setToolbarItems:[NSArray arrayWithObjects:space, item1, space, item2,item3, space, item4, space, nil]];
[space release];
[LoadingView showLoadingViewAddedTo:loadingView];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loadingView.alpha = 0.7;
[UIView commitAnimations];
}
- (void) webViewDidStartLoad:(UIWebView *)webView {
item1.enabled = NO;
item2.enabled = NO;
item3.enabled = NO;
item4.enabled = NO;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loadingView.alpha = 0.7;
[UIView commitAnimations];
}
- (void) webViewDidFinishLoad:(UIWebView *)webView {
if (webView.canGoBack) {
item1.enabled = YES;
}
if (webView.canGoForward) {
item4.enabled = YES;
}
item2.enabled = YES;
item3.enabled = YES;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loadingView.alpha = 0;
[UIView commitAnimations];
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"iHabr" message:[NSString stringWithFormat:#"Не удалось загрузить страницу. %#", [error userInfo]] delegate:nil cancelButtonTitle:#"Понятно :(" otherButtonTitles: nil] autorelease];
[alert show];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loadingView.alpha = 0;
[UIView commitAnimations];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController isToolbarHidden] == NO) {
[self.navigationController setToolbarHidden:YES animated:YES];
}
}
After opening URL in second controller, and going back to first, some scrolling up and down - my app showing error EXC_BAD_ACCESS. I turned on NSZombieEnable and now I see this:
* -[webViewController respondsToSelector:]: message sent to deallocated instance 0xec624b0
in my console.
You have to be sure to set the delegate property of the web view to nil before it goes away. Do this both in your dealloc and viewDidUnload methods, since viewDidUnload is not always called before dealloc. What’s happening is that after your view controller is deallocated, the web view still has a reference to its address, and is trying to send it a message (-respondsToSelector:).

UIButton view unrecognized selector sent to instance

Basically i have a UIToolbar on the main window and when i hit the infobutton to open a modal view application is crashing with output message that UIButton view unrecognized selector sent to instance. Can someone please help me to solve this output message.
UIButton *infoItem = [[UIButton buttonWithType:UIButtonTypeInfoLight] retain];
infoItem.frame = CGRectMake(250.0, 8.0, 25.0, 25.0);
infoItem.backgroundColor = [UIColor clearColor];
[infoItem addTarget:self action:#selector(displayModalViewaction:) forControlEvents:UIControlEventTouchUpInside];
infoItem.backgroundColor = [UIColor grayColor];
UIBarButtonItem *flexItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
NSArray *toolbarItems = [NSArray arrayWithObjects: settingsButton, flexItem, systemItem, flexItem, systemItem1,flexItem, systemItem2, flexItem, systemItem3, flexItem, infoItem, nil];
[toolbar setItems:toolbarItems];
[settingsButton release];
[systemItem release];
[systemItem1 release];
[systemItem2 release];
[systemItem3 release];
[infoItem release];
[flexItem release];
[super viewDidLoad];
- (void) playaudio: (id) sender {
// Get the file path to the song to play.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"theme"
ofType:#"mp3"];
// Convert the file path to a URL.
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
//Initialize the AVAudioPlayer.
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
// Making sure the audio is at the start of the stream.
self.audioPlayer.currentTime = 0;
[self.audioPlayer play];
}
- (void)pause: (id)sender {
if
([audioPlayer isPlaying])
{[audioPlayer pause];}
else
{[audioPlayer play];}
}
- (void)stop: (id) sender
{
[audioPlayer stop];
}
- (void)displayModalViewaction
{
self.viewController = [[Infoviewcontroller alloc] init];
UINavigationController *navigationController=[[UINavigationController alloc] init];
navigationController.navigationBar.tintColor = [UIColor brownColor];
[navigationController pushViewController:_viewController animated:YES];
[self.view addSubview:navigationController.view];
}
Appreciate help to solve this.
Thanks in advance.
[infoItem addTarget:self action:#selector(displayModalViewaction:) forControlEvents:UIControlEventTouchUpInside];
infoItem.backgroundColor = [UIColor grayColor];
should be
[infoItem addTarget:self action:#selector(displayModalViewaction) forControlEvents:UIControlEventTouchUpInside];
infoItem.backgroundColor = [UIColor grayColor];
because displayModalViewaction do not receive any parameters.
use #selector(displayModalViewaction) to add event;
or change method define with: -(void)displayModalViewaction:(id)sender;