Change User-agent in UIWebView (IOS 5) - objective-c

What I have done so far:I use the code below to change User-Agent in UIWebView in the project.
NSDictionary *userAgentReplacement = [[NSDictionary alloc] initWithObjectsAndKeys:userAgent, #"UserAgent",nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:userAgentReplacement];
Problem:I have this code working, however when I call the function again, to change the UserAgent to something else, UIWebView's do not update. In order to successfully update the UserAgent I need to remove/release the UIWebView and alloc/show it again, but it causes the UIWebView to lose all history. Is there any way to update the UserAgent without having to create a new UIWebView in order to have it take effect?

As you're using NSUserDefaults I assume that you're setting them in
application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
The alternative that I've previously used is
NSMutableURLRequest*request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:yourURL]];
[request setValue:userAgent forHTTPHeaderField:#"User-Agent"];
[webView loadRequest:request];
You can also use the UIWebView Delegate to capture the last loaded state of the webview using a NSString variable
-(void)webViewDidFinishLoad:(UIWebView *)webView{
currentConfig=[webView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML];
}
And then reload the webView using
[webView loadHTMLString:currentConfig baseURL:yourURL];

Related

Opening URL in browser by clicking button

Hi friends,
I am getting data from server when user post a link on his timeline am displaying like this but my requirement is when i click Title then it will open browser. How can i do this?
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://www.stackoverflow.com"]];
Will open a URL by the Application defined for the scheme. http has Safari as default (I guess)
To open it in the App itself create a ViewController + xib,
add a UIWebView to your View
& Buttons to get back to the app.
Then you can create an instance of your new ViewController and present it with
[self presentViewController:WebVC animated:YES completion:^(void){
[[WebVC MyWebView] loadRequest: [NSMutableURLRequest requestWithURL:[NSURL URLWithString: #"http://stackoverflow.com"]];
}];
e.g.
To make it even easier you could add a function to your ViewController like this one
-(void) LoadUrlFromString: (NSString *)url{
[self.MyWebView loadRequest: [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]]];
}
and then just do as before but call
[WebVC LoadUrlFromString:#"http://stackoverflow.com"];
on completition
You can use TTTAttributedlabel
TTTAttributedlabel *title_lbl = [TTTAttributedlabel alloc]init] //Make it an instance of TTTAttributed label what you are using for displaying the Title.
NSRange range = [title_lbl.text rangeOfString:"YOUR_TILE_HERE (Latest bollywod and hollywood.....")"];
[title_lbl addLinkToURL:[NSURL URLWithString:#"YOUR_URL_HERE (www.bollywood.com)"] withRange:range];
title_lbl.delegate = self;
And for onlcick method
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url
{
NSlog("%#",label.text);
[UIApplication sharedApplication] openURL:url];
}

UIWebView webViewDidStartLoad not called

I post this message because i haven't found any answer.
I send a request to my UIWebView, webViewDidStartLoad is not called. I need to use the method reload, and then it will work. By the way the shouldStartLoadWithRequest is called then twice.
If i'm using a test url (like say Google), i will not get any problem. So that it not seems to be from my code.
But here, I'm calling a ugly site who use lot of angular JS (and i don't know how it has been made). Strange things is that it's working fine on Safari.
What i don't understand is that it just get "stuck" in shouldStartLoadWithRequest. But after no callback. Nothing happen, even (didFailLoadWithError:).
Any idea?
*** EDIT *****
Ok i found the problem, but that's still a strange related issue. I've found the solution trying to send you the code, and i couldn't believe that the code was actually working.
the fact is that i was calling http request while my web view was hidden, and i don't know why, the second call is never working. You cannot reproduce the "bug", since the website is sandboxed, and i've tested on Google, and that works.
You need to know that the site i have tested on use a lot of angular JS based on GUI state. If someone still can explain me how can a uiwebview can be stuck from server side (webViewDidStartLoad never called), i'll be happy. So the bug is 100% server related.
Here the code:
#interface ViewController ()<UIWebViewDelegate>
#property(nonatomic, retain)UIWebView* webview;
#end
#implementation ViewController
#synthesize webview = _webview;
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType{
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
// With that ugly site it will be never called if _webview.hidden is set to true.
}
#pragma mark - lifeCycle
- (void)viewDidLoad{
[self setUpWebView];
// first time, it will work.
[self performSelector: #selector(loadUrlString:) withObject: #"http://theUglySite.com" afterDelay: 1];
// now, if the uiwebview is hidden, no response.
[self performSelector: #selector(loadUrlString:) withObject: #"http://theUglySite.com" afterDelay: 3];
[super viewDidLoad];
}
#pragma mark - logic
- (void)setUpWebView{
self.webview = [[[UIWebView alloc] initWithFrame:(CGRect){0,0,320,480}] autorelease];
_webview.delegate = self;
// hidding the webView will break the delegate callBack. That will still work on normal
// urlRequest.
_webview.hidden = YES;
[self.view addSubview: _webview];
}
- (void)loadUrlString:(NSString*)urlString{
NSURL* url = [NSURL URLWithString: urlString];
NSURLRequest* request = [NSURLRequest requestWithURL: url];
[_webview loadRequest: request];
}
#end
apparently, the webview in ios checks specifically for "iframe" tags in the html's dom and in case it finds, it creates events based on that tag as well. therefore, a simple however a patchy solution would be adding the following code in the part of the dom that is changing (for example, in the actual template of each section):
<iframe></iframe>
did the trick for me.. i'm also using angularjs version 1.3.16

UIWebView Content is not resizable by user

I'm struck over this little issue and just can't figure a way out. My apologies and gratitude.
Description:
an UIView with fullscreen UIWebView targeted for iPhone programmatically loads a web page using viewDidLoad method. When running the app into the simulator UIWebView is displayed, the web page loaded, but no pinching is allowed. Thus, I can move around the page, but I can't resize with multigesture.
Details:
- (void)viewDidLoad {
NSString *urlAddress = #"http://www.someurl.it";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
webView.userInteractionEnabled=YES;
webView.autoresizingMask=YES;
webView.multipleTouchEnabled=YES;
}
Just insert this line of code along with the other properties you set for the webview:
webView.scalesPageToFit = YES;
Because the proper property to set to allow UIWebView's to interpret pinch-to-zoom events is calledscalesPageToFit. Setting an autoresizingMask is a hint to the auto-rotational layout mechanism in UIView of where a view should be positioned in the new coordinate space of the given device.

Generate a website screen capture in ios

As the question says, on a iOS device if a user inputs a URL in uitextfield I want to generate a thumbnail capture of this URL. How can this be achieved? Unfortunately I don't have a clue where to start from.
Of course one way I can do this is to send this URL to backend & get the image screenshot from there. I know how one can do this kinda stuff using python or php. But I want to avoid the extra round trip to my backend servers.
I want something like - (uiimage *)screenCapture:(nsurl *)url
As per your question i think you'll want to manipulate the generated screenshot afterwards. You'll add a UIWebView programmatically to load the needed URL then take a snapshot of the loaded web page then remove the UIWebView
Here are the steps
a UIImageView to your viewController and connect it to your viewController class
#property (weak, nonatomic) IBOutlet UIImageView *image_Thumbnail;
having the URL in a variable named "webPageUrlString" add the following lines
UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.frame];
webView.backgroundColor = [UIColor redColor];
NSURL *websiteUrl = [NSURL URLWithString:**webPageUrlString**];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:websiteUrl];
[webView loadRequest: urlRequest];
webView.delegate = self;
[self.view addSubview:webView];
right now you have requested to load the URL but can't render the snapshot unless the web page is fully loaded,so you'll need to wait for the web page loading notification.In order to that you must subscribe to the webView delegate in the header file like that
#interface ViewController : UIViewController<UIWebViewDelegate>
Now you'll implement the "webViewDidFinishLoad" and take the snapshot you want then hide and remove the webView.
-(void)webViewDidFinishLoad:(UIWebView *)webView{
viewImage = [[UIImageView alloc] initWithFrame:self.view.frame];
viewImage.backgroundColor = [UIColor greenColor];
UIGraphicsBeginImageContext(webView.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[webView setAlpha:0];
[webView removeFromSuperview];
[self.view addSubview:viewImage];
}
Now you have the screenshot you want in the property called "viewImage" and you can do what ever you want with it ;)

iPhone SDK: UIWebView

I'm working on an app that uses a UIWebView to display its help files. The webView lives in it's own view, DocViewController...when its called the
- (void)viewDidLoad {
method uses
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:docPage ofType:#"html"]isDirectory:NO]]];
to load the proper doc page. However, once the first page is loaded, the view becomes static and new pages aren't loaded when the docPage changes and the view is toggled. Is there a way to clear the webView so new pages load when requested?
Edit:
The first answer is confusing to me. As is the routine below works. It's just that it only works once. After the view is loaded the first time it does not change when this view is toggled on again and the requested html page is different. The view always displays the first html page requested and will not load new requests.
- (void)viewDidLoad {
docPage = [NSString stringWithFormat: #"%d", hexpage];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[NSBundle mainBundle] pathForResource:docPage ofType:#"html"]isDirectory:NO]]];
}
viewDidLoad is only called once, unless the view is released and needs to be reloaded. This occurs usually only when the view controller receives a low memory warning. Instead of viewDidLoad, try putting that code in viewWillAppear:, which gets called every time the view will show on the screen.
Try using
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
passing an NSURL object to the dir that contains your HTML as baseURL and loading the HTML string with something like
NSString *path = [[NSBundle mainBundle] pathForResource:#"myfile"
ofType:#"html"];
NSString *html = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
Edit:
Also, make sure that your hyperlinks are not trying to open in a new window with something like target="_blank", your webview will not open those