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

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

Related

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 does not load full content from an url

I have a UIWebView where i load a url. But it does not load full content. I have checked all possible forums for solution but couldn't find a breakthrough yet. Any help would be really appreciated? You can try out the below url yourself. Basically, the url is supposed to contain html5 content/player.
-(void)loadPlayerUrl
{
activityIndicatorView.hidden = NO;
NSURL* nsUrl = [NSURL URLWithString:#"http://watch.nimbletv.com/tv"]
NSURLRequest* request = [NSURLRequest requestWithURL:nsUrl cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30];
[self.playerWebView loadRequest:request];
}
However, this works perfectly in safari or any other browser.
You should create ViewControllerWebPage
Then
- (void)viewDidLoad
{
[super viewDidLoad];
self.screenName = #"Info Ekran";
NSURL *mobileCreaURL = [NSURL URLWithString:#"http://mobilecrea.com/"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:mobileCreaURL];
[mobileCrea loadRequest:myRequest];
}
Also create new view, select your new custom class (ViewControllerWebPage) and than create UIWebView

UIWebView not displaying URL

Pretty easy enough problem, but It's driving me crazy. I connected my uiwebview to the .h and called it myWebView. then in the viewdidLoad, i did this:
NSString *urlString = #"www.google.com";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[myWebView loadRequest:request];
But when I run the app I just see a blank screen...
I don't know what's going on.
All help is appreciated, thanks
Your urlstring isn't well-formed (for your intent)
Use http://www.google.com/
Technically www.google.com is a valid URL (according to things like RFC 1738 and 3986), but since it lacks the scheme (the http part), the UIWebView doesn't quite know what to do with it.

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.

Using NSURLCredentialPersistenceForSession while request and then clearing the credentials on logout still persist the cerdentials

I am using NSURLCredentialPersistenceForSession within didReceiveAuthenticationChallenge of NSURLConnection delegate method while login.
Now when I logout and use this code for clearing the storage..
NSURLCredentialStorage *credentialStorage = [NSURLCredentialStorage sharedCredentialStorage];
NSDictionary *credentialsDicationary = [credentialStorage allCredentials];
NSLog(#"credentialsDicationary..%#",[credentialsDicationary description]);
for (NSURLProtectionSpace *space in [credentialsDicationary allKeys]) {
NSDictionary *spaceDictionary = [credentialsDicationary objectForKey:space];
NSLog(#"spaceDictionary..%#",[spaceDictionary description]);
for (id userName in [spaceDictionary allKeys]) {
NSURLCredential *credential = [spaceDictionary objectForKey:userName];
[credentialStorage removeCredential:credential forProtectionSpace:space];
}
}
But when I suddenly login again exactly after logout the login happens with wrong credentials. Please let mw know how to clear the cache. It works if I relogin after some 5 secs of time.
Thanks in advance..
AJ
If you're using NSURLSession, invalidate the session and create a new one, e.g.:
[self.session invalidateAndCancel];
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
This will clear session-scoped credentials.
If you use NSURLCredentialPersistenceForSession to create the credential then the app stores the credential for the entire session until the app is closed.
You can work around this by either:
changing the url (like appending '#' to the end of the url)
Use NSURLCredentialPersistenceNone and provide the credentials with each nsurlrequest
Append auth info to the url (http://username:password#mywebsite.com), instead of using creds
Append auth info to the request header, instead of using creds
//Pseudo code for appending to header:
NSString *authString = [NSString stringWithFormat:#"%#:%#", self.loginCreds.username, self.loginCreds.password];
NSData *stringData = [authString dataUsingEncoding:NSUTF8StringEncoding];
authString = [NSString stringWithFormat:#"Basic %#", [stringData base64EncodedString]];
[[self requestHeader] setValue:authString forHTTPHeaderField:#"Authorization"];
It's possible to remove the credential but it can take minutes before it is actually removed. However, I don't remember how its done.. It's either done the way you mentioned in the question or through the keychain.
I had the same issue and I tried clear the credential storage, cookies associated with url and even trying to reset the session but nothing seemed to work, finally I just resorted to adding a a random query string value to the end of the url and that did the trick for me
// Random number calculated.
NSInteger randomNumber = arc4random() % 16;
NSURL* apiURL = [NSURL URLWithString:#"https://localhost/api/"];
[[RKObjectManager sharedManager] getObjectsAtPath:[NSString stringWithFormat:#"%#getUser?randomNumber=%d",apiURL,randomNumber]
parameters:nil
success:successBlock
failure:failureBlock];
So instead of trying to remove current cached credentials (which seemed impossible) just use a "fresh" url so there aren't any cached objects associated with it.
I was facing the same problem, now it works.
Using NSURLConnection this issue can be fixed easily by adding a random number to the end of the URL:
So, search for your URLRequest and append the random number to URLRequest
NSInteger randomNumber = arc4random() % 999;
NSString *requestURL = [NSString stringWithFormat:#"%#?cache=%ld",yourURL,(long)randomNumber];
NSURL *URLRequest = [NSURL URLWithString:requestURL];
And make sure you have a random number at the end of all URLs you are calling.

Resources