I'm an iOS newb (.NET professional), so this may be a simple issue but I couldn't find anything through the SO search or Google (and maybe not looking for the right terms).
I'm writing an app that displays information from a DD-WRT router through it's web interface. I have no problem displaying the initial page and navigating through any of the other pages, but if I make any change on a form (and it redirects to apply.cgi or applyuser.cgi), the UIWebView is blank - it's supposed to display the same page, with the form submission changes. The site works fine in Mobile Safari, which I find intriguing, but I guess UIWebView isn't totally the same.
I think the iOS code is pretty standard for display a webpage, but I'll list it below. I can't give you access to my router because, well, that's not a good idea :) Hopefully someone with a DD-WRT router can help (or know what my issue is anyway).
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *sURL = #"http://user:pass#XXX.XXX.X.X";
NSURL *url = [NSURL URLWithString:sURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
self.webView.delegate = self ;
}
And I'm doing a few things with Javascript in the webViewDidFinishLoad method, but I know that's not the culprit because it still happens when I comment it out.
Well I figured out the problem on my own. I think part of it was putting the username & password in the URL (which was just a temporary measure) because I found that method provided the same results in mobile Safari and desktop Chrome.
So I added MKNetworkKit to my project that provided a simple way to add authentication to my request, and found I had to make a specific request to POST the data, then reloaded the page the to see the changes.
In the (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType method, I check if ([request.HTTPMethod isEqualToString:#"POST"]) and do this:
NSString *sPostData = [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding];
NSArray *aPostData = [sPostData componentsSeparatedByString:#"&"];
NSMutableDictionary *dPostData = [[NSMutableDictionary alloc] init];
//i don't know if this is the best way to set a dictionary, but it works
for (id apd in aPostData)
{
NSString *key = [apd componentsSeparatedByString:#"="][0];
NSString *val = [apd componentsSeparatedByString:#"="][1];
[dPostData setValue:val forKey:key];
}
MKNetworkEngine *engine = [[MKNetworkEngine alloc] init];
MKNetworkOperation *op = [engine operationWithURLString:[request.URL description] params:dPostData httpMethod:#"POST"];
[op setUsername:#"myUserName" password:#"myPassword" basicAuth:YES];
self.postedRequest = TRUE; //a bool I set so, when it comes to webViewDidFinishLoad, I reload the current page
[op start]; //send POST operation
Related
my application is just a simple webview which loads a given url. My problem is that if I turn on my application after some time, the webview doesn't show its content any more. My question is how to know if a webview has rendered something, or is it showing white screen and i have to reload it.
I've searched SO with no luck, so I would appreciate any suggestions or directions to sites where I could find a solution to my problem.
Thanks in advance!
In case anyone needs this I'm loading content like this and everything works, except when i don't use it for some time and it sits in the background, after it enters foreground it is white. I guess iOS is handling memory this way, and clears the webview.
- (void)loadWebView
{
NSDate *date = [NSDate date];
long unixTimeStamp = (long)[date timeIntervalSince1970];
NSString *urlString = [NSString stringWithFormat:#"http://www.myurlExample.com/mobile/?timestamp=%lu&secret=%#",unixTimeStamp,[[NSUserDefaults standardUserDefaults] objectForKey:kUniqueUserSecretID]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
[request setHTTPShouldHandleCookies:YES];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies: cookies];
[request setAllHTTPHeaderFields:headers];
[self.webView loadRequest:request];
}
Sounds like the problem occurs when you foreground the app?
You can do something like this in your AppDelegate.m:
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Depending on the architecture of your app, grab the handler to your controller that contains the webView
[webViewController.webview reload];
}
One way might be to use -stringByEvaluatingJavaScriptFromString: to check on the web view's content. For example, you could do something like:
NSString *head =
[myWebView stringByEvaluatingJavaScriptFromString:
#"document.getElementsByTagName(\"head\")"];
I have a webview that when loaded, the user is logged in by a POST request. After they are logged in, I want them to be taken to a webpage. My POST request is a URL as follows:
- (void)viewDidLoad {
[super viewDidLoad];
[_scoreWebView setDelegate:self];
NSMutableURLRequest *detailRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"myrul"]];
[detailRequest setHTTPMethod:#"POST"];
NSString *sendInfo =[NSString stringWithFormat:#"action=login&EMAIL=email&PASSWORD=password", nil];
NSData *infoData = [sendInfo dataUsingEncoding:NSUTF8StringEncoding];
[detailRequest setHTTPBody:infoData];
[_scoreWebView loadRequest:detailRequest];
}
This log in process works fine. However, after I send the user to my webpage it is launching webviewdidfinishload infinitely. I know that it fires each time something is loaded. Is there an alternate solution to redirecting the user to my page after log in? Also, I have three different pages that the user could be redirected to based on their input, this is just one of them for simplicity. This is my finishload method:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//Check here if still webview is loding the content
if (webView.isLoading)
return;
else //finished
NSLog(#"finished loading");
NSLog(#"%# in calendar", _thisScriptUniqueID);
NSString *fullURL=[NSString stringWithFormat:#"myurl/%##score", _thisScriptUniqueID];
NSLog(#"%#", fullURL);
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_scoreWebView loadRequest:requestObj];
}
Is there a different method that could be used to take the user to the page, or would it be possible to include both in the viewDidLoad?
After a lot of research, I decided that the functionality would work a lot better on the server side. I made it so that the same URL logs the user in and brings them to the desired page at the same time.
I am a newbie iOS learner. Couldn't find answer to following question after searching for a while. Hence, here it is.
Building on a first app that displays recent pictures from a user's instagram feed, I am trying to display pictures from the follows of that users instead.
To call recent pictures from the Instagram feed, which worked well, I had created the following method "imageForPhoto"
+ (void)imageForPhoto:(NSDictionary *)photo size:(NSString *)size completion:(void(^)(UIImage *image))completion {
if (photo == nil || size == nil || completion == nil) {
return;
}
NSString *key = [[NSString alloc] initWithFormat:#"%#-%#", photo[#"id"], size];
NSURL *url = [[NSURL alloc] initWithString:photo[#"images"][size][#"url"]];
[self downloadURL:url key:key completion:completion];
}
Therefore, I first modified my code to get the data related to the "follows" in my PhotosViewController instead of recent media pictures ( v1/users/3/follows ):
NSURLSession *session = [NSURLSession sharedSession];
NSString *urlString = [[NSString alloc] initWithFormat:#"https://api.instagram.com/v1/users/3/follows?count=99&access_token=%#", self.accessToken];
Then, I created a new method that I called friendAvatarForPhoto to get the follows profile pictures from a photo NSDictionary that is passed in as the only method parameter. I placed this method in my PhotoController class:
+ (void)friendAvatarForPhoto:(NSDictionary *)photo completion:(void(^)(UIImage *image))completion {
if (photo == nil || completion == nil) {
return;
}
NSString *key = [[NSString alloc] initWithFormat:#"avatar-%#", photo[#"user"][#"id"]];
NSURL *url = [[NSURL alloc] initWithString:photo[#"profile_picture"]];
[self downloadURL:url key:key completion:completion];
}
It seems to work. I have manually checked that the pictures that are rendered on my UICollectionView are actually coming from the "profile_picture" key of the responseDictionary I get back from Instagram.
Here is the structure of this dictionary: https://www.dropbox.com/s/ldjqupadqg0j3nq/friends_response_dictionary.png
Specifically, as you can see, I modified both the key and the url:
NSString *key = [[NSString alloc] initWithFormat:#"avatar-%#", photo[#"user"][#"id"]];
NSURL *url = [[NSURL alloc] initWithString:photo[#"profile_picture"]];
but I am not really understanding what I need to initial the *key string with... I kept "avatar" for example but why should I? I am pretty sure it's wrong although the result seems to be fine from what is returned on my UICollectionView.
What should I initiate this string with instead?
What is the function of this key in the overall NSURLSession process?
I'd love to better understand the overall process and better connect the dots with Instagram's API so I can query the right key and be sure I am getting what I am looking for. In a reliable way, not an intuitive one as I have just done app-arently.
Any help from experienced developers in the community would be welcome, I've just started to explore iOS dev a few weeks ago based on rusty C skills from a long time back.
Thank you!
:) Arsene
I am writing an App where I pass a Link as a NSString from a TableView to my DetailView. The String gets passed correctly, as I can see it in the log. The problem is, that the WebView just stays blank; unless I hard code any URL in. Even the ones that I can see in the log by just copy pasting them. What am I missing? Any help is greatly appreciated. Here's a sample log output and my code. I also checked this thread, where the guy hab the exact same problem as me, but none of the solutions posted there where helpful. UIWebView not loading URL when URL is passed from UITableView
2013-06-17 13:19:52.147 Feuerwehr[1661:c07] http://oliverengelhardt.de/ffw_app/Einsaetze/GB0505/index.html
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = url;
NSURL *myURL = [NSURL URLWithString:urlString];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:myURL];
[webView loadRequest:requestObj];
NSLog(urlString);
}
I think you stringUrl is nil when it loads (so it doesn't get passed. Break point view did load and see the value of the urlstring
Based on what you've said, your url isn't formatted correctly
i think you are missing delegate
self.webView.delegate = self;
I'm working on a payment system that runs in a UIWebView. The user completes a form on one site, and is taken to a payment gateway to process their card information. Once the payment has been processed, the user is taken back to a confirmation page on the first site.
The sites work as expected when tested in a normal browser, or even Mobile Safari. The sites are black boxes, and I can't change anything inside them. Apparently, the sites use relative URLs, and my issue occurs because my UIWebView is trying to load a page on the second domain with the base URL from the first domain.
For example,
User posts form from http://theform.com/page
User is taken to http://theform.com/OrderCC.aspx?orderRef=e59d7f53a693472cad8a76dd8fb64
In the second step, the user should have been taken to http://thepaymentgateway.com/OrderCC.aspx...
I'm trying to intercept requests to the wrong base URL, and reroute them to a correct one like this:
-(BOOL)webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest*)inRequest navigationType:(UIWebViewNavigationType)inType {
NSString *wrongURL = #"http://theform.com/OrderCC.aspx";
NSString *request = [[inRequest URL] absoluteString];
NSString *data = [[NSString alloc] initWithData:[inRequest HTTPBody] encoding:NSASCIIStringEncoding];
if ([request length] >= 33 && [[request substringWithRange:NSMakeRange(0, 33)] isEqualToString:wrongURL]) {
[webView loadData:[inRequest HTTPBody] MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://thepaymentgateway.com/OrderCC.aspx%#", [request substringFromIndex:33]]]];
return NO;
}
return YES;
}
After this runs, it seems my UIWebView is just displaying a blank page containing the POST data string. Where am I going wrong?