Xcode Open target=_blank links in Safari - xcode

I'm pretty new to Xcode... I have a single page iOS app that just has a UIWebView opening a specific URL. I would like any links within the pages that have target="_blank" to open in Safari, rather than inside the app.
Can someone tell me how to accomplish this? (I've searched everywhere) and also tell me in which files and where to put the code? Thank you SOOO much!!
EDIT
I implemented the following code in my ViewController.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Add line below so that external links & PDFs will open in Safari.app
webView.delegate = self;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.example.com/"]]];
}
// Add section below so that external links & PDFs will open in Safari.app
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:request.URL];
return false;
}
return true;
}
But for the line webView.delegate = self; I am getting a yellow warning that says:
Assigning to 'id'from incompatible type 'UIWebViewViewController *const_strong'
What is this error, and how can I fix it in Xcode?

Perhaps following answer on SO can solve your problem or atleast give you some ideas on how to achieve what you are trying to do:
UIWebView open links in Safari

This is the way we solved it:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
first.delegate = (id)self;
[first loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.website.com"]]];
}
// Add section below so that external links & PDFs will open in Safari.app
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeOther) {
NSString *checkURL = #"http://www.linkyouwanttogotoviasafari.com";
NSString *reqURL = request.URL.absoluteString;
if ([reqURL isEqualToString:checkURL])
{
[[UIApplication sharedApplication] openURL:request.URL];
return false;
}
else {
return true;
}
}
return true;
}

Related

How to share image through WhatsApp?

I'm using this code, but it's not working, how can it fit it?
Anyone help? Thanks!
UIImage *iconImage = [UIImage imageNamed:#"Home01-A01.png"];
NSString *savePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/whatsAppTmp.wai"];
[UIImageJPEGRepresentation(iconImage, 1.0) writeToFile:savePath atomically:YES];
_documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];
_documentInteractionController.UTI = #"net.whatsapp.image";
_documentInteractionController.delegate = self;
[_documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
Hi You can share your file on WhatsApp using UIDocumentationView Controller, do the following to achieve the same,
In your viewcontroller.h file,
add Delegate for
UIDocumentInteractionControllerDelegate
declare UIDocumentInteractionController object like this
UIDocumentInteractionController *controller;
In your viewcontroller.m file,
add following Delegate methos for UIDocumentationView controller to track the status for success and failure
pragma mark - Delegate Methods
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
return self;
}
- (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application {
NSLog(#"Starting to send this puppy to %#", application);
}
- (void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application {
NSLog(#"We're done sending the document.");
}
add following code to share your file,
-(void)openDocument {
// here's a URL from our bundle
NSURL *documentURL = [[NSBundle mainBundle]URLForResource:#"chat" withExtension:#"png”];// You can set your filename and extention here
// pass it to our document interaction controller
controller = [[UIDocumentInteractionController alloc]init];
controller.delegate = self;
controller.URL = documentURL;
// present the preview
[controller presentPreviewAnimated:YES];
}
Note: the URL that you specify needs to be local.
The goal of the UIDocumentInteractionController is to share (local) documents
between applications.if your file is not stored locally then you can
achive this by storing the file in temp or local caching directory then accessing it from the
main bundle.

After viewing web in app, cannot return to app without closing it and relaunching

I have an app which has several different buttons leading to various views. One of the views will open a website in Safari on iPhone which is what I want to happen. THe problem is that if I then want to go back to the app, all I get is a white screen, and I have to double click on home button, close the app and relaunch it.
Would this relate to releasing memory or view perhaps? I'm not sure how to go about fixing it so after viewing the web page in safari I can then go back to the app and continue with other views.
Here is what I am using in webViewController.m
#import "webViewController.h"
#interface webViewController ()
#end
#implementation webViewController
- (void)viewDidLoad
{
NSURL *url = [ [ NSURL alloc ] initWithString: #"http://www.mydomain.com" ];
[[UIApplication sharedApplication] openURL:url];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
you can use webView to load this url, then you can make a back button on this webview to come back to your app without leaving the app.
UIWebView * webView =[[UIWebView alloc]init];
webView.backgroundColor = [UIColor clearColor];
[webView setFrame: CGRectMake(0, 51, 320, 398)];
NSURL *url = [NSURL URLWithString:#"http://www.mydomain.com"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView setDelegate:self];
webView loadRequest:requestObj];
[self.view addSubview:webView];
You can also use some delegate methods of webView to know whether your page has been loaded or not
-(void)webViewDidStartLoad:(UIWebView *)webView
{
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
}
Ah I've figured it out, I've added
web view.scalesPagesToFit = Yes
statement and opening the webpage in the webview works exactly how I wanted it to.

Remove elasticity from webview

I have a webview which I would like to remove the elasticity from. As it is now, when scrolling a page that is smaller than the webview, it will make an elasticity effect revealing the background underneath. I would like to remove this.
I have tried doing the following but without success. It finds the WebDynamicScrollBarsView but setting the elasticity of this, does not change anything.
- (void)awakeFromNib
{
NSScrollView *scrollView = [self findScrollViewInSubviews:self.subviews];
scrollView.horizontalScrollElasticity = NSScrollElasticityNone;
scrollView.verticalScrollElasticity = NSScrollElasticityNone;
}
- (NSScrollView *)findScrollViewInSubviews:(NSArray *)subviews
{
for (NSView *view in subviews)
{
if ([view isKindOfClass:[NSScrollView class]])
return (NSScrollView *) view;
else
return [self findScrollViewInSubviews:view.subviews];
}
return nil;
}
Does anyone know how to remove the elasticity effect from a webview?
In my subclass of WebView (or you can just do it directly, with webView.mainFrame.frameView.documentView.enclosingScrollView, but this makes it easier for me, personally)
// return the scroll view that we are currently using, if applicatble
- (NSScrollView *)mainScrollView {
return [[[[self mainFrame] frameView] documentView] enclosingScrollView]; // can be nil
}
Then on finish load, as Anne noted literally as I was typing my answer :) ,
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
NSScrollView *mainScrollView = [sender mainScrollView];
[mainScrollView setVerticalScrollElasticity:NSScrollElasticityNone];
[mainScrollView setHorizontalScrollElasticity:NSScrollElasticityNone];
}
I'm not sure if doing it after the content has loaded is necessary, but I don't have my mac with me to try right now.

Expected ";" before "WebView" in Xcode

I am trying to follow the basic WebKit tutorial provided on Apple's Mac Dev site:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DisplayWebContent/DisplayWebContent.html
I am at the part where I update my title to the current page's title and update the URL to the current URL. However, when I try to Build this:
- (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame //2 errors on this line stating: expected ")" before "WebView" and expected ")" before "WebFrame"
{
//Only report feedback from main frame.
if (frame == [sender mainFrame]) {
NSString *url = [[[[frame provisionalDataSource] request] URL] absoluteString];
[textField setStringValue:url];
}
}
- (void)webView:(WebView *)sender didRecieveTitle:(NSString *)title forFrame:(WebFrame *)frame // Same 2 errors as the first line of code
{
if (frame == [sender mainFrame]){
[[sender window] setTitle:title];
}
}
Could somebody please tell me what is wrong with this? It is the exact code as Apple's example.
--Thank you
Did your right click on "frameworks" and click "Add existing Framework" and add Webkit.framework?
Did you include the include files?

Intercept web requests from a WebView Flash plugin

I've got a desktop browser app which uses a WebView to host a Flash plugin. The Flash plugin makes regular requests to an external website for new data, which it then draws as fancy graphics.
I'd like to intercept these web requests and get at the data (so I can display it via Growl, instead of keeping a desktop window around). But best I can tell, requests made by Flash don't get picked up by the normal WebView delegates.
Is there another place I can set a hook? I tried installing a custom NSURLCache via [NSURLCache setSharedURLCache] but that never got called. I also tried method swizzling a few of the other classes (like NSCachedURLResponse) but couldn't find a way in. Any ideas? Many thanks!
Surprised no one answered this, it is actually pretty easy. Create a subclass of NSURLProtocol, and then call registerClass to start intercepting.
[NSURLProtocol registerClass:[MyCustomURLProtocol class]];
Here are the important bits of the subclass:
#define REQUEST_HEADER_TAG #"x-mycustomurl-intercept"
+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest
{
// Check for the custom header on the request to break the
// infinite loop created by the [startLoading] below.
if ([theRequest valueForHTTPHeaderField:REQUEST_HEADER_TAG]) {
return NO;
}
if ([theRequest.URL.scheme caseInsensitiveCompare:#"http"] == NSOrderedSame) {
return YES;
}
return NO;
}
+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)theRequest
{
return theRequest;
}
- (id)initWithRequest:(NSURLRequest*)theRequest
cachedResponse:(NSCachedURLResponse*)cachedResponse
client:(id<NSURLProtocolClient>)client
{
// Add a custom header on the request to break the
// infinite loop created by the [startLoading] below.
NSMutableURLRequest* newRequest = [theRequest mutableCopy];
[newRequest setValue:#"" forHTTPHeaderField:REQUEST_HEADER_TAG];
// Now continue the process with this "tagged" request
self = [super initWithRequest:theRequest
cachedResponse:cachedResponse
client:client];
if (self) {
// capture the data received
[self setRequest:newRequest];
receivedData = [[NSMutableData data] retain];
}
[newRequest release];
return self;
}
- (void)dealloc
{
[connection release];
[request release];
[receivedData release];
[super dealloc];
}
- (void)startLoading
{
// Load the data off the web as usual, but set myself up as the delegate
// so I can intercept the response data as it comes in.
[self setConnection:[NSURLConnection connectionWithRequest:request delegate:self]];
}
- (void)stopLoading
{
[connection cancel];
}
#pragma mark NSURLConnection delegate implementation
- (void)connection:(NSURLConnection*)conn
didReceiveResponse:(NSURLResponse*)response
{
[[self client] URLProtocol:self
didReceiveResponse:response
cacheStoragePolicy:[request cachePolicy]];
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
[[self client] URLProtocol:self didLoadData:data];
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)conn
{
[[self client] URLProtocolDidFinishLoading:self];
[self setConnection:nil];
if (requestTag != 0) {
if (requestDelegate &&
[requestDelegate respondsToSelector:
#selector(finishedLoadingData:forURL:taggedWith:)]) {
[requestDelegate finishedLoadingData:receivedData
forURL:[request URL]
taggedWith:requestTag];
}
}
}
- (void)connection:(NSURLConnection*)conn didFailWithError:(NSError*)error
{
[[self client] URLProtocol:self didFailWithError:error];
[self setConnection:nil];
}

Resources