UIWebView not opening requested url from other view controller Objective C - objective-c

mainViewController.h
#import "ECSlidingViewController.h"
-(void)Loadwebview:(NSURL *)url;
mainViewController.m
-(void)Loadwebview:(NSURL *)url
{
// NSURL *testURL = [NSURL URLWithString:#"http://www.google.com"];
NSLog(#"loadwebview: %#", url);
[webViewBox loadRequest:[NSURLRequest requestWithURL:url]];
}
leftViewController.h
#import "mainViewController.h"
#import "ECSlidingViewController.h"
leftViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *urlString = [[dao libraryItemAtIndex:indexPath.row] valueForKey:#"url"];
NSURL *url = [NSURL URLWithString:#"http://www.google.com"]; //urlString];
NSLog(#"selected url: %#", url);
mainViewController *mvc = [[mainViewController alloc]init];
[mvc Loadwebview:url];
//NSLog(#"%#", [[dao libraryItemAtIndex:indexPath.row] valueForKey:#"url"]);
[self.slidingViewController resetTopView]; //it will show mainViewController
}
This code is not working... OutPut steps are,
Log shows :
Selected url: http://www.google.com
loadwebview: http://www.google.com
which means I am passing url from leftViewController.m to mainViewController.m and calling loadwebview function properly. But the issue is that webViewBox is not opening requested url.
:-(

Related

Objective C - When tapping the tab bar item again, how to reload web view again?

I really need help please. Initially, by tapping on a tab bar item, I will load a webview on Gym VC user will then scroll down the web view
What I am trying to accomplish is when user tap on the same tab bar item again, the webView will reload again. I managed to call the method handleRefresh from MyTabBarController But the method doesn't do anything at all. Any guidance is much appreciated.
Currently I have the following code
MyTabBarController.m
#import "GymNavigationController.h"
#import "Gym.h"
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
if([viewController isKindOfClass:[GymNavigationController class]]){
Gym *myGym = [[Gym alloc] init];
[myGym handleRefresh:nil];
}
}
Gym.m
#import "Gym.h"
#import "AppDelegate.h"
#import "GymDet.h"
#import <QuartzCore/QuartzCore.h>
#interface Gym () {
AppDelegate *appDelegate;
NSString *sURL, *sRefresh;
}
#end
#implementation Gym
#synthesize webView;
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
sURL = appDelegate.gURL;
sURL = [sURL stringByAppendingString:#"/apps/gym.asp?"];
NSLog(#" The sURL to be load for the current page : %# ", sURL);
sRefresh = sURL;
[defaults setObject:sRefresh forKey:#"txtRefresh"];
[defaults synchronize];
NSURL *url = [NSURL URLWithString:sURL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView setDelegate:(id<UIWebViewDelegate>)self];
[webView loadRequest:urlRequest];
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];
[webView.scrollView addSubview:refreshControl];
}
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//[self handleRefresh:nil];
[[self navigationController] setNavigationBarHidden:YES animated:YES];
}
-(void)viewDidDisappear:(BOOL)animated{
[[self navigationController] setNavigationBarHidden:NO animated:YES];
}
- (void)handleRefresh:(UIRefreshControl *)refresh {
//--- Call the stored txtMemCode, something like session ---
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
sRefresh = [defaults objectForKey:#"txtRefresh"];
NSURL *url = [NSURL URLWithString:sRefresh];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
[refresh endRefreshing];
}
First i would like to suggest why you're initiating a new Gym object every time tabbar is tapped you should take a reference of the Gym object and initialise it if its nil then process ahead with the reference, but it maybe your requirement and if it is i would like to suggest you to create a BOOL variable lets say isUpdateRequire and when you're instantiating your viewcontroller assign isUpdateRequire = true. Then in the end of view did load or view will appear (according to your need) check
if isUpdateRequire {
[self handleRefresh:nil]
}
Alternatively you can create protocols in your webviewcontroller and assign its delegate to your tabbarcontroller and fire the delegate method when ever required.
and if you don't want the method to call when you come back to vc simply put this condition in viewWillAppear
if self.isMovingToParentViewController {
[self handleRefresh:nil]
}

Web View not working in iOS

I am new to Objective-C.
I have a table view populated with links that the user has added. When the user clicks on one of the cells in the table view, they are guided to a second view controller with a web view that displays the website of the link. However, when I run the app the web view appears blank. How do I fix this problem? There are no errors noted in the console either.
Table View .m
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showWebsite"]) {
UITableViewCell *cell = (UITableViewCell*)sender;
NSURL *url = [NSURL URLWithString:cell.textLabel.text];
NSString *string = url.absoluteString;
SecondViewController *vc = [segue destinationViewController];
vc.url = string;
}
}
Second View Controller .m
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *URL = [NSURL URLWithString:[self.url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[self.webView loadRequest:request];
}
Can you try placing the 3 lines from the
- (void)viewDidLoad
to the
-(void)viewDidAppear:(BOOL)animated
instead?

AVAudioPlayer iOS no sound

Seems to be similar questions asked but none of the solutions seem to work for me. Cant for the life of me understand why my code doesnt work so here it is.
I dont get any errors but also get no sound.
#interface MainApp ()
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
-(void)playSoundFX:(NSString*) soundFile;
#end
#implementation MainApp
- (void)viewDidLoad {
[super viewDidLoad];
// Play sound
[self playSoundFX:#“sound.mp3"];
}
// Play sound
- (void)playSoundFX:(NSString*)soundFile {
// Setting up path to file url
NSBundle* bundle = [NSBundle mainBundle];
NSString* bundleDirectory = (NSString*)[bundle bundlePath];
NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:soundFile]];
// Make an audioPlayer object and play file
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer setVolume:100.0f];
if (audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[audioPlayer play];
}
#end
*********vvvvvvvvv Amended Code that works vvvvvvvvv**********
#interface MainApp ()
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
-(void)playSoundFX:(NSString*) soundFile;
#end
#implementation MainApp
- (void)viewDidLoad {
[super viewDidLoad];
// Play sound
[self playSoundFX:#“sound.mp3"];
}
// Play sound
- (void)playSoundFX:(NSString*)soundFile {
// Setting up path to file url
NSBundle* bundle = [NSBundle mainBundle];
NSString* bundleDirectory = (NSString*)[bundle bundlePath];
NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:soundFile]];
// Make an audioPlayer object and play file
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[self.audioPlayer setVolume:100.0f];
if (self.audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[self.audioPlayer play];
}
#end
I am execute your code on my iPhone. It is work properly.Please Select a device and run your code. I hope it will execute properly with sound.
You got to segregate the functionalities..
Loading audio file in viewDidLoad and play it on play action, some thing like this
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
{
AVAudioPlayer *_audioPlayer;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Construct URL to sound file
NSString *path = [NSString stringWithFormat:#"%#/sound.mp3", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
// Create audio player object and initialize with URL to sound
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)playSoundTapped:(id)sender
{
// When button is tapped, play sound
[_audioPlayer play];
}

- (BOOL)webview: doesn't run in objective c xcode

I am trying to get this to run... I have put in NSLogs, but nothing appears in the debugger when I change page.
Here is my code:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize webview;
- (void)viewDidLoad
{
[super viewDidLoad];
self.webview.delegate = self;
NSString *path = [[NSBundle mainBundle] pathForResource:#"menu" ofType:#"html" inDirectory:#"pages"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webview loadRequest:request];
NSLog(#"%#",[[request URL] absoluteString]); //this log appears when the ipad simulator starts
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
This section below doesn't seem to run (no log appears in the debugger!)
- (BOOL)webview:(UIWebView*)aWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"%#",[[request URL] absoluteString]);
NSString *absoluteUrl = [[request URL] absoluteString];
if ([absoluteUrl isEqualToString:#"didtap://button1"]) {
NSLog(#"Button tapped");
return NO;
}
return YES;
}
Check the capitalization of your delegate method; it should be:
- (BOOL)webView:(UIWebView*)aWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
i.e. webView, not webview.

TableView doesn't push to WebView

I'm trying to make an RSS Feed for my website inside the app. I'm trying to make it so that when the user clicks a cell in my TableView it brings you to the link of the specific post parsed. The link is being parsed, but the console gives me this error:
Application tried to push a nil view controller on target .
Here is my code:
WebViewController.h
#import <Foundation/Foundation.h>
#interface WebViewController : UIViewController
#property (nonatomic, readonly) UIWebView *webView;
#end
WebViewController.m
#import "WebViewController.h"
#implementation WebViewController
-(void)loadView
{
CGRect screenFrame = [[UIScreen mainScreen] applicationFrame];
UIWebView *wv = [[UIWebView alloc] initWithFrame:screenFrame];
[wv setScalesPageToFit:YES];
[self setView:wv];
}
-(UIWebView *)webView
{
return (UIWebView *)[self view];
}
#end
MasterViewController.h My TableView
#import <UIKit/UIKit.h>
// A forward declaration; we'll import the header in the .m
#class RSSChannel;
#class WebViewController;
#interface MasterViewController : UITableViewController
<NSXMLParserDelegate>
{
NSURLConnection *connection;
NSMutableData *xmlData;
RSSChannel *channel;
}
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#property (strong, nonatomic) IBOutlet UINavigationItem *navigationBar;
#property (nonatomic, strong) WebViewController *webViewController;
- (void)fetchEntries;
#end
MasterViewController.m
#import "MasterViewController.h"
#import "WebViewController.h"
#import "RSSChannel.h"
#import "RSSItem.h"
#interface MasterViewController () {
NSMutableArray *_objects;
}
#end
#implementation MasterViewController
#synthesize tableView = _tableView;
#synthesize navigationBar;
#synthesize webViewController;
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self fetchEntries];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
#pragma mark - Table View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIImage *myImage = [UIImage imageNamed:#"SephardiJewsHeader.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
imageView.frame = CGRectMake(0,-1,320,93);
return imageView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 93;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"The amount of items in the table: %u", [[channel items] count]);
return [[channel items] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:#"UITableViewCell"];
}
RSSItem *item = [[channel items] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[item title]];
[[cell detailTextLabel] setText:[item date]];
return cell;
}
- (void)fetchEntries
{
// Create a new data container for the stuff that comes back from the service
xmlData = [[NSMutableData alloc] init];
// Construct a URL that will ask the service for what you want -
// Note we can concatenate literal strings together on multiple lines in this way it
// results in a single NSString instance
NSURL *url = [NSURL URLWithString:
#"http://sephardijews.com/feed/"];
// Putting the URL we made into an NSURLRequest, so we can connect to the url data that we specifed
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Creating a connecting that will exchange this request for the data from the URL we specifed
connection = [[NSURLConnection alloc] initWithRequest:req
delegate:self
startImmediately:YES];
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifedName
attributes:(NSDictionary *)attributeDict
{
NSLog(#"%# found a %# element", self, elementName);
if ([elementName isEqual:#"channel"]) {
// If the parser saw a channel, create new instance, store in our ivar
channel = [[RSSChannel alloc] init];
// Give the channel object a pointer back to ourselves for later
[channel setParentParserDelegate:self];
// Set the parser's delegate to the channel object
[parser setDelegate:channel];
}
}
// This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[xmlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
// Give it a delegate - don't worry about the warning
[parser setDelegate:self];
// Tell it to start parsing - the documet will be parsed and the delegate of NSXMLParser will get all of its delegate messages sent to it before this line finishes execution - it is blocking
[parser parse];
// Get rid of the XML data as we no longer need it
xmlData = nil;
// Get rid of the connection, no longer need it
connection = nil;
// Reload the table
[[self tableView] reloadData];
NSLog(#"%#\n %#\n %#\n", channel, [channel title], [channel infoString]);
}
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
// Release the connection object, we are done with it cause' there is no connection
// Setting the connection to nil will stop the connection because it is nothing/0
connection = nil;
// Release the xmlData object. We stopped to connection to put the data in the xmlData object, so we set it to nil also
xmlData = nil;
// Grab the description of the error object passed to us, so we can tell the user
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
// Create and show an alert view to the user with the error string to tell them the error in the process of the connection
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error"
message:errorString
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[av show];
}
/* - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
WebViewController *aWebViewController = [[WebViewController alloc] init];
self.webViewController = aWebViewController;
[self.navigationController pushViewController:self.webViewController animated:YES];
RSSItem *entry = [[channel items] objectAtIndex:[indexPath row]];
NSURL *url = [NSURL URLWithString:[entry link]];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[[webViewController webView] loadRequest:req];
[[webViewController navigationItem] setTitle:[entry title]];
} */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showPost"]) {
WebViewController *awebViewController = [segue destinationViewController];
self.webViewController = awebViewController;
NSIndexPath *selectedRow = [self.tableView indexPathForSelectedRow];
RSSItem *entry = [[channel items] objectAtIndex:[selectedRow row]];
NSURL *url = [NSURL URLWithString:[entry link]];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[[webViewController webView] loadRequest:req];
[[webViewController navigationItem] setTitle:[entry title]];
}
}
#end
Thanks for your help!
Your WebViewController isn't being initialized anywhere. Try this in your tableView:didSelectRowAtIndexPath::
WebViewController *aWebViewController = [WebViewController alloc] init];
self.webViewController = aWebViewController;
[self.navigationController pushViewController:self.webViewController animated:YES];
[aWebViewController release];
If you're using Storyboard, add a view controller and change its class to WebViewController. From the MasterViewController in the Storyboard, right-click on a cell and connect the push segue to the WebViewController. Click the push segue and change its identifier to something like "showPost" or whatever.
Go back to MasterViewController.m and delete your code from tableView:didSelectRowAtIndexPath: and add this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showPost"]) {
WebViewController *aWebViewController = [segue destinationViewController];
NSIndexPath *selectedRow = [self.tableView indexPathForSelectedRow];
RSSItem *entry = [[channel items] objectAtIndex:[selectedRow row]];
NSURL *url = [NSURL URLWithString:[entry link]];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[aWebViewController.webView loadRequest:req];
aWebViewController.title = entry.title
}
}