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.
Related
I am working on ELCAlbumPickerController, i am able to select multiple images and upload, but in addition i want to get the file name and datatype of the file. how can i do that?
I am able to select either image or video , how can i select both image and video and any file at a time?
Please find my code below for your reference.
- (void)viewDidLoad {
UIImage *anImage = [UIImage imageNamed:#"elc-ios-icon.png"];
NSArray *Items = [NSArray arrayWithObjects:
#"A text line",
anImage, nil];
UIActivityViewController *ActivityView =
[[UIActivityViewController alloc]
initWithActivityItems:Items applicationActivities:nil];
[self presentViewController:ActivityView animated:YES completion:nil];
}
- (IBAction)launchController
{
ELCAlbumPickerController *albumController = [[ELCAlbumPickerController alloc] initWithNibName: nil bundle: nil];
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:albumController];
[albumController setParent:elcPicker];
[elcPicker setDelegate:self];
ELCImagePickerDemoAppDelegate *app = (ELCImagePickerDemoAppDelegate *)[[UIApplication sharedApplication] delegate];
if ([app.viewController respondsToSelector:#selector(presentViewController:animated:completion:)]){
[app.viewController presentViewController:elcPicker animated:YES completion:nil];
} else {
[app.viewController presentModalViewController:elcPicker animated:YES];
}
[elcPicker release];
[albumController release];
}
- (IBAction)launchSpecialController
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
self.specialLibrary = library;
[library release];
NSMutableArray *groups = [NSMutableArray array];
[_specialLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
[groups addObject:group];
} else {
// this is the end
[self displayPickerForGroup:[groups objectAtIndex:0]];
}
} failureBlock:^(NSError *error) {
self.chosenImages = nil;
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Album Error: %# - %#", [error localizedDescription], [error localizedRecoverySuggestion]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
NSLog(#"A problem occured %#", [error description]);
// an error here means that the asset groups were inaccessable.`
// Maybe the user or system preferences refused access.
}];
}
- (void)displayPickerForGroup:(ALAssetsGroup *)group
{
ELCAssetTablePicker *tablePicker = [[ELCAssetTablePicker alloc] initWithNibName: nil bundle: nil];
tablePicker.singleSelection = YES;
tablePicker.immediateReturn = YES;
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:tablePicker];
elcPicker.delegate = self;
tablePicker.parent = elcPicker;
// Move me
tablePicker.assetGroup = group;
[tablePicker.assetGroup setAssetsFilter:[ALAssetsFilter allAssets]];
if ([self respondsToSelector:#selector(presentViewController:animated:completion:)]){
[self presentViewController:elcPicker animated:YES completion:nil];
} else {
[self presentModalViewController:elcPicker animated:YES];
}
[tablePicker release];
[elcPicker release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return YES;
} else {
return toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}
}
#pragma mark ELCImagePickerControllerDelegate Methods
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]){
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
for (UIView *v in [_scrollView subviews]) {
[v removeFromSuperview];
}
CGRect workingFrame = _scrollView.frame;
workingFrame.origin.x = 0;
images = [NSMutableArray arrayWithCapacity:[info count]];
for(NSDictionary *dict in info) {
UIImage *image = [dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[_scrollView addSubview:imageview];
[imageview release];
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
}
self.chosenImages = images;
NSLog(#"Images:%#",images);
[_scrollView setPagingEnabled:YES];
[_scrollView setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];
for (int i=0; i< images.count; i++) {
NSData *image = UIImageJPEGRepresentation(images[i], 0.1);
NSLog(#"NSDATA:%#",image);
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"name=thefile&&filename=recording"];
[urlString appendFormat:#"%#", image];
NSLog(#"urlstring:%#",urlString);
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString * namecount=[NSString stringWithFormat:#"fn%i.png",i];
NSString * baseurl =[[NSString alloc]initWithFormat:#"http://199.198.12.555/serviceService.svc/serviceupload?fileName=%#",namecount];
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:image];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
}
NSLog(#"%#",images[0]);
NSLog(#"%lu",(unsigned long)images.count);
}
-(IBAction)upload:(id)sender{
}
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]){
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
}
- (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
{
[_specialLibrary release];
[_scrollView release];
[super dealloc];
}
#end
#implementation APActivityProvider
- (id) activityViewController:(UIActivityViewController *)activityViewController
itemForActivityType:(NSString *)activityType
{
if ( [activityType isEqualToString:UIActivityTypePostToTwitter] )
return #"This is a #twitter post!";
if ( [activityType isEqualToString:UIActivityTypePostToFacebook] )
return #"This is a facebook post!";
if ( [activityType isEqualToString:UIActivityTypeMessage] )
return #"SMS message text";
if ( [activityType isEqualToString:UIActivityTypeMail] )
return #"Email text here!";
if ( [activityType isEqualToString:#"it.albertopasca.myApp"] )
return #"OpenMyapp custom text";
return nil;
}
- (id) activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController { return #""; }
#end
#implementation APActivityIcon
- (NSString *)activityType { return #"it.albertopasca.myApp"; }
- (NSString *)activityTitle { return #"Open Maps"; }
- (UIImage *) activityImage { return [UIImage imageNamed:#"elc-ios-icon.png"]; }
- (BOOL) canPerformWithActivityItems:(NSArray *)activityItems { return YES; }
- (void) prepareWithActivityItems:(NSArray *)activityItems { }
- (UIViewController *) activityViewController { return nil; }
- (void) performActivity {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"maps://"]];
}
#end
Thanks
You can get the asset URL using the key UIImagePickerControllerReferenceURL which would give the 'name', but that probably won't be very useful as its probably a UUID. The UIImagePickerControllerMediaType key contains the type.
I am building one iPhone application where I have two views one for login view and another for web view. When user enters the login credentials, then it will redirect to web view. while loading the webview from login view too much time is taking to load. hence I used alertview to show loading image.
#interface FocusViewController ()
#end
#implementation FocusViewController
#synthesize txtsecurecode;
#synthesize webView;
#synthesize OrganizationCode;
UIActivityIndicatorView *indicator;
UIAlertView *alert;
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = (FocusAppDelegate *)[[UIApplication sharedApplication]delegate];
if(appDelegate.data.strOrganizationCode == nil || appDelegate.data.strAccessCode == nil)
{
NSLog(#"YOUR FIRST SCREEN");
_loginView.hidden = NO;
webView.hidden = YES;
}
else
{
NSLog(#"LOAD WEBVIEW DIRECTLY\n");
NSLog(#"Organization Code -> %# \n Secure Access Code -> %#",appDelegate.data.strOrganizationCode,appDelegate.data.strAccessCode);
OrganizationCode.text = appDelegate.data.strOrganizationCode ;
txtsecurecode.text = appDelegate.data.strAccessCode;
[self loginClicked:nil];
webView.hidden = NO;
_loginView.hidden = YES;
}
}
- (IBAction)loginClicked:(id)sender {
#try {
if([[txtsecurecode text] isEqualToString:#""] || [[OrganizationCode text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter Access code" :#"Login Failed!":0];
}
else
{
NSString *post =[[NSString alloc] initWithFormat:#"txtsecurecode=%# #&password=%#",[txtsecurecode text],[OrganizationCode text]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://myexample.com/AccountService/security/ValidateAccess?accesscode=%#&companycode=%#&type=1", txtsecurecode.text, OrganizationCode.text]];
NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];
if([responseData isEqualToString:#""]){
[self alertStatus:#"Please enter valid Access Code" :#"Login Failed !" :0];
}
else
{
appDelegate.data.strOrganizationCode = OrganizationCode.text;
appDelegate.data.strAccessCode = txtsecurecode.text;
[FocusAppDelegate addCustomObjectToUserDefaults:appDelegate.data key:kCredentails];
//Updated
_loginView.hidden = YES;
webView.hidden = NO;
responseData = [responseData stringByReplacingOccurrencesOfString:#" "" " withString:#""];
NSString* encodedString = [responseData stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#" ,encodedString);
alert = [[[UIAlertView alloc] initWithTitle:#"Loading\nPlease Wait..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
[alert show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
indicator.center = CGPointMake(alert.bounds.size.width / 2, alert.bounds.size.height - 50);
[indicator startAnimating];
[alert addSubview:indicator];
[indicator release];
webView.backgroundColor = [UIColor clearColor];
webView.opaque = NO;
webView.delegate = self;
webView.frame = self.view.bounds;
NSString* urlTwo = [[encodedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
stringByReplacingOccurrencesOfString:#"%22" withString:#""];
NSURL *url2;
if([urlTwo hasPrefix:#"http://"]){
url2 = [NSURL URLWithString:urlTwo];
}else{
url2 = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#" , urlTwo]];
}
NSLog(#"url2:%#", url2);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[webView loadRequest:requestObj];
[[self view] addSubview:webView];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!" :0];
}
}
-(void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(#"webViewDidStartLoad");
[self.view addSubview:self.indicator];
alert.hidden = NO;
}
- (void) webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"webViewDidFinishLoad");
[self.indicator removeFromSuperview];
[self.alert dismissWithClickedButtonIndex:1 animated:NO] ;
}
- (IBAction)backgroundClick:(id)sender
{
[txtsecurecode resignFirstResponder];
[OrganizationCode resignFirstResponder];
}
#end
Until content in webview displays, loading image is displaying and working good. but content of webview is not editable and remaining static as I think I used 'web view.hidden = YES'. when I comment the alert method and run then content of webview is also editable and working good as required. I need to load the content of url after loading image stops loading.
I would suggest show the activity indicator from the Viewcontroller having the WebView and implement the WebView Delegate methods
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[actvityIndicator startAnimating];
}
and
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[actvityIndicator stopAnimating];
}
this will keep your webview Interactive and also show the indicator till the page loads completely
you can try something like this. The Delegate is important in .h file
FocusViewController.h
#interface FocusViewController : UIViewController <UIWebViewDelegate> {
UIActivityIndicatorView *indicator;
}
FocusViewController.m
- (void)viewDidLoad
{
// Loading Indicator
indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[indicator setColor:[UIColor colorWithRed:50.0/255.0 green:120.0/255.0 blue:200.0/255.0 alpha:1.0]];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[indicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[indicator stopAnimating];
}
I am having some difficulty figuring out the best way to get my uitextfields to not be hidden when the keyboard popsup. Right now i have a UIView that contains a uitableview subview and button.
*The tableview that is inside the uiview is actually a uiviewcontroller with a programatically created tableivew, so it is not controlled by a uitableviewcontroller.
I have done research and i think i would need a scrollview then add the view to the scrollview and work on some scrolling when a specific textfield is selected and is hidden with the keyboard up scroll it up.
Is this a good approach ?
UPDATE:
I have two seperate Viewcontrollers. For-example let say MainViewcontroller and SecondViewcontroller. The secondviewcontroller has a uitableview in it. The cells inside of the tableview have textboxes which store user information(like a form). Then what i did was created an object of secondviewcontroller inside of mainviewcontroller. I did this becuause i need to have a "Next Button" at the bottom of the view. When I select a field where it would be located underneith the keyboard when it pops up i would like to have it scroll up and when closed it will go down. I had to use an object of uitableview because the Mainviewcontroller class would be way to big.(Please correct me if i am wrong). Thanks for the reply.
Here is a screenshot of what i am trying to do...
FUll UIView: http://postimage.org/image/puzdwpj3t/
With Keyboard open: http://postimage.org/image/g5nkwzwpd/
//Here is some code:
1. The first class here is for instance SecondViewcontroller.
2. The second section of code is for instance the mainviewcontroller, which creates an object of secondviewcontroller.
The below uiviewcontroller will create a table with 3 sections. Each cell has a textfield(except the middle, it is a button which pulls up a uipickerview). This is not a full class i only took the areas where the table is created.
-(void)viewDidLoad{
[super viewDidLoad];
// scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 500)];
// scrollview.pagingEnabled = YES;
//
// //[scrollview addSubview:self.view];
// [self.view addSubview:scrollview];
table.scrollEnabled = YES;
dataArray = [[NSMutableArray alloc] init];
titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 290, 30)];
//dropper
titleField = [[UITextField alloc] initWithFrame:CGRectMake(10, 2, 300, 30)];
titleField.layer.cornerRadius = 8;
titleField.backgroundColor = [UIColor clearColor];
NSArray *firstItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2", nil];
NSDictionary *firstItemsArrayDict = [NSDictionary dictionaryWithObject:firstItemsArray forKey:#"data"];
[dataArray addObject:firstItemsArrayDict];
//Second section dat
NSArray *secondItemsArray = [[NSArray alloc] initWithObjects:#"1", nil];
NSDictionary *secondItemsArrayDict = [NSDictionary dictionaryWithObject:secondItemsArray forKey:#"data"];
[dataArray addObject:secondItemsArrayDict];
NSArray *thirdItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2",#"3", nil];
NSDictionary *thirdItemsArrayDict = [NSDictionary dictionaryWithObject:thirdItemsArray forKey:#"data"];
[dataArray addObject:thirdItemsArrayDict];
NSLog(#"the dataArray%#",dataArray);
if([self connectedToNetwork]){
dispatch_async(kBgQueue, ^{
//build the url of strings
FULLURL = [SERVERNAME stringByAppendingFormat:TitleLink];
//create the url
NSURL *url = [[NSURL alloc] initWithString:FULLURL];
//NSLog(#"here title url%#",url);
//get the data from the url
NSData* data = [NSData dataWithContentsOfURL: url];
//NSLog(#"here%#",data);
//get the data from the url
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
// NSLog(#"titleid:%#",TITLEID);
// NSLog(#"title categories:%#",titlecategories);
});
[table setBounces:NO];
}else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Please Check your internet connection"
message:#"Enable your internet connection"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
});
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return [dataArray count];
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
//Number of rows it should expect should be based on the section
NSDictionary *dictionary = [dataArray objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"data"];
return [array count];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 1){
cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:#"longdropper300.png"]];
}
else{
cell.backgroundColor = [UIColor whiteColor];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 10, 290, 30)];
static NSString *cellValue = #"Cell";
UITableViewCell *cell =nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellValue];
}
cell.selectionStyle = UITableViewCellSelectionStyleGray;
if ([indexPath section] == 0) {
//cellValue=[items objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle= UITableViewCellSelectionStyleNone;
//textField.tag = 1;
textField.adjustsFontSizeToFitWidth = YES;
textField.textColor = [UIColor blackColor];
if(indexPath.section == 0){
//textfield for email
if ([indexPath row] == 0) {
textField.tag = 1;
textField.text = EMAIL;
textField.textColor= [UIColor blackColor];
textField.placeholder = #"Email: example#gmail.com";
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
//textfield for phone number
else {
textField.tag = 2;
if ([PHONENUMBER isEqual: [NSNull null]] && PHONENUMBER == nil && PHONENUMBER == NULL && [PHONENUMBER isEqual: #""]){
NSLog(#"phone is empty%#",PHONENUMBER);
//[PHONENUMBER isEqual:#"frank"];
}else{
NSLog(#"phone is not empty%#",PHONENUMBER);
textField.text = PHONENUMBER;
}
textField.placeholder = #"Phone: xxx-xxx-xxxx";
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.secureTextEntry = NO;
}
textField.backgroundColor = [UIColor whiteColor];
textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
}
if(indexPath.section == 1){
[titleField setTextColor:[UIColor whiteColor]];
titleField.tag = 3;
titleField.placeholder = #"Select Contact Title";
titleField.returnKeyType = UIReturnKeyNext;
//titleField == textField.tag = 3;
if ([TITLENAME isEqual: [NSNull null]]){
NSLog(#"titlename is empty%#",TITLENAME);
}else{
NSLog(#"titlename is not empty%#",TITLENAME);
titleField.text = TITLENAME;
}
titleField.keyboardType = UIKeyboardTypeDefault;
titleField.returnKeyType = UIReturnKeyDone;
titleField.secureTextEntry = NO;
titleField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
titleField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
titleField.textAlignment = UITextAlignmentCenter;
titleField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[titleField setEnabled: NO];
titleField.delegate = self;
[cell addSubview:titleField];
NSLog(#"here is the titlename%#",TITLENAME);
}
if(indexPath.section == 2){
if ([indexPath row] == 0) {
textField.tag = 4;
textField.placeholder = #"First Name";
cell.selectionStyle= UITableViewCellSelectionStyleNone;
if ([FIRSTNAME isEqual: [NSNull null]]){
NSLog(#"firstname is empty%#",FIRSTNAME);
textField.text = #"";
}else{
textField.text = FIRSTNAME;
}
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
if([indexPath row] == 1){
textField.tag = 5;
textField.placeholder = #"Last Name";
if ([LASTNAME isEqual: [NSNull null]]){
NSLog(#"lastname is empty%#",LASTNAME);
textField.text = #"";
}else{
textField.text = LASTNAME;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyNext;
//textField.secureTextEntry = NO;
}
if([indexPath row] == 2){
textField.tag = 6;
textField.placeholder = #"Company";
if ([COMPANY isEqual: [NSNull null]]){
NSLog(#"company is empty%#",COMPANY);
textField.text = #"";
}
else{
textField.text = COMPANY;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.secureTextEntry = NO;
}
//]textField.backgroundColor = [UIColor whiteColor];
textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
return cell;
}
//Change the Height of title cell drop down
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
if (indexPath.section == 1) {
if (indexPath.row == 0) {
return 30;
}
}
return 45;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if(([textField tag] == 1)){
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:textField.text] == YES)
{
EMAIL = [textField.text copy];
NSLog(#"here is the email%#",EMAIL);
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Bad Email"
message: #"Please Re-enter the email address with a valid email"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
textField.text = nil;
NSLog(#"email not in proper format");
}
}
if(([textField tag] == 2)){
NSString *phoneRegex = #"[235689][0-9]{6}([0-9]{3})?";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
//valid email address
if ([phoneTest evaluateWithObject:textField.text] == YES)
{
PHONENUMBER = [textField.text copy];
NSLog(#"here is the phone number %#",PHONENUMBER);
}
else
{
NSLog(#"Phone Number Invalid");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"xxx-xxx-xxxx"
message: #"Please enter a valid phone number"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
textField.text = nil;
}
}
if(([textField tag] == 4)){
FIRSTNAME = [textField.text copy];
NSLog(#"here is the firstName%#",FIRSTNAME);
}
if(([textField tag] == 5)){
LASTNAME = [textField.text copy];
NSLog(#"here is the Last Name%#",LASTNAME);
}
if(([textField tag] == 6)){
COMPANY = [textField.text copy];
NSLog(#"here is the Company%#",COMPANY);
}
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
Main View Controller
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)addMyButton{ // Method for creating button, with background image and other properties
loginButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
loginButton.frame = CGRectMake(10.0,130.0, 300.0, 40.0);
[loginButton setTitle:#"Login" forState:UIControlStateNormal];
loginButton.backgroundColor = [UIColor clearColor];
[loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
UIImage *buttonImageNormal = [UIImage imageNamed:#"blueButton.png"];
UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[loginButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
UIImage *buttonImagePressed = [UIImage imageNamed:#"whiteButton.png"];
UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[loginButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
[self.view addSubview:loginButton];
[loginButton addTarget: self
action: #selector(loginButtonClicked:)
forControlEvents: UIControlEventTouchUpInside];
}
//Change the View and send the information to the servlet once login is clicked.
- (void)loginButtonClicked: (id)sender{
loginButton.enabled = NO;
activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(20, 60, 20, 20)];
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
[self navigationItem].rightBarButtonItem = barButton;
[activityIndicator startAnimating];
[passwordTF resignFirstResponder];
//start new thread
//dispatch_async(kBgQueue, ^{
NSLog(#"Username:%#",USERNAME);
NSLog(#"Password:%#",PASSWORD);
NSLog(#"COMPANYID: %#", COMPANYID);
//NSLog(#"LOGINID: %#", LOGINID);
if((USERNAME == NULL) || (USERNAME == nil) || ([USERNAME isEqualToString:#""])){
//NSLog(#"null password or usernaem");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Username or password not found"
message:#"please try again"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[activityIndicator stopAnimating];
// MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
// [self.navigationController pushViewController:SenderInfoViews animated:NO];
}else if((PASSWORD == NULL) || (PASSWORD == nil) || ([PASSWORD isEqualToString:#""])){
//NSLog(#"null password or usernaem");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Username or password not found"
message:#"please try again"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[activityIndicator stopAnimating];
// MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
// [self.navigationController pushViewController:SenderInfoViews animated:NO];
}else{
//NSLog(#"all good");
NSLog(#"Login button clicked, load the next view and check for password");
NSLog(#"full the url%#",FULLURL);
//build the url of strings
FULLURL = ******
if([self connectedToNetwork])
{
dispatch_queue_t downloadQueue = dispatch_queue_create("data loader", NULL);
dispatch_async(downloadQueue, ^{
//create the url
NSURL *url = [[NSURL alloc] initWithString:FULLURL];
NSLog(#"here%#",url);
//get the data from the url
NSData* data = [NSData dataWithContentsOfURL: url];
NSLog(#"here%#",data);
NSLog(#"here that data%#",data);
if(data != nil){
//
//get the data from the url
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
//
NSLog(#"hello Username:%#",USERNAME);
NSLog(#"Password:%#",PASSWORD);
NSLog(#"h4llo COMPANYID: %#", COMPANYID);
NSLog(#"LOGINID: %#", LOGINID);
//
// // [self performSelectorOnMainThread:#selector(checkLogin:) withObject:LOGINID waitUntilDone:YES];
//
//
#try {
//NSLog(#"before loginddd %#",LOGINID);
if(COMPANYID != 0){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:USERNAME forKey:#"UserName"];
[prefs setObject:#"Pass" forKey:#"Pass"];
// This is suggested to synch prefs, but is not needed
[prefs synchronize];
NSLog(#"here is the login identiy%#",LOGINID);
MangoContactSelection *SenderInfoViews = [[MangoContactSelection alloc] init];
[self.navigationController pushViewController:SenderInfoViews animated:NO];
}
else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"bad NAME"
message:#"GOO"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
// [self.view setNeedsDisplay];
[self.view reloadInputViews];
MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
[self.navigationController pushViewController:SenderInfoViews animated:NO];
[activityIndicator stopAnimating];
});
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Login Failed"
message:#"Bad"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
//[activityIndicator stopAnimating];
}
// if the data is nil do this
}else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"No Internet!"
message:#"Please Check your internet Connection"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[self.view setNeedsDisplay];
MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
[self.navigationController pushViewController:SenderInfoViews animated:NO];
});
}
dispatch_async(dispatch_get_main_queue(), ^ {
//UIImage *image = [UIImage imageWithData:imageData];
//[table reloadData];
//[actIndicator stopAnimating];
[self.view reloadInputViews];
[activityIndicator stopAnimating];
// sender because that's the element that called us by clicking refresh
});
});
}else{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"No Internet!"
message:#"Please Check your internet Connection"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[self.view setNeedsDisplay];
MangoLoginViewController *SenderInfoViews = [[MangoLoginViewController alloc] init];
[self.navigationController pushViewController:SenderInfoViews animated:NO];
}
}
[self.view reloadInputViews];
}//login
-(void)gobacktoContactCreate{
MangoContactSelection *gobackhome = [[MangoContactSelection alloc]init];
[self.navigationController pushViewController:gobackhome animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//self.view setBackgroundColor:([UIColor blackColor]);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *userName = [prefs stringForKey:#"UserName"];
//NSString *pass = [prefs stringForKey:#"Pass"];
//navigation bar
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
[self.navigationController setNavigationBarHidden: NO animated:NO];
self.navigationItem.hidesBackButton = YES;
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:nil action:#selector(gobacktoContactCreate)];
self.navigationItem.title=#"Login";
//User name text field................
usernameTF = [[UITextField alloc] initWithFrame:CGRectMake(10, 25, 300, 40)];
usernameTF.borderStyle = UITextBorderStyleRoundedRect;
usernameTF.font = [UIFont systemFontOfSize:15];
usernameTF.placeholder = #"Username";
usernameTF.text = userName;
usernameTF.autocorrectionType = UITextAutocorrectionTypeNo;
usernameTF.keyboardType = UIKeyboardTypeDefault;
usernameTF.returnKeyType = UIReturnKeyNext;
usernameTF.clearButtonMode = UITextFieldViewModeWhileEditing;
usernameTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//User name text field................
passwordTF = [[UITextField alloc] initWithFrame:CGRectMake(10, 75, 300, 40)];
passwordTF.borderStyle = UITextBorderStyleRoundedRect;
passwordTF.font = [UIFont systemFontOfSize:15];
passwordTF.placeholder = #"Password";
passwordTF.autocorrectionType = UITextAutocorrectionTypeNo;
passwordTF.keyboardType = UIKeyboardTypeDefault;
passwordTF.returnKeyType = UIReturnKeyDone;
passwordTF.clearButtonMode = UITextFieldViewModeWhileEditing;
passwordTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
passwordTF.secureTextEntry = YES;
//create the clickable labels
//register link
registerLabel = [[UILabel alloc]initWithFrame:CGRectMake(150,170, 150, 20)];
registerLabel.text = #"Request an account";
registerLabel.font = [UIFont systemFontOfSize:12];
registerLabel.userInteractionEnabled = YES;
registerLabel.textColor = [UIColor blueColor];
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(requestRegistration:)];
[registerLabel addGestureRecognizer:gr];
gr.numberOfTapsRequired = 1;
gr.cancelsTouchesInView = NO;
//create the label for
registerText = [[UILabel alloc]initWithFrame:CGRectMake(60,170, 90, 20)];
registerText.text = #"New to *******?";
registerText.font = [UIFont systemFontOfSize:12];
// //forgot password link
// forgotPassword = [[UILabel alloc]initWithFrame:CGRectMake(210,190, 150, 20)];
// forgotPassword.font = [UIFont systemFontOfSize:12];
// forgotPassword.textColor = [UIColor blueColor];
// forgotPassword.text = #"Forgot Password?";
// forgotPassword.userInteractionEnabled = YES;
// UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(requestForgottenPassword:)];
// [registerLabel addGestureRecognizer:tapRec];
// tapRec.numberOfTapsRequired = 1;
// tapRec.cancelsTouchesInView = NO;
[self.view addSubview:passwordTF];
[self.view addSubview:usernameTF];
[self.view addSubview:registerLabel];
[self.view addSubview:registerText];
// [self.view addSubview:forgotPassword];
[self addMyButton];
usernameTF.delegate = self;
passwordTF.delegate = self;
}
-(void)requestRegistration:(UITapGestureRecognizer *)gr{
//for registration
NSLog(#"request registration link clicked");
}
-(void)requestNewPassword:(UITapGestureRecognizer *)tapRec{
//for registration
NSLog(#"request password link clicked");
}
//Grabs the Json from the servlet and then parses it for the username and password.
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
//NSLog(#"here is the login info from json: %#", json);
// NSString *FALSELOGIN;
COMPANYID = [json valueForKey:#"companyid"];
NSLog(#"COMPANY ID: %#", COMPANYID);
// LOGINID = [json valueForKey:#"login"];
// NSLog(#"LOGIN ID: %#", LOGINID);
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if((textField = usernameTF)){
USERNAME = [textField.text copy];
//NSLog(#"here is the string for username;%#", USERNAME);
}
if((textField = passwordTF)){
PASSWORD = [textField.text copy];
//NSLog(#"here is the password guy %#",PASSWORD);
}
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == usernameTF) {
[passwordTF becomeFirstResponder];
}
else{
[passwordTF resignFirstResponder];
}
return YES;
}
//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
// [passwordTF resignFirstResponder];
//
//}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
You have added Tableview inside view of UIViewController. right?
In which view you have added UITextview.? View of UIViewController ??
You can add UITextView in UIView and by applying animation just change frame of UITextView.
Ex.
// Take View UP....
[UIView animationWithDuration:secs delay:0.0 option:option animation:^{
CGRect frame = textview.frame;
frame.origin.y = 10; // Change Y position of frame.
textview.frame = frame;
}
completion:nil];
// Take View down
[UIView animationWithDuration:secs delay:0.0 option:option animation:^{
CGRect frame = textview.frame;
frame.origin.y = 100; // Change Y position of frame.
textview.frame = frame;
}
completion:nil];
No need to take UIScrollView.
Dhaval, I beleive your solution would work, but I ended up finding exactly what i was looking for here:
http://www.youtube.com/watch?feature=player_detailpage&v=qSvDWnasJ9I
Thanks.
On iOS 6 when a player is not signed in and is trying to use GameCenter an UIAlertView with the text that i put in title pops up. "game center unavailable player is not signed in". My question is is it possible to replace that UIAlertView with anything else, with my own interface element?
[GKLocalPlayer localPlayer].authenticateHandler = ^(UIViewController *viewController, NSError *error)
{
if ([[GKLocalPlayer localPlayer] isAuthenticated])
{
NSLog(#"[gamecenter] player authenticated: %#\n", [GKLocalPlayer localPlayer]);
[self gamecenterLoadAchievements];
[GKMatchmaker sharedMatchmaker].inviteHandler = ^(GKInvite *acceptedInvite, NSArray *playersToInvite)
{
// Insert application-specific code here to clean up any games in progress.
if (acceptedInvite)
{
NSLog(#"Accepted invitation");
isInvited = YES;
[[GameLevel sharedGameLevel] setCurrentGameMode:GameModeGameCenter];
GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithInvite:acceptedInvite] autorelease];
mmvc.matchmakerDelegate = self;
AppDelegate * delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
[delegate.viewController presentModalViewController:mmvc animated:YES];
}
else if (playersToInvite)
{
NSLog(#"Players to invite");
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = 2;
request.maxPlayers = 2;
request.playersToInvite = playersToInvite;
GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithMatchRequest:request] autorelease];
mmvc.matchmakerDelegate = self;
[presentingViewController presentModalViewController:mmvc animated:YES];
}
};
}
else
if (viewController)
{
AppDelegate *delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
NavigationController *_viewController = delegate.viewController.navController;
[_viewController presentViewController: viewController animated: YES completion:nil];
}
else
{
NSLog(#"[gamecenter] %#\n", error);
gcLoginFailed = YES;
if ([[error domain] isEqualToString:GKErrorDomain])
{
if ([error code] == GKErrorNotSupported)
gcIsSupported = NO;
else
if ([error code] == GKErrorCancelled)
gcLoginCancelled = YES;
}
}
};
Just not use UIAlertView Use your own graphics with a UIButton
If you are using the disableGameCenter method in authenticating , just don't use it , instead of it use a integer ilk int isPlayerSignedIn . And just return it to 1 or 0 . So ;
if (isPlayerSignedIn==0) {
//display your graphics
}
else do nothing .
edit :
else
if (viewController)
{
AppDelegate *delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
NavigationController *_viewController = delegate.viewController.navController;
[_viewController presentViewController: viewController animated: YES completion:nil];
}
just if you don't use these lines of code you will see that you don't get that UIAlertView
Then you can implement a "game center is unavailable" staff , but additionally you have to implement a login screen too.
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:).