problems showing the actual URL of a page in my app - iphone

I'm making an iPad browser, and I have a little problem. When I go to google, for example, I write the google direction in a textField. The problem is that when I change the web page, it still says http://www.google.com/. Here's my code:
-(IBAction)buttonpressed2:(id)sender {
url = [NSURL URLWithString:[textField text]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[webView isEqual:textField.text];
}
How can I make the textField show the page that I'm watching right now, and not the first url typed in the field?

First, make sure when you set up the webView, you assign the UIWebViewDelegate to self
Then, implement the delegate method: webViewDidFinishLoad, as such:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSURLRequest *currentRequest = [webView request];
NSURL *currentURL = [currentRequest URL];
//This will log the current url
NSLog(#"Current URL is %#", currentURL.absoluteString);
//Then to display it in the textField
textfield.text = currentURL.absoluteString;
}
Edit:
A delegate is a special set of methods that wait for an event to happen. When that event happens, the appropiate method is called. The method above is one of the delegate methods for a UIWebView - When a specific event happens with the webView, in this case when the webViewDidFinishLoad, that method is automtically called and we can respond as such. In order to set the delegate, we can proceed one of two ways:
If you created the webView in code, this is with something like this:
UIWebView *webView = [[UIWebView alloc] init...]
then all you need to do is add the following line of code:
webView.delegate = self;
However, you might have also created the webView in the interface builder - If that's the case, click on the webView and the linker tab, and drag the delegate option over to "File's Owner".
and thats it.

Your class should implement the UIWebViewDelegate protocol. Then in the method webView:shouldStartLoadWithRequest:navigationType: you can do this:
[textField setText:[[request URL] absoluteString]];
This way the value in the textField will be updated whenever you navigate to a new url.

Related

Which way is faster to load page in uiwebview

Which way is faster to load webpages in uiwebivew
using
Loading NSData into a UIWebView
OR
using Load Request URL?
Network requests take time. There's no point in trying to optimize a few milliseconds off this type of code. Write the code that is most readable / maintainable and it will serve you better.
You could put the webpage, scripts, css, and images in your app bundle; get a URL that points to it (file://...) and use that. Within your webpage, you can use AJAX to pull in some dynamic data, etc.
That'd be a better path to optimize; but it all depends on your situation.
If you have the option of using loadRequest, I'd recommend it. Let the OS take the work off your hands.
edit:
PS: UIWebView tends to take it's time about displaying data; even when no network is involved.
I often set the webview's alpha to 0 in IB or viewDidLoad; then fade it in when the content is ready.
Inside your webViewDidFinishLoad: method, add this:
if (0.0f == webview.alpha) {
[UIView animateWithDuration:0.4f
animations:^{
webview.alpha = 1.0f;
}];
}
Their is really isn't any "technical" way to load Webview faster, But I would recommend you use:
Load Request URL
Load Request URL Code:
#interface WebViewController : UIViewController {
IBOutlet UIWebView *webView;
}
#property (nonatomic, retain) UIWebView *webView;
#end
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad {
NSString *urlAddress = #"http://www.google.com";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}

calling xcode method from javascript function to and get returned value

im developing an app, which requires to load some menu's and presentations(pdf, flash etc.)
menu items are loaded from database and each contains ID and Text. Menu items looks like below:
Crocin
Combiflame
above menu items are hyper links, clicking them will open up presentations on the same page.
i need to call a xcode method in this scenario which can query database (located in document folder in app) and return presentation name and some other details.
i got two problems here
1) i came across
**– webView:shouldStartLoadWithRequest:navigationType:**
but this method returns BOOL and i want to return Presentation with other information
2) no idea how can i load presentation (inside Resources Folder of my app ) via javascript on the same page.
Any suggestions will b greatly appreciated. Thanks in advance.
You can do pretty much what you need in webView:shouldStartLoadWithRequest:navigationType.
If you return NO from it, then the web view will not load the current request; this will make your app free of doing whatever it needs:
you can then either load a different request in the same web view (say an HTML string that embeds the presentation resource),
or, you can send a message to some controller of yours to run a different workflow altogether (display a different kind of view or whatever).
EDIT:
elaborating more option 2:
say that you have a view controller which embed the UIWebView and also acts as delegate for it;
you could define a method in the view controller which gets and HTML string and loads it into the web view, like this:
- (void)loadContentInWebView:(NSString*)content {
[_webView loadHTMLString:content baseURL:nil];
}
now, in webView:shouldStartLoadWithRequest:navigationType, you could do something like this:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] absoluteString] isEqual:WHATEVER]) {
[self loadContentInWebView:HERE_THE_HTML];
return NO;
}
return YES;
}
What you should define here is:
([[[request URL] absoluteString] isEqual:WHATEVER])
i.e., the logics to understand when the user touched some link that should make a presentation loaded;
and:
[self loadContentInWebView:HERE_THE_HTML];
i.e., define in some way the HTML content that you want to use so to have the presentation displayed.
i got a work around..although it is not a good practice:
in model:
This method gets called whenever a request comes for this webview even when the page loads in webview
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
// check the request, if it's ajax callback, just return NO; other wise YES;
// NSURLRequest *request = [self request];
NSURL *url = [request URL];
NSString *file = [url lastPathComponent];
if ([file isEqualToString:#"Presentation.html"] == YES) {
return YES;
}
if ([file isEqualToString:#"ajaxcallback.htm"] == YES) {
// that means the ajax call is done, so you can call this
NSString *result = [web stringByEvaluatingJavaScriptFromString:#"getResponse();"];
// don't forget to stop loading this fake page
return NO;
}
}
and in javascript:
function sendRequestToApp(){
window.location="http://www.domain.com/ajaxcallback.htm";
}
function getResponse(src){
alert("response");
document.getElementById("sample").src=src;
}

How do I get a Web-view to switch sites when pressing different side of UISegmentedControl (iOS Objective-C)

I think all of the tutorials I found are from before you could use a xib with uisegmented control. Basically, I am just trying to load websites, that will switch when tapping between UISegmentedControls.
FYI, this is the way I am loading the websites:
NSURL *USurl = [NSURL URLWithString:USurlAddress];
//URL Requst Object
NSURLRequest *USrequestObj = [NSURLRequest requestWithURL:USurl];
//Load the request in the UIWebView.
[webview loadRequest:USrequestObj];
If you're using a XIB, you have to bind the valueChanged event to a function on your file owner for example.
That function will be called when the segmented control value change, for example:
- (IBAction)segValueChanged:(UISegmentedControl *)seg {
switch (seg.selectedSegmentIndex) {
....
}
}
If you're doing this by code you can add an event listener to your segmented control with:
[segmentedControl addTarget:self
action:#selector(action:)
forControlEvents:UIControlEventValueChanged];
P.S.: Variable names, by convention, start with a lowercase character...
Create a method(let's call it -(void)switchBetweenTheViews:(id)sender) and then add the following line to the code where you create the UISegmentedControl:
[yourSegmentedControl addTarget:self action:#selector(switchBetweenTheViews:) forControlEvents:UIControlEventValueChanged];
Then whenever a user will tap on the other side of that UISegmentedControl this method will be called. Example of that method would be:
-(void)switchBetweenTheViews:(id)sender {
UISegmentedControl *sc = (UISegmentedControl*)sender;
NSURL *USurl;
if (sc.selectedSegmentIndex == 0) {
USurl = [NSURL URLWithString:USurlAddress];
} else {
USurl = [NSURL URLWithString:USurlAddress2];
}
NSURLRequest *USrequestObj = [NSURLRequest requestWithURL:USurl];
[webview loadRequest:USrequestObj];
}
Hope it helps

How to call a web service on page load

I am trying to call a web service on page load. Currently I call it on a button click and it works fine. But when I try to do the same on viewDidAppear, it doesn't happen. What i want to achieve is if username and password are saved then it should automatically load the next page. It is filling in the text boxes but not loading the next page.
Here is my code for submit button and ViewDidAppear:
-(IBAction)submitButton{
[apd showCoverView:YES WithActivityIndicator:YES];
PlaceWebService *handler = [[PlaceWebService alloc]init];
[handler setRequestType:Loginparser];
NSString *url = [NSString stringWithFormat:#"http://www.mywebsite.com/api.php?command=auth&cardno=%#&password=%#",username.text,password.text];
[handler sendingLoginRequest:url Respond:self At:#selector(showParsed:)];
}
and for viewDidAppear
-(void)viewDidAppear:(BOOL)animated
{
NSLog(#"Appeared");
[self loginArea];
apd=[[UIApplication sharedApplication]delegate];
NSString *filepath=[self pathOfFile];
if([[NSFileManager defaultManager]fileExistsAtPath:filepath])
{
NSArray *array=[[NSArray alloc]initWithContentsOfFile:filepath];
username.text=[array objectAtIndex:0];
password.text=[array objectAtIndex:1];
[self submitButton];
}
}
What should I do? Please help...
If you want to call the method after loading view and without any event, then you need to that as normal instance method instead of IBAction method.
-(Void)submitButton{
// implementation
}
and then call this method from viewDidAppear.
A couple things could be the problem here.
1)
IBActions usually take a parameter. Declare it as:
- (IBAction) submitButton: (id) sender;
And then call it from your viewDidAppear method as:
[self submitButton: self];
2)
Also make sure UI stuff is happening on the main thread (you didn't specify if the app is multi threaded or not), so maybe:
[self performSelectorOnMainThread: #selector(submitButton:) withObject: self];
And
3)
Set breakpoints to see if your submitButton method (and the lines before it) are actually even called when viewFromAppear: is called.
And Rishi's suggestion is good, too!

entity nbsp not defined

I have been trying to load the url http://friscotxcoc.weblinkconnect.com/cwt/External/WCPages2/wcevents/eventsstartpage.aspx?oe=true&ce=true into a webview but it shows up an error 'Entity nbsp not found'.
The link works properly over Safari (Machine as well as simulator) but doesnt load properly when loaded through a webview. Can someone point me as to how to do it?
#define kEventsCalenderLink #"http://friscotxcoc.weblinkconnect.com/cwt/External/WCPages2/wcevents/eventsstartpage.aspx?oe=true&ce=true"
NSURL *eventsURL = [NSURL URLWithString:kEventsCalenderLink];
eventsWebView.delegate = self;
[eventsWebView loadRequest:[NSURLRequest requestWithURL:eventsURL]];
The server is serving that page with the Content-Type of "application/xhtml+xml" to the Simulator version of Safari. Safari is interpreting the page as strict XML, which does not have an entity.
Unfortunately, UIWebView manipulates its HTTP headers behind the scenes, and it's seemingly impossible to configure it to make a request that will cause your server to serve content as "text/html"
The one workaround I would suggest is to retrieve the content with an NSURLConnection, then feed it to your web view with the loadData:MIMEType:textEncodingName:baseURL: method, being sure to pass "text/html" as the MIME type.
This may also necessitate intercepting future requests via the webView:shouldStartLoadWithRequest:navigationType: delegate method (in order to cancel them and load them in the manner described above to prevent similar problems).
Or, if you have control of the server, you could configure it to serve HTML with the appropriate content type. Or convert the content to use proper XML entities.
Do it in this way:
NSString *kEventsCalenderLink #"http://friscotxcoc.weblinkconnect.com/cwt/External/WCPages2/wcevents/eventsstartpage.aspx?oe=true&ce=true"
NSLog(#"%#",kEventsCalenderLink);
eventsWebView.delegate = self;
eventsWebView.userInteractionEnabled = true;
[eventsWebView loadRequest:[[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:kEventsCalenderLink]]];
You have only defined the URL which you haven't mentioned that it's string type.
Here is the sample code which i implemented.Hope it would help you
- (void)loadView
{
UIView *vew=[[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.view=vew;
//self.title=#"sanjay";
//self.navigationItem.title=#"afdsfasd";
self.view.backgroundColor=[UIColor redColor];
[vew release];
UIButton *smsbtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
smsbtn.frame=CGRectMake(50, 280, 100, 50);
[smsbtn setTitle:#"SMS APP" forState:UIControlStateNormal];
[smsbtn setTitleEdgeInsets:UIEdgeInsetsZero];
[smsbtn addTarget:self action:#selector(loadsms) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:smsbtn];
}
-(void)loadsms
{
NSString *url = [NSString stringWithFormat:#"http://friscotxcoc.weblinkconnect.com/cwt/External/WCPages2/wcevents/eventsstartpage.aspx?oe=true&ce=true"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: url]];
}
This code is working dude.Try this out.I have implemented this for you only.