I'm trying to launch a UIViewController when a table line is clicked...
The code is main view controller is ...
- (void)showDetail:(NSString *)detail
{
DetailViewController *secondViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:secondViewController animated:YES];
[DetailViewController release];
}
I filled in the viewDidLoad method in my "DetailViewController" class that is attached to the NIB.
- (void)viewDidLoad:(BOOL)animated;
{
NSURL *url = [NSURL URLWithString:#"www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
When I hit the pushViewController method, the NIB appears to load (can see a test label on it) but the viewDidLoad method is not called. In that method, I'm trying to load a test HTML into a UIWebView.
Any ideas?
There is no event viewDidLoad: change to the bellow it should work.
- (void)viewDidLoad{
NSURL *url = [NSURL URLWithString:#"www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
Related
I'm working on an iOS app for my school that will allow the user to access school documents like schedules, calendars, and grade/tuition sites. I've been doing research on how to save credentials for some of the sites that require logins, and my ultimate goal is not only save credentials, but automatically log in the user to the websites when the webview is loaded as well. So far my code looks like this:
#import "PJP Webview.h"
#implementation PJP_Webview
#synthesize webView, loginView, username, password, body, urlToLink,usernameField,passwordField, firstTime, loginNeeded, callerCell;
-(void) viewDidLoad {
[super viewDidLoad];
loginView.hidden = true;
if (firstTime && loginNeeded) {
loginView.hidden = false;
[self.view bringSubviewToFront:loginView];
}
else {
loginView.hidden = true;
[self.view addSubview:self.webView];
[self.view bringSubviewToFront:webView];
if (loginNeeded) {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *usernameSave = [NSString stringWithFormat:#"%#username", self.callerCell];
self.username = [userDefaults objectForKey:usernameSave];
NSString *passwordSave = [NSString stringWithFormat:#"%#password", self.callerCell];
self.password = [userDefaults objectForKey:passwordSave];
NSURL *url = [NSURL URLWithString: urlToLink];
NSString *bodyForUse = [NSString stringWithFormat: body, username, password];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: [bodyForUse dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest: request];
}
else {
NSURL *url = [NSURL URLWithString: urlToLink];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
}
}
- (IBAction)acceptInput:(id)sender {
self.username = usernameField.text;
self.password = passwordField.text;
loginView.hidden = true;
[self.view addSubview:self.webView];
[self.view bringSubviewToFront:webView];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *usernameSave = [NSString stringWithFormat:#"%#username", self.callerCell];
[userDefaults setObject:username forKey:usernameSave];
NSString *passwordSave = [NSString stringWithFormat:#"%#password", self.callerCell];
[userDefaults setObject:password forKey:passwordSave];
[userDefaults synchronize];
NSURL *url = [NSURL URLWithString: urlToLink];
NSString *bodyForUse = [NSString stringWithFormat: body, username, password];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: [bodyForUse dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest: request];
}
#end
I modeled some of my code after another stack overflow article found here Loading a webpage through UIWebView with POST parameters
An example of one of the websites I am trying to integrate is https://adphila.gradeconnect.com/front/slogin.php
So far my code has not been successful at logging me into the website and taking me to the next page, so I'm not sure if maybe the body I am using for the parameters is wrong, if my code is faulty, or some other issue is present. Also, if you have any suggestions for how to make my previous code more efficient I welcome that too!
Edit: The school also uses gmail for student emails, so is it possible to embed a uiwebview of email content as well? I know Google has their own APIs but I have never used non-Apple libraries before.
Edit 2:
#import "PJP Webview.h"
#implementation PJP_Webview
#synthesize webViewCurrent, loginView, username, password, bodyUsername, bodyPassword, urlToLink,usernameField,passwordField, firstTime, loginNeeded, callerCell, bodyButton;
-(void) viewDidLoad {
[super viewDidLoad];
[webViewCurrent setDelegate:self];
loginView.hidden = true;
if (firstTime && loginNeeded) {
loginView.hidden = false;
[self.view bringSubviewToFront:loginView];
}
else {
loginView.hidden = true;
if (loginNeeded) {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *usernameSave = [NSString stringWithFormat:#"%#username", self.callerCell];
self.username = [userDefaults objectForKey:usernameSave];
NSString *passwordSave = [NSString stringWithFormat:#"%#password", self.callerCell];
self.password = [userDefaults objectForKey:passwordSave];
NSURL *url = [NSURL URLWithString: urlToLink];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webViewCurrent loadRequest:request];
}
else {
NSURL *url = [NSURL URLWithString: urlToLink];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webViewCurrent loadRequest:request];
}
[self.view addSubview:self.webViewCurrent];
[self.view bringSubviewToFront:webViewCurrent];
}
}
- (IBAction)acceptInput:(id)sender {
self.username = usernameField.text;
self.password = passwordField.text;
loginView.hidden = true;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *usernameSave = [NSString stringWithFormat:#"%#username", self.callerCell];
[userDefaults setObject:username forKey:usernameSave];
NSString *passwordSave = [NSString stringWithFormat:#"%#password", self.callerCell];
[userDefaults setObject:password forKey:passwordSave];
[userDefaults synchronize];
NSURL *url = [NSURL URLWithString: urlToLink];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webViewCurrent loadRequest:request];
[self.view addSubview:self.webViewCurrent];
[self.view bringSubviewToFront:webViewCurrent];
}
-(void) webViewDidFinishLoad:(UIWebView *)webView {
NSString *fillData = [NSString stringWithFormat:#"document.getElementById('%#').value = '%#';document.getElementById('%#').value = '%#';", bodyUsername, username, bodyPassword, password];
[webView stringByEvaluatingJavaScriptFromString:fillData];
NSString *buttonData = [NSString stringWithFormat:#"document.getElementById('%#').click()", bodyButton];
[webView stringByEvaluatingJavaScriptFromString:buttonData];
}
#end
There is a new error though, void SendDelegateMessage(NSInvocation *): delegate (webView:didFinishLoadForFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode
For the website I am using, the bodyUsername is lusername, the bodyPassword lpassword, and the bodyButton login. The page loads but is not executing the javascript.
You can do this by Autopopulating the username and password field of that webpage. First get the name of the username and password field from the webpage. right click on the webpage.
Click on inspect element and then You van easily find it.
Then write the WebView Delegate Method.
// ViewController.m
// WebDemo
//
// Created by Nilesh on 7/31/16.
// Copyright © 2016 Nilesh. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()<UIWebViewDelegate>
#property (weak, nonatomic) IBOutlet UIWebView *webView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *urlToLink = #"https://adphila.gradeconnect.com/front/slogin.php";
NSURL *url = [NSURL URLWithString: urlToLink];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) webViewDidFinishLoad:(UIWebView *)webView {
NSString* userId = #"userName" ;//Your userName
NSString* password = #"password";// Your Password
NSString* jScriptString1 = [NSString stringWithFormat:#"document.forms[0]['lusername'].value='%#'", userId];
NSString* jScriptString2 = [NSString stringWithFormat:#"document.forms[0]['lpassword'].value='%#'", password];
[webView stringByEvaluatingJavaScriptFromString:jScriptString1];
[webView stringByEvaluatingJavaScriptFromString:jScriptString2];
NSString *jsStat = #"document.forms[0]['login'].click()";
[webView stringByEvaluatingJavaScriptFromString:jsStat];
}
#end
I am a beginner & I am trying to figure out how to upload text from a textfield to a server along with coordinates but I need to add the textfield to userdefaults.
The UITextfield is in my ViewController, while the coordinates & post to server are in a separate object class.
A tutorial or sample code will be very helpful.
Below, I have attached the relevant code I am using to upload the coordinates.
What I need is help on adding and uploading text from UITextfield in another class to the code below.
Singleton.m
#implementation Singleton {
CLLocation *location;
CLLocationManager *locationManager;
NSMutableData *responseData;
}
- (id)init {
if (self = [super init]) {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setDouble:location.coordinate.latitude forKey:#"latitude"];
[userDefaults setDouble:location.coordinate.longitude forKey:#"longitude"];
[userDefaults synchronize];
}
return self;
}
- (void) timerDidFire:(NSTimer *)timer
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (([userDefaults doubleForKey:#"latitude"] != location.coordinate.latitude) || ([userDefaults doubleForKey:#"longtitude"] != location.coordinate.longitude)) {
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:#"http://setslocation.php"]];
NSDictionary *requestData = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSString stringWithFormat:#"%f", location.coordinate.longitude], #"longitude",
[NSString stringWithFormat:#"%f", location.coordinate.latitude], #"latitude",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];
[userDefaults setDouble:location.coordinate.latitude forKey:#"latitude"];
[userDefaults setDouble:location.coordinate.longitude forKey:#"longtitude"];
[userDefaults synchronize];
}
}
first save your textfield value to NSUserDefaults and synchronize. You can get your value any where in your project from NSUserDefaults.
set value like:
[[NSUserDefaults standardUserDefaults] setObject:#"your textfield value" forKey:#"your key name"];
[[NSUserDefaults standardUserDefaults] synchronize];
get value:
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"your key name"]);
make sure you write same key name.
in part of my app (storyboard) I have a table view with various rows, and when I select a row, an html file should be displayed. Instead when I select a row, I get a blank screen instead.
I thought I needed another view controller after the tableview controller, but I get the same issue whether I have one or not.
In my table controller .m file I have the following code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
articleIndex = indexPath.row;
WebView *selectedArticle = [[WebView alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:selectedArticle animated:YES];
[selectedArticle release];
That is allowing me to select a row and the screen changes to a blank one, rather than loading the relevant html file.
I have in my resources folder a .h and .m file as follows:
webView.h
#import <UIKit/UIKit.h>
#import "globals.h"
#interface WebView : UIViewController{
NSArray *articleNames;
IBOutlet UIWebView *webView;
}
#property(nonatomic, retain)IBOutlet UIWebView *webView;
#end
webView.m
#import "WebView.h"
#implementation WebView
#synthesize webView;
- (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];
articleNames = [[NSArray arrayWithObjects:
#"chapter1",
#"chapter2",
#"chapter3",
#"chapter4",
#"chapter5",
#"chapter6",
nil] retain];
NSString *chapterName = [[NSString alloc] initWithString:[articleNames objectAtIndex:articleIndex]];
NSString *path = [[NSBundle mainBundle] pathForResource:chapterName ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:path];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
[chapterName release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
I can't see what I have done wrong here, any advice? I'm not sure how to get the html files to display or where I need to make changes to allow it. If I remove the HTML files from the project the app crashes so it's definitely loading them but for some reason not displaying...
Well first off where is "articleIndex" I see you set it in your tableViewController but it is not webView.h or webView.m. I would suggest first adding in a NSLog
NSURL *url = [NSURL fileURLWithPath:path];
NSLog(#"Article URL:%#", url);
This will let you see if the url is correct first. Second it looks like you connected your UIWebView with interface builder, so make sure that the webView is connect correctly. You can also test the webView buy using:
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: #"http://www.apple.com"]];
And see if apple.com loads. If it does then you know your issue is with your html files or the paths to them.
I would like to parse a webpage to get the content of a table on that page. However, the table is created by calling document.write() and several javascript functions. i.e. when I load the URL request of that page, the source that I get contains no html tags of that table. Is it possible to get the source of the final page (i.e. the source containing the html tags of the table I want)? And it's very curious that I can view the "final page source" in safari Browser's Developer Tools but not the source of the page.
this is the source of the page the source
You should use implement the NSConnectionDataDelegate protocol and use the NSConnection class. I believe that by the time -(void) connectionDidFinishLoading:(NSURLConnection *)connection is called, the page has finished loading completely.
-(void) requestPage
{
NSString *urlString = #"http://the.page.you.want.com";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:20.0f];
responseData = [[NSMutableData alloc] init];
connection = [[NSURLConnection connectionWithRequest:request delegate:self] retain];
delegate = target;
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if ([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
//If you need the response, you can use it here
}
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[responseData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == adCheckConnection)
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//You've got all the data now
//Do something with your response string
[responseString release];
}
[responseData release];
[connection release];
}
yes, just use view generated source in firefox with the web developer extension or firebug extension
I'm trying to display a local html file from a three20 table controller. The table shows up correctly, but when I select the item, all I get is a blank screen. If I use an external URL, the page shows correctly. I haven't tried using UIWebView, but I was wondering if there was an easy way using the Three20 framework.
Thanks.
EDIT: I forgot that has changed recently...
Assuming you have registered a TTWebController in your navigator that way :
TTNavigator* navigator = [TTNavigator navigator];
TTURLMap* map = navigator.URLMap;
[map from:#"*" toViewController:[TTWebController class]];
You can simply open a local html file that way :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
TTOpenURL([url description]);
Then all you have to to is to add TTTableLinkedItem or subclass (almost all of TT*Cell are) to your dataSource with a local file URL like that :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
TTTableTextItem *item = [TTTableTextItem itemWithText:#"foobar" URL:[url description]];
Much simpler that what I wrote before...
ENDOFEDIT
Forget whats under, unless you're interested in others solutions... (more complex... or not, see last one)
Basically here is how you load content in a UIWebView :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
The three20 TTWebController can take a request in a query :
- (id)initWithNavigatorURL:(NSURL*)URL query:(NSDictionary*)query {
if (self = [self initWithNibName:nil bundle:nil]) {
NSURLRequest* request = [query objectForKey:#"request"];
if (nil != request) {
[self openRequest:request];
} else {
[self openURL:URL];
}
}
return self;
}
So to open a local html file in a TTWebController you could do this :
NSString *creditsPath = [[NSBundle mainBundle] pathForResource:#"credits" ofType:#"html"];
NSURL *url = [NSURL fileURLWithPath:creditsPath];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[[TTNavigator navigator] openURLAction:
[[[TTURLAction actionWithURLPath:#"url://to/your/ttwebcontroller"]
applyQuery:[NSDictionary dictionaryWithObject:ulrRequest
forKey:#"request"]]
applyAnimated:YES]];
Now the last part, to trigger this from a TTTableViewController...
You have in your ViewController to implement :
- (void)didSelectObject:(id)object atIndexPath:(NSIndexPath*)indexPath {
// there you retrieve a *TTTableItem* corresponding to your row
// and call previous snippet from URL...
// TTTableItem class has userInfo property you could use:
TTTableItem *item = (TTTableItem *)object;
NSString *htmlFile = item.userInfo.
[self openLocalHtmlFile:htmlFile];
}
Hope that helps!
Nothing tested, at all, should not compile or whatsoever, but that is a solution.
That's a solution using basic three20 + iOS features. You could also write a TTCustomWebController inheriting from TTWebController that would take urls like #"myapp://openLocalHtml?file=credits" that's not that hard to do...
...That here is a draft :
#interface TTCustomWebController : TTWebController {}
#end
#implementation TTCustomWebController
- (id)initWithFile:(NSString *)name {
self = [super init];
if (self) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:name ofType:#"html"];
NSURL *URL = [NSURL fileURLWithPath:filePath];
[self openURL:URL];
}
return self;
}
#end
Then you could simply use TTTableLinkedItem in your datasource pointing to these #"myapp://openLocalHtml?file=credits"...
Good luck! :)