I have simple UIWebView app that load the html, the problem is that the UIWebView does not rotate when I rotate the device.
Here is the ViewController.m
#import "WrapperViewController.h"
#implementation WrapperViewController
- (void) viewDidLoad
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle bundlePath];
NSString *fullPath = [NSBundle pathForResource:#"index"
ofType:#"htm" inDirectory:path];
[webView loadRequest:[NSURLRequest requestWithURL:
[NSURL fileURLWithPath:fullPath]]];
}
- (BOOL) shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
-(BOOL)shouldAutorotate{
return YES;
}
- (void) didRotateFromInterfaceOrientation:
(UIInterfaceOrientation)fromInterfaceOrientation
{
webView.scalesPageToFit = YES;
webView.backgroundColor = [UIColor blackColor];
}
- (void) didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void) dealloc
{
[super dealloc];
}
#end
Related
I have several CoreDataTableViewControllers that utilize the helper class from Paul Hegarty's course. Everyone of them works except this one, and I cannot see a difference.
When the table first comes up, it is correctly populated and the segue executes properly when a cell is selected. However when I hit the back button, the table displays (null), (null) everywhere.
I have tried every variant of calling [self useDocument] that I can think of, still to no avail. Any thoughts? Thanks in advance.
//
// TeamTableViewController.m
//
#import "TeamTableViewController.h"
#import "iTrackAppDelegate.h"
#import "CoreDataTableViewController.h"
#import "SchoolRecords.h"
#import "ScheduleViewController.h"
#interface TeamTableViewController ()
#property NSInteger toggle;
#end
#implementation TeamTableViewController
#synthesize iTrackContext = _iTrackContext;
#synthesize schoolSelected = _schoolSelected;
-(void) setSchoolSelected:(SchoolRecords *)schoolSelected
{
_schoolSelected = schoolSelected;
}
-(void) setITrackContext:(NSManagedObjectContext *)iTrackContext
{
if(_iTrackContext != iTrackContext){
if (!iTrackContext) {
MyCoreDataHandler* cdh =
[(iTrackAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];
_iTrackContext = cdh.context;
} else {
_iTrackContext = iTrackContext;
}
}
[self useDocument];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)setupFetchedResultsController // attaches an NSFetchRequest to this UITableViewController
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"SchoolRecords"];
// no predicate because we want ALL the Athletes
request.sortDescriptors = [NSArray arrayWithObjects:
[NSSortDescriptor sortDescriptorWithKey:#"schoolName" ascending:YES],
nil];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.iTrackContext
sectionNameKeyPath:nil
cacheName:nil];
__block NSInteger myCount;
int64_t delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self.iTrackContext performBlock:^(void){NSError* requestError = nil;
myCount = [self.iTrackContext countForFetchRequest:request error:&requestError];
NSLog(#"In %# and count of iTrackContext = %lu", NSStringFromClass([self class]),(unsigned long)myCount);
}];
if (!myCount || myCount == 0) {
[self displayAlertBoxWithTitle:#"No Teams" message:#"Have you added athletes yet? \nPlease go to Add Athletes" cancelButton:#"Okay"];
}
});
}
- (void)useDocument
{
if (self.iTrackContext) {
[self setupFetchedResultsController];
} else {
NSString* errorText = #"A problem arose opening the search results database of Athletes.";
[self displayAlertBoxWithTitle:#"File Error" message:errorText cancelButton:#"Okay"];
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (!self.iTrackContext) {
MyCoreDataHandler* cdh =
[(iTrackAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];
[self setITrackContext:cdh.context];
} else {
NSLog(#"In %# of %#. Getting ready to call useDocument",NSStringFromSelector(_cmd), self.class);
[self useDocument];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// If divide into sections use line below otherwise return 1.
// return [[self.fetchedResultsController sections] count];
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Do not really need this with only one section, but makes code usable if add sections later.
return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"teamInformation";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
SchoolRecords *schoolResults = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString* titleText = schoolResults.schoolName;
cell.textLabel.text = titleText;
cell.detailTextLabel.text = [NSMutableString stringWithFormat:#"%#, %#", schoolResults.schoolCity, schoolResults.schoolState];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
# pragma navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
[self setSchoolSelected:[self.fetchedResultsController objectAtIndexPath:indexPath]];
// be somewhat generic here (slightly advanced usage)
// we'll segue to ANY view controller that has a photographer #property
if ([segue.identifier isEqualToString:#"scheduleDetailSegue"]) {
// use performSelector:withObject: to send without compiler checking
// (which is acceptable here because we used introspection to be sure this is okay)
NSLog(#"Preparing to passing school with schoolID = %#", self.schoolSelected.schoolID);
[segue.destinationViewController convenienceMethodForSettingSchool:self.schoolSelected];
}
}
- (void) displayAlertBoxWithTitle:(NSString*)title message:(NSString*) myMessage cancelButton:(NSString*) cancelText
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:myMessage
delegate:nil
cancelButtonTitle:cancelText
otherButtonTitles:nil];
[alert show];
}
#end
Well, I am not certain what the problem was. I ended up deleting the "offending" TableViewControllers in StoryBoard and recreated them. That did the trick. In retrospect, I wonder if I did not specify the wrong type of segue from my tabViewController. But I deleted it before I thought of that possibility.
I have written a Singleton Class for managing iAds.The iAds pop up after 5 seconds of the user inactivity. The idleTimerExceeded call generate a notification to show the iAd. This code works fine for my requirements but since I am new to iOS development, my application sometimes hangs unexpectedly after integrating this code. This code results in lots of warnings etc. I would like to optimize my code in terms of memory and performance.
I would be very thankful for your kind suggestions and reviews.
Below is my code:
iAdSingleton.h
#import <Foundation/Foundation.h>
#import "AppDelegate.h"
#import "iAd/iAd.h"
#interface iAdSingleton : UIViewController<ADBannerViewDelegate> {
ADBannerView *adView;
UIViewController *displayVC;
NSTimer *idleTimer;
BOOL isItFirstTime;
}
#property (nonatomic, retain) ADBannerView *adView;
#property (nonatomic, retain) UIViewController *displayVC;
#property (nonatomic) BOOL isItFirstTime;
+ (id) shareAdSingleton;
- (void) resetIdleTimer;
- (void) idleTimerExceeded;
#end
iAdSingleton.m
#import "iAdSingleton.h"
#implementation iAdSingleton
static iAdSingleton* _sharedAdSingleton = nil;
BOOL bannerVisible = NO;
BOOL controlAccessBannerVisibility = NO;
#synthesize adView, displayVC;
#synthesize isItFirstTime;
#define kMaxIdleTimeSeconds 5.0
+(id)sharedAdSingleton
{
#synchronized(self)
{
if(!_sharedAdSingleton)
_sharedAdSingleton = [[self alloc] init];
return _sharedAdSingleton;
}
return nil;
}
+(id)alloc
{
#synchronized([iAdSingleton class])
{
NSAssert(_sharedAdSingleton == nil, #"Attempted to allocate a second instance of a singleton.");
_sharedAdSingleton = [super alloc];
return _sharedAdSingleton;
}
return nil;
}
-(id)init
{
self = [super init];
if (self != nil) {
/* Initialize The Parameters Over Here */
//adView = [[ADBannerView alloc] initWithFrame:CGRectMake(0, 480, 0, 0)];
adView = [[ADBannerView alloc] init];
adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
self.adView.delegate=self;
[self resetIdleTimer];
}
return self;
}
-(void)dealloc
{
displayVC = nil;
if (adView) {
[adView removeFromSuperview]; //Remove ad view from superview
[adView setDelegate:nil];
adView = nil;
}
[super dealloc];
}
-(UIViewController *)viewControllerForPresentingModalView
{
return displayVC;
}
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
banner.hidden = NO;
if(!bannerVisible){
NSLog(#"Banner Changes 1 - Purpose: Visibility");
// [UIView beginAnimations:#"bannerAppear" context:NULL];
// banner.frame = CGRectOffset(banner.frame, 0, -100);
// [UIView commitAnimations];
bannerVisible = YES;
controlAccessBannerVisibility = YES;
}
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
//NSLog(#"Unable to receive Ad.");
NSLog(#"Banner Changes 2 - Purpose: Unable to Receive Ad.");
banner.hidden = YES;
if(bannerVisible){
[UIView beginAnimations:#"bannerDisappear" context:NULL];
banner.frame = CGRectOffset(banner.frame, 0, 100);
[UIView commitAnimations];
bannerVisible = NO;
}
}
- (BOOL) bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
{
NSLog(#"Pause anything necessary");
return YES;
}
- (void) bannerViewActionDidFinish:(ADBannerView *)banner
{
NSLog(#"We now resume to normal operations");
}
- (void)resetIdleTimer {
if (!idleTimer) {
idleTimer = [[NSTimer scheduledTimerWithTimeInterval:kMaxIdleTimeSeconds
target:self
selector:#selector(idleTimerExceeded)
userInfo:nil
repeats:NO] retain];
}
else {
if (fabs([idleTimer.fireDate timeIntervalSinceNow]) < kMaxIdleTimeSeconds-1.0) {
[idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kMaxIdleTimeSeconds]];
/*
Notification: HideAd
*/
NSLog(#"Notification Generated For HideAd");
[[NSNotificationCenter defaultCenter] postNotificationName:#"HideAdBanner" object:nil userInfo:nil];
}
}
}
- (void)idleTimerExceeded {
AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDel.adVisible == NO) {
NSLog(#"Notification Generated For ShowAd");
/*
Notification: ShowAd
*/
if (controlAccessBannerVisibility == YES) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"ShowAdBanner" object:nil userInfo:nil];
}
}
}
#end
This is what you need. This code is thread safe as well as will not have any memory issue and warnings.
+ (iAdSingleton *) sharedInstance
{
static dispatch_once_t onceToken;
static iAdSingleton * __sharedInstance = nil;
dispatch_once(&onceToken, ^{
__sharedInstance = [[self alloc] init];
});
return __sharedInstance;
}
I 'm new to IOS and Objective C.
The scenario is I have 2 buttons, which open (with segue) 2 view controllers containing a UIWebview.
I thought is better to do it with 1 UIWebView so I tried to pass the request object of the webvew and use only one webview controller.
so I got the wwwBtn (UIButton that opens a site) and fbBtn (UIButton that goes to a Facebook URL) my viewController and the wwwWebViewController which contains th UIWebView.
Here is how I did it.
The viewController.h file :
#interface ViewController : UIViewController {
UIButton *wwwBtn;
UIButton *fbButton;
}
#property (retain, nonatomic) IBOutlet UIButton *wwwBtn;
#property (retain, nonatomic) IBOutlet UIButton *fbBtn;
The ViewController.m file :
#import "ViewController.h"
#import "wwwWebViewController.h"
#implementation ViewController
#synthesize wwwBtn;
#synthesize fbBtn;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"web"]) {
NSString *urlstr=#"http ://www.google.com";
wwwWebViewController *vc = [segue destinationViewController];
vc.urlStr = urlstr;
} else if ([[segue identifier] isEqualToString:#"fb"]) {
NSString *urlstr = #"http://www.facebook.com";
wwwWebViewController *vc = [segue destinationViewController];
vc.urlStr = urlstr;
}
}
the wwwWebViewController.h file :
#interface wwwWebViewController : UIViewController {
UIWebView *webView;
}
#property (retain, nonatomic) IBOutlet UIWebView *webView;
The wwwWebViewController.m file :
- (void)viewDidLoad
{
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[super viewDidLoad];
}
Do as the following, you will assign this class to the destination UIViewControllers that you will need to pass the NSString *urlstr to them:
WebViewController.h
#interface WebViewController : UIViewController {
NSString *urlstr;
}
#property (strong, nonatomic) IBOutlet UIWebView *WebView;
#property (strong, nonatomic) NSString *urlstr;
WebViewController.m
#implementation WebViewController
#synthesize WebView;
#synthesize urlstr;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSURL *url = [NSURL URLWithString:urlstr];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[self.WebView loadRequest:requestObj];
}
Now it's time to create two segues from my main storyboard class InfoViewController to the destination class WebViewController, in my case I've created three segues but only two are using the WebViewController class.
You've also to give the segues a spacial Identifier for each to target them programmatically in the main class InfoViewController.
let's check out how the InfoViewController : UITableViewController will look like:
InfoViewController.m
#import "InfoViewController.h"
#import "WebViewController.h"
#interface InfoViewController ()
#end
#implementation InfoViewController
#synthesize AboutCell = _AboutCell;
#synthesize CGCell = _CGCell;
#synthesize FTACell = _FTACell;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *AboutCellClicked = [self.tableView cellForRowAtIndexPath:indexPath];
UITableViewCell *CGCellClicked = [self.tableView cellForRowAtIndexPath:indexPath];
UITableViewCell *FTACellClicked = [self.tableView cellForRowAtIndexPath:indexPath];
if (AboutCellClicked == _AboutCell) {
[self performSegueWithIdentifier:#"AboutPush" sender:self];
} else if (CGCellClicked == _CGCell) {
[self performSegueWithIdentifier:#"CGPush" sender:self];
} else if (FTACellClicked == _FTACell) {
[self performSegueWithIdentifier:#"FTAPush" sender:self];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
WebViewController *webController = [[WebViewController alloc] init];
if ([[segue identifier] isEqualToString:#"CGPush"]) {
NSString *urlstr=#"http://www.google.com";
webController = [segue destinationViewController];
webController.urlstr = urlstr;
} else if ([[segue identifier] isEqualToString:#"FTAPush"]) {
NSString *urlstr=#"http://www.yahoo.com";
webController = [segue destinationViewController];
webController.urlstr = urlstr;
}
}
#end
I hope this will solve your problem, If you have any question do not hesitate to ask.
I want to display login window and then type login and password credencial it will open the account. So i tried but it shows error like
/81: error: 'didReceiveMemoryWarning' undeclared (first use in this function)
*:81: error: expected ';' before '{' token*
100: error: expected declaration or statement at end of input
and i posted below the code please help
Thanks in advance
.h file
#import <UIKit/UIKit.h>
#interface Password1ViewController : UIViewController {
UITextField *textfieldName;
UITextField *textfieldPassword;
}
#property (nonatomic, retain) IBOutlet UITextField *textfieldName;
#property (nonatomic, retain) IBOutlet UITextField *textfieldPassword;
#end
.m file
#import "Password1ViewController.h"
#implementation Password1ViewController
#synthesize textfieldName;
#synthesize textfieldPassword;
-(void)alertView:(UIAlertView *)alertview clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertview cancelButtonIndex])
{
NSLog(#"Name: %#", textfieldName.text);
NSlog(#"Name: %#", textfieldPassword.text);
}
}
-(void) someMethod
{
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"Please Login" message:#"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Submit",nil];
[alert addTextFieldWithValue:#"" label:#"User Name"];
[alert addTextFieldWithValue:#"" label:#"Password"];
textfieldName = [alert textFieldAtIndex:0];
textfieldName.keyboardType = UIKeyboardTypeAlphabet;
textfieldName.keyboardAppearance = UIKeyboardAppearanceAlert;
textfieldName.autocorrectionType = UITextAutocorrectionTypeNo;
textfieldPassword = [alert textFieldAtIndex:1];
textfieldPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
textfieldPassword.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
textfieldPassword.keyboardAppearance = UIKeyboardAppearanceAlert;
textfieldPassword.autocorrectionType = UITextAutocorrectionTypeNo;
textfieldPassword.secureTextEntry = YES;
[alert show];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[textfieldName release];
[textfieldPassword release];
[super dealloc];
}
#end
You were missing a closing brace which I corrected in my edit. So, try now with the edited code.
I want to add simple search bar in the table view. Program getting run with no error, but when I try to add text in search bar, program gets terminates
following is my code:
#interface RootViewController : UITableViewController<UISearchBarDelegate> {
NSArray *list;
IBOutlet UISearchBar *searchBar;
NSMutableArray *searchresult;
BOOL isSearchon;
BOOL canSelectRow;
}
#property(nonatomic, retain)NSArray *list;
#property(nonatomic, retain)IBOutlet UISearchBar *searchBar;
-(void)doneSearching:(id)sender;
-(void)searchlist;
#end
//in .m
#implementation RootViewController
#synthesize list,searchBar;
-(void)doneSearching:(id)sender
{
isSearchon=NO;
canSelectRow=YES;
self.tableView.scrollEnabled=YES;
self.navigationItem.rightBarButtonItem=nil;
[searchBar resignFirstResponder];
[self.tableView reloadData];
}
-(void)searchlist
{NSString *searchText = searchBar.text;
[searchresult removeAllObjects];
for(NSString *str in list)
{
NSRange titleResultsRange=[str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[searchresult addObject:str];
}
}
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
[self searchlist];
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
if([searchText length]>0)
{isSearchon =YES;
canSelectRow=YES;
self.tableView.scrollEnabled=YES;
[self searchlist];}
else{
isSearchon =NO;
canSelectRow=NO;
self.tableView.scrollEnabled=NO;
}
[self.tableView reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
list = [[NSArray alloc]initWithObjects:#"rohan",#"vidhya",#"kavita",#"pushkar",nil];
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType=UITextAutocorrectionTypeYes;
searchresult=[[NSMutableArray alloc]init];
isSearchon =NO;
canSelectRow=YES;
self.navigationItem.title = #"Names";
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
isSearchon =YES;
canSelectRow=NO;
self.tableView.scrollEnabled=NO;
self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneSearching:)]autorelease];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isSearchon){
return [searchresult count];}
else{
return [list count];}
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if(isSearchon)
{
cell.text=[searchresult objectAtIndex:indexPath.row];}
else{
cell.text=[list objectAtIndex:indexPath.row];}
// Configure the cell.
return cell;
}
- (void)dealloc {
[super dealloc];
[searchBar release];
}
#end
I have edited my code in my question...it works fine nw....AnyOne willing to use searchbar in tableview in Iphones can refer the code.