UIWebview white screen after application enters foreground - ios

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\")"];

Related

How to use different User-Agent in different iOS Webview request

I know I can use the below code to change the default agent:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"Your user agent", #"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
but I want to request a different User-Agent for different requests. Examples: request 'www.google.com', use agent=‘google Agent’, request 'www.github.com', use agent='github Agent'.
I have tried the below way to set the 'User_Agent' in each request, but it doesn't seem to work.
- (void)viewDidLoad {
NSString *urlAddress = #"http://www.amazon.com";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Requst Object
NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:url];
[requestObj setValue:#"Foobar/1.0" forHTTPHeaderField:#"User_Agent"];
// But the value is not "Foobar/1.0"
NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:#"navigator.userAgent"];
NSLog(#"agent - %#", secretAgent);
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}
One more question:
It seems a change to the default agent only work change in 'AppDelegate' or 'initialize'. Am I right? Because I try to change in 'viewDidLoad' but it doesn't seem to work.
I observed that if you load any url in webView with a user-agent set
to it. After some time you load the different url & different user
agent but used the same allocated WebView instane.The web view will
load the new url but can not set new user-agent. It just set old one
that you have set before loading first time.
You can not change untill you initiate new instanse of UIWebview(or
we can say that user agent can be set once per session). So I coame to result that user-agent can be set only once.
What I did for this problem is, I allocated new instance when I want set new user-agent.
You don't need to set it using JavaScript.
You have misspelled User-Agent. Use this minimal code taken from here
NSString* userAgent = #"My Cool User Agent";
NSURL* url = [NSURL URLWithString:#"http://whatsmyuseragent.com/"];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:userAgent forHTTPHeaderField:#"User-Agent"];

iOS xcode Alternative to UIWebview didFinishLoad

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.

UIWebView displays blank page on form submit

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

Loading a UIWebview when pressing a UIButton

I am developing a simple testing app for iPhone. I want to click a button to change the URL of webview, then load the new URL. Here is my code:
NSString *nurl = [NSString stringWithFormat: #"http://www.abc.com/abc.aspx?SN=%#&fdate=%#&tdate=%#", SNstr, fDate, tDate];
NSLog(#"################: %#", nurl);
NSURL *url = [NSURL URLWithString:nurl];
NSLog(#"################: %#", url);
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[Logs loadRequest:req];
It is working well inside viewDidLoad.
I move it into a button:
-(IBAction)CheckLog:(id)sender
{
// codes here
}
When I press the button, it gives nurl's value correct, but url's value is null. So nothing is changed on the UIWebView Logs.
Why could this be, when the code runs correctly in viewDidLoad?
your button action will be like this...
-(IBAction)CheckLog:(id)sender
{
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSString *nurl = [NSString stringWithFormat: #"http://www.abc.com/abc.aspx?SN=%#&fdate=%#&tdate=%#", SNstr, fDate, tDate];
NSURL *url = [NSURL URLWithString: [nurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ];
// NSURL *theURL = [NSURL URLWithString:#"https://www.google.co.in/"]; // Your new URL
[self.myWebView loadRequest:[NSURLRequest requestWithURL:url]];
}
The first thing to check is that the method is definitely being called. Are your NSLog statements being printed? If not, check that you have connected the button to the IBAction correctly in Interface Builder.
I can't see anything in your code that is immediately jumping out to me as incorrect, so your best bet is to set a breakpoint at the start of the method and step through it line-by-line, checking the values of each variable as you go.

Box.Net iOS SDK Moving Files and Folders

I am currently developing an iOS application and am implementing the Box.Net SDK. I have gotten everything to work except the ability to move files around, which is not a native feature of the SDK. I am trying to twist my way through it.
If you are familiar with the structure of Box.Net, each file/folder has an ID number for itself, and an ID its parent. From what I understand if I want to move a file, I am supposed to change the parent ID number on the file which will point it to the new location. I can't seem to get it to work properly though. My application seems to keep crashing.
This is what I have so far, generalized.
BoxObject *boxObject = [[[Box objectWithID:(ID#ofParent)] children] objectAtIndex:i];
[boxObject parent].boxID = 0; // <-- Problem (causes crash)
I also tried this.
[boxObject setParent:[Box folderWithID:[BoxID numberWithInt:i]]];
The boxObject variable is the file that I want to move. I am setting its parent ID equal to 0, which is supposed to be the root folder. However, my application crashes when I try to reassign the parent ID for the file. Any ideas on how to successfully move files/folders? Any help is much appreciated! Thanks in advance!
Okay. I suppose there wasn't a way to do fix this in-house with the SDK. So, I had to send out an external PUT request. I used the following code to handle moving files.
- (void)moveItem:(BoxObject *)object toParentFolderWithID:(BoxID *)parentID
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.box.com/2.0/files/%#", object.boxID]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"PUT"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *auth = [NSString stringWithFormat:#"BoxAuth api_key=%#&auth_token=%#",[Box boxAPIKey],[defaults objectForKey:#"box-api-auth-token"]];
NSString *payload = [NSString stringWithFormat:#"{\"parent\": {\"id\": %#}}", parentID];
[request setHTTPBody:[NSMutableData dataWithData:[payload dataUsingEncoding:NSUTF8StringEncoding]]];
[request setValue:auth forHTTPHeaderField:#"Authorization"];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
Just as a reminder if you are new to the Box SDK, you will most likely need to update/refresh the data after moving the files. If not handled, your application could crash if the file doesn't exist. Hope this helps to anyone was not sure about this.

Resources