How to eliminate delay in presentation of MFMessageComposeViewController? - iphone

if([MFMessageComposeViewController canSendText])
{
MFMessageComposeViewController *sms_message_vc = [[MFMessageComposeViewController alloc] init];
sms_message_vc.body = text;
sms_message_vc.recipients = recipients;
sms_message_vc.messageComposeDelegate = self;
[self presentModalViewController:sms_message_vc animated:FALSE];
[[UIApplication sharedApplication] setStatusBarHidden:TRUE];
[sms_message_vc release];
}
When this executes there's a delay of several seconds before the compose view is actually shown. What is causing this and how does one go about eliminating the delay?
EDIT 1: Clarification: Making sms_message_vc and ivar doesn't help because the ...alloc] init] process will hang the UI for seconds, regardless of where it is.
EDIT 2: Tried GCD (with different priorities) to attempt to run initialization concurrently. Did not help:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, (unsigned long)NULL), ^(void){
sms_message_vc = [[MFMessageComposeViewController alloc] init];
sms_message_vc.messageComposeDelegate = self;
});

Consider making MFMessageComposeViewController *sms_message_vc a class instance variable and calling:
MFMessageComposeViewController *sms_message_vc = [[MFMessageComposeViewController alloc] init];
earlier, along with setting the delegate to self right after initing sms_message_vc
Then just do:
sms_message_vc.body = text;
sms_message_vc.recipients = recipients;
[self presentModalViewController:sms_message_vc animated:FALSE];
[[UIApplication sharedApplication] setStatusBarHidden:TRUE];
[sms_message_vc release];
When you want to actually send the message. This shouldn't change it too much but might help some.

I have the same problem.
I tried to cache the controller in a static variable. But it did not work. behaved erratically. First time works, second time delegate called automatically without any user action and 3rd time screen goes black. Looks like you have to create the instance after each dismiss!
import Foundation
import UIKit
import MessageUI
class UIUtil {
static var messageController:MFMessageComposeViewController? = nil
static var checkedOnce = false
class func createMessageController () -> MFMessageComposeViewController? {
if checkedOnce {
return messageController
}
checkedOnce = true
if (MFMessageComposeViewController.canSendText()) {
messageController = MFMessageComposeViewController()
messageController?.recipients = [SettingsManager.shared.switchPhoneNumber]
} else {
print("SMS services are not available in this device.")
}
return messageController
}
}
usage,
func createSMSView (text:String) {
print("Sending SMS to \(SettingsManager.shared.switchPhoneNumber). Text: \(text)")
if let ctr = UIUtil.createMessageController() {
ctr.body = text
ctr.messageComposeDelegate = self
self.present(ctr, animated: true, completion: nil)
} else {
print("Could not send SMS. Text: \(text)")
}
}

Related

Game Center Achievements and Cocos2d

I have a singleton class that handles all my game center stuff. I have set it to be a delegate of GKAchievementViewControllerDelegate.
I call the following method showAchievements
- (void) showAchievements
{
GKAchievementViewController *achievements = [[GKAchievementViewController alloc] init];
if (achievements != nil)
{
achievements.achievementDelegate = self.delegate;
[self.viewController presentModalViewController: achievements animated: YES];
}
}
and I implement the following
- (void)achievementViewControllerDidFinish:(GKAchievementViewController *)achievements
{
[self.viewController dismissModalViewControllerAnimated: YES];
}
I set self.viewController with the following code before calling showAchievements
AppController* appDelegate = (AppController*)[[UIApplication sharedApplication] delegate];
[GameCenterManager instance].viewController = appDelegate.window.rootViewController;
The app crashes and the following shows up in the console log when I call showAchievements.
Jul 16 12:36:28 imac-3 myApp[17103] <Info>: 12:36:28.287698 com.apple.AVConference: GKSConnSettings: set server: {
"gk-cdx" = "17.173.254.218:4398";
"gk-commnat-cohort" = "17.173.254.220:16386";
"gk-commnat-main0" = "17.173.254.219:16384";
"gk-commnat-main1" = "17.173.254.219:16385";
}
At the point where I call showAchievements the user has been logged in successfully.
Any idea what I might be doing wrong here?
My suspicions were correct, I was trying to access the viewController in the wrong way. I should have been using the CCDirectorIOS object instead of the UIWindow object.
GKAchievementViewController is deprecated. Try using GKGameCenterViewController.

Inmobi orientation iphone,

I have a huge problem, I've integrated inmobi in my app, which doesnt support interface orientation, but when i press on ad, view is loaded on top and it rotates, this wouldn't be bad, but the when it rotates, the view becomes distorted, not covering full screen,
maybe someone has had similar problem?
My code:
- (void)showInMobiBanner
{
if (_inMobView == nil)
{
_inMobView = [[IMAdView alloc] init];
_inMobView.delegate = self; //optional
_inMobView.imAppId = kInMobiAppId;
_inMobView.imAdUnit = IM_UNIT_320x50;
_inMobView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
}
if (self.containerView != nil)
{
_inMobView.rootViewController = self.containerView;
}
else
{
_inMobView.rootViewController = self.navigationController;
}
IMAdRequest *request = [IMAdRequest request];
request.isLocationEnquiryAllowed = NO;
_inMobView.frame = CGRectMake(0, 0, 320, 50);
_inMobView.imAdRequest = request;
[_inMobView loadIMAdRequest:request];
[self.view addSubview:_inMobView];
}
Thanks in advance!
It seems you're using an older version of InMobi SDK(3.0.2).
There has been a newer version launched very recently: http://developer.inmobi.com/wiki/index.php?title=IOS_SDK_350
A new method has been introduced:
- (BOOL)shouldRotateToInterfaceOrientation:(UIInterfaceOrientation)orientation;
You can make use of this method in your UIViewController, and tackle orientation changes something like this:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return [imAdView shouldRotateToInterfaceOrientation:interfaceOrientation];
}
Hope this helps!

App crashes while using setContentViewController in iOS 5

I am making my app compatible to iOS 5 but the app crashes on the code where i have used setContentViewController.
Here is my code.
[[ChoicesViewController sharedChoices] setCurrentValue:[[(UIButton *)sender titleLabel] text]];
[self.choicesPopoverController setContentViewController:[ChoicesViewController sharedChoices]];
CGFloat popoverHeight = 44.0f * [[[ChoicesViewController sharedChoices] choices] count];
[self.choicesPopoverController setPopoverContentSize:CGSizeMake(380.0f, MIN(400.0f, popoverHeight))];
if ([self.choicesPopoverController isPopoverVisible]) {
[self.choicesPopoverController dismissPopoverAnimated:YES];
} else {
[self.choicesPopoverController presentPopoverFromRect:[(UIButton *)sender frame]
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
}
here is what shared choices returns:
static ChoicesViewController *_sharedChoices = nil;
+(id)sharedChoices
{
if (!_sharedChoices)
{
_sharedChoices = [[[self class] alloc] init];
}
return _sharedChoices;
}
//When i comment the below code , the app wont crash in iOS 5 but the UIPopover is not shown too. And if I uncomment it it will crash in iOS 5.
-(UIPopoverController *)choicesPopoverController
{
if (!choicesPopoverController)
{
choicesPopoverController = [[UIPopoverController alloc] initWithContentViewController:self];
}
return choicesPopoverController;
}
You say you set breakpoints and found this line was the problem :
[self.choicesPopoverController setContentViewController:[ChoicesViewController sharedChoices]];
but there's a few things going on there. Where does it crash if you change that line to
id controller = self.choicesPopoverController;
id shared = [ChoicesViewController sharedChoices];
[controller setContentViewController:shared];
?
Finally i found the solution :
instead of writing
[self.choicesPopoverController setContentViewController:[ChoicesViewController sharedChoices]];
i did
choicesPopoverController = [[UIPopoverController alloc] initWithContentViewController:[ChoicesViewController sharedChoices]];
and commented out the this code
/*
-(UIPopoverController *)choicesPopoverController
{
if (!choicesPopoverController)
{
choicesPopoverController = [[UIPopoverController alloc] initWithContentViewController:self];
}
return choicesPopoverController;
}
*/
Now it doesnt crash in iOS 5.

TTPostController - Keyboard is not appearing

Hi
I am adding a "post comment section in my iPhone APP"
rest all things are working fine but when I tap on "postController textView" a keyboard is suppose to appear from the bottom but it is not appearing However the cursor is displaying and the text that I am passing using postController.textView.text = #"" is also displaying.
Please suggest the areas to be looked for fixing this bug.
-(void)showCommentView
{
TTPostController *postController = [[TTPostController alloc] init];
// self must implement the TTPostControllerDelegate protocol
postController.delegate = self;
self.popupViewController = postController;
// assuming self to be the current UIViewController
postController.superController = self;
postController.textView.text=#"temporary text";
[postController showInView:self.view animated:YES];
[postController release];
}
above is the code that is giving call to the Three20 PostController
below is the calling method which is unchanged...
-(IBAction)postComment:(id)sender
{
[UserManager instance]authenticateUserAndProceed:self withSelector:#selector(showCommentView)];
}
-(void)showCommentView
{
TTPostController *postController = [[TTPostController alloc] init];
// self must implement the TTPostControllerDelegate protocol
postController.delegate = self;
self.popupViewController = postController;
// assuming self to be the current UIViewController
postController.superController = self;
postController.textView.text=#"temporary text";
[postController showInView:self.view animated:YES];
[postController release];
}
changed method
-(void)authenticateUserAndProceed:(id)parent withSelector:(SEL)selector
{
theParentViewController = parent;
self.theFunctionToCall = selector;
if(userid == nil)
{
GetUserInfoViewController *guivc = [[GetUserInfoViewController alloc] init];
[parent presentModalViewController:guivc animated:YES];
guivc.delegate = self;
[guivc release];
}
else {
//////////////////// below line was replaced///////////
// 2. [theParentViewController performSelector:selector];
// with below code
UIAlertView *alert =[[UIAlertView alloc]initWith Title........
[alert show];
}
}
PROBLEM SUMMARY:
as soon as the user registered, he was not able to the kyboard for the TTPostController
CHANGE SUMMARY:
As soon as the user is registered the call to
[theParentViewController performSelector:selector];
is not sent directly but the call goes to ann alertview which inter calls it.
EFETCS SUMMARY:
the user will see a "you are registered successfully" (kind of) alertview.
tapping OK on which, he will be sent to TTPostController. (this time the keyboard is appearing)
I kept the line# 2 in the AlertViewDelegate method.
I was amazed o see it working just by not calling the line 2 directly.
this worked for me.
I welcome any new and better idea to implement the same

UIWebView - Enabling Action Sheets on <img> tags

Is it just me or has the action sheet on <img> tags been disabled in UIWebView? In Safari, e.g, when you want to save an image locally, you touch and hold on the image to get an action sheet shown. But it's not working in my custom UIWebView. I mean, it is still working for <a> tags, i.e, when I touch and hold on html links, an action sheet shows up. But not for the <img> tags.
I've tried things like putting img { -webkit-touch-callout: inherit; } in css, which didn't work. On the other hand, when I double-tap and hold on the images, a copy-balloon shows up.
So the question is, has the default action sheet callout for <img> tags been disabled for UIWebView? Is so, is there a way to re-enable it? I've googled around and saw many Q&As on how to disable it in UIWebView, so is it just me who aren't seeing the popup?
Thanks in advance!
Yes apple has disabled this feature (among others) in UIWebViews and kept it for Safari only.
However you can recreate this yourself by extending this tutorial, http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/.
Once you've finished this tutorial you'll want to add a few extra's so you can actually save images (which the tutorial doesn't cover).
I added an extra notification called #"tapAndHoldShortNotification" after 0.3 seconds which calls a method with just the disable callout code in it (to prevent both the default and your own menu popping while the page is still loading, a little bug fix).
Also to detect images you'll need to extend the JSTools.js, here's mine with the extra functions.
function MyAppGetHTMLElementsAtPoint(x,y) {
var tags = ",";
var e = document.elementFromPoint(x,y);
while (e) {
if (e.tagName) {
tags += e.tagName + ',';
}
e = e.parentNode;
}
return tags;
}
function MyAppGetLinkSRCAtPoint(x,y) {
var tags = "";
var e = document.elementFromPoint(x,y);
while (e) {
if (e.src) {
tags += e.src;
break;
}
e = e.parentNode;
}
return tags;
}
function MyAppGetLinkHREFAtPoint(x,y) {
var tags = "";
var e = document.elementFromPoint(x,y);
while (e) {
if (e.href) {
tags += e.href;
break;
}
e = e.parentNode;
}
return tags;
}
Now you can detect the user clicking on images and actually find out the images url they are clicking on, but we need to change the -(void)openContextualMenuAtPoint: method to provide extra options.
Again here's mine (I tried to copy Safari's behaviour for this):
- (void)openContextualMenuAt:(CGPoint)pt{
// Load the JavaScript code from the Resources and inject it into the web page
NSString *path = [[NSBundle mainBundle] pathForResource:#"JSTools" ofType:#"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:jsCode];
// get the Tags at the touch location
NSString *tags = [webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:#"MyAppGetHTMLElementsAtPoint(%i,%i);",(NSInteger)pt.x,(NSInteger)pt.y]];
NSString *tagsHREF = [webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:#"MyAppGetLinkHREFAtPoint(%i,%i);",(NSInteger)pt.x,(NSInteger)pt.y]];
NSString *tagsSRC = [webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:#"MyAppGetLinkSRCAtPoint(%i,%i);",(NSInteger)pt.x,(NSInteger)pt.y]];
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
selectedLinkURL = #"";
selectedImageURL = #"";
// If an image was touched, add image-related buttons.
if ([tags rangeOfString:#",IMG,"].location != NSNotFound) {
selectedImageURL = tagsSRC;
if (sheet.title == nil) {
sheet.title = tagsSRC;
}
[sheet addButtonWithTitle:#"Save Image"];
[sheet addButtonWithTitle:#"Copy Image"];
}
// If a link is pressed add image buttons.
if ([tags rangeOfString:#",A,"].location != NSNotFound){
selectedLinkURL = tagsHREF;
sheet.title = tagsHREF;
[sheet addButtonWithTitle:#"Open"];
[sheet addButtonWithTitle:#"Copy"];
}
if (sheet.numberOfButtons > 0) {
[sheet addButtonWithTitle:#"Cancel"];
sheet.cancelButtonIndex = (sheet.numberOfButtons-1);
[sheet showInView:webView];
}
[selectedLinkURL retain];
[selectedImageURL retain];
[sheet release];
}
(NOTES: selectedLinkURL and selectedImageURL are declared in the .h file to let them be accessed throughout the class, for saving or opening the link latter.
So far we've just been going back over the tutorials code making changes but now we will move into what the tutorial doesn't cover (it stops before actually mentioning how to handle saving the images or opening the links).
To handle the users choice we now need to add the actionSheet:clickedButtonAtIndex: method.
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:#"Open"]){
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:selectedLinkURL]]];
}
else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:#"Copy"]){
[[UIPasteboard generalPasteboard] setString:selectedLinkURL];
}
else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:#"Copy Image"]){
[[UIPasteboard generalPasteboard] setString:selectedImageURL];
}
else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:#"Save Image"]){
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(saveImageURL:) object:selectedImageURL];
[queue addOperation:operation];
[operation release];
}
}
This checks what the user wants to do and handles /most/ of them, only the "save image" operation needs another method to handle that. For the progress I used MBProgressHub.
Add an MBProgressHUB *progressHud; to the interface declaration in the .h and set it up in the init method (of whatever class you're handling the webview from).
progressHud = [[MBProgressHUD alloc] initWithView:self.view];
progressHud.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Tick.png"]] autorelease];
progressHud.opacity = 0.8;
[self.view addSubview:progressHud];
[progressHud hide:NO];
progressHud.userInteractionEnabled = NO;
And the -(void)saveImageURL:(NSString*)url; method will actually save it to the image library.
(A better way would be to do the download through an NSURLRequest and update the progress hud in MBProgressHUDModeDeterminate to deflect how long it'll actually take to download, but this is a more hacked together implementation then that)
-(void)saveImageURL:(NSString*)url{
[self performSelectorOnMainThread:#selector(showStartSaveAlert) withObject:nil waitUntilDone:YES];
UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]], nil, nil, nil);
[self performSelectorOnMainThread:#selector(showFinishedSaveAlert) withObject:nil waitUntilDone:YES];
}
-(void)showStartSaveAlert{
progressHud.mode = MBProgressHUDModeIndeterminate;
progressHud.labelText = #"Saving Image...";
[progressHud show:YES];
}
-(void)showFinishedSaveAlert{
// Set custom view mode
progressHud.mode = MBProgressHUDModeCustomView;
progressHud.labelText = #"Completed";
[progressHud performSelector:#selector(hide:) withObject:[NSNumber numberWithBool:YES] afterDelay:0.5];
}
And of cause add [progressHud release]; to the dealloc method.
Hopefully this shows you how to add some of the options to a webView that apple left out.
Of cause though you can add more things to this like a "Read Later" option for instapaper or a "Open In Safari" button.
(looking at the length of this post I'm seeing why the original tutorial left out the finial implementation details)
Edit: (updated with more info)
I was asked about the detail I glossed over at the top, the #"tapAndHoldShortNotification", so this is clarifying it.
This is my UIWindow subclass, it adds the second notification to cancel the default selection menu (this is because when I tried the tutorial it showed both menus).
- (void)tapAndHoldAction:(NSTimer*)timer {
contextualMenuTimer = nil;
UIView* clickedView = [self hitTest:CGPointMake(tapLocation.x, tapLocation.y) withEvent:nil];
while (clickedView != nil) {
if ([clickedView isKindOfClass:[UIWebView class]]) {
break;
}
clickedView = clickedView.superview;
}
if (clickedView) {
NSDictionary *coord = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:tapLocation.x],#"x",
[NSNumber numberWithFloat:tapLocation.y],#"y",nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"TapAndHoldNotification" object:coord];
}
}
- (void)tapAndHoldActionShort:(NSTimer*)timer {
UIView* clickedView = [self hitTest:CGPointMake(tapLocation.x, tapLocation.y) withEvent:nil];
while (clickedView != nil) {
if ([clickedView isKindOfClass:[UIWebView class]]) {
break;
}
clickedView = clickedView.superview;
}
if (clickedView) {
NSDictionary *coord = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:tapLocation.x],#"x",
[NSNumber numberWithFloat:tapLocation.y],#"y",nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"TapAndHoldShortNotification" object:coord];
}
}
- (void)sendEvent:(UIEvent *)event {
NSSet *touches = [event touchesForWindow:self];
[touches retain];
[super sendEvent:event]; // Call super to make sure the event is processed as usual
if ([touches count] == 1) { // We're only interested in one-finger events
UITouch *touch = [touches anyObject];
switch ([touch phase]) {
case UITouchPhaseBegan: // A finger touched the screen
tapLocation = [touch locationInView:self];
[contextualMenuTimer invalidate];
contextualMenuTimer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:#selector(tapAndHoldAction:) userInfo:nil repeats:NO];
NSTimer *myTimer;
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:#selector(tapAndHoldActionShort:) userInfo:nil repeats:NO];
break;
case UITouchPhaseEnded:
case UITouchPhaseMoved:
case UITouchPhaseCancelled:
[contextualMenuTimer invalidate];
contextualMenuTimer = nil;
break;
}
} else { // Multiple fingers are touching the screen
[contextualMenuTimer invalidate];
contextualMenuTimer = nil;
}
[touches release];
}
The notification is then handled like this:
// in -viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(stopSelection:) name:#"TapAndHoldShortNotification" object:nil];
- (void)stopSelection:(NSNotification*)notification{
[webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.style.webkitTouchCallout='none';"];
}
It's only a little change but it fixes the annoying little bug where you get 2 menus appear (the standard one and yours).
Also you could easily add iPad support by sending the touches location as the notification fires and then showing the UIActionSheet from that point, though this was written before the iPad so doesn't include support for that.
After struggling for, like 2 or 3 days non-stop on this problem, it seems like the position is computed "relatively" to the UIWebView's "TOP-LEFT" corner (I am programing for iOS 7).
So, to make this work, when you get the position, on the controller where your WebView is (i'll put a snippet of my code below), don't add the "scroll-offset"
SNIPPET - ContextualMenuAction:
- (void)contextualMenuAction:(NSNotification*)notification {
// Load javascript
[self loadJavascript];
// Initialize the coordinates
CGPoint pt;
pt.x = [[[notification object] objectForKey:#"x"] floatValue];
pt.y = [[[notification object] objectForKey:#"y"] floatValue];
// Convert point from window to view coordinate system
pt = [self.WebView convertPoint:pt fromView:nil];
// Get PAGE and UIWEBVIEW dimensions
CGSize pageDimensions = [self.WebView documentSize];
CGSize webviewDimensions = self.WebView.frame.size;
/***** If the page is in MOBILE version *****/
if (webviewDimensions.width == pageDimensions.width) {
}
/***** If the page is in DESKTOP version *****/
else {
// convert point from view to HTML coordinate system
CGSize viewSize = [self.WebView frame].size;
// Contiens la portion de la page visible depuis la webview (en fonction du zoom)
CGSize windowSize = [self.WebView windowSize];
CGFloat factor = windowSize.width / viewSize.width;
CGFloat factorHeight = windowSize.height / viewSize.height;
NSLog(#"factor: %f", factor);
pt.x = pt.x * factor; // ** logically, we would add the offset **
pt.y = pt.y * factorHeight; // ** logically, we would add the offset **
}
NSLog(#"x: %f and y: %f", pt.x, pt.y);
NSLog(#"WINDOW: width: %f height: %f", [self.WebView windowSize].width, [self.WebView windowSize].height);
NSLog(#"DOCUMENT: width: %f height: %f", pageDimensions.width, pageDimensions.height);
[self openContextualMenuAt:pt];
}
SNIPPET - in openContextualMenuAt:
To load the correct JS function:
- (void)openContextualMenuAt:(CGPoint)pt {
// Load javascript
[self loadJavascript];
// get the Tags at the touch location
NSString *tags = [self.WebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"getHTMLTagsAtPoint(%li,%li);",(long)pt.x,(long)pt.y]];
...
}
SNIPPET - in JSTools.js:
This is the function I use to get the element touched
function getHTMLTagsAtPoint(x,y) {
var tags = ",";
var element = document.elementFromPoint(x,y);
while (element) {
if (element.tagName) {
tags += element.tagName + ',';
}
element = element.parentNode;
}
return tags;
}
SNIPPET - loadJavascript
I use this one to inject my JS code in the webview
-(void)loadJavascript {
[self.WebView stringByEvaluatingJavaScriptFromString:
[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"JSTools" ofType:#"js"] encoding:NSUTF8StringEncoding error:nil]];
}
This part (everything I did to overrride the default UIActionSheet) is HEAVILY (should I say completely) based on
this post
#Freerunning's answer is complete (i did almost everything he said in my other classes, like on the post my code is based on), the snippets i posted is just to show you more "completely" how my code is.
Hope this helps! ^^
First of all thanks to Freerunnering for the great solution!
But you can do this with an UILongPressGestureRecognizer instead of a custom LongPressRecognizer. This makes things a bit easier to implement:
In the Viewcontroller Containing the webView:
Add UIGestureRecognizerDelegate to your ViewController
let mainJavascript = "function MyAppGetHTMLElementsAtPoint(x,y) { var tags = \",\"; var e = document.elementFromPoint(x,y); while (e) { if (e.tagName) { tags += e.tagName + ','; } e = e.parentNode; } return tags; } function MyAppGetLinkSRCAtPoint(x,y) { var tags = \"\"; var e = document.elementFromPoint(x,y); while (e) { if (e.src) { tags += e.src; break; } e = e.parentNode; } return tags; } function MyAppGetLinkHREFAtPoint(x,y) { var tags = \"\"; var e = document.elementFromPoint(x,y); while (e) { if (e.href) { tags += e.href; break; } e = e.parentNode; } return tags; }"
func viewDidLoad() {
...
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(CustomViewController.longPressRecognizerAction(_:)))
self.webView.scrollView.addGestureRecognizer(longPressRecognizer)
longPressRecognizer.delegate = self
...
}
func longPressRecognizerAction(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizerState.Began {
let tapPostion = sender.locationInView(self.webView)
let tags = self.webView.stringByEvaluatingJavaScriptFromString("MyAppGetHTMLElementsAtPoint(\(tapPostion.x),\(tapPostion.y));")
let href = self.webView.stringByEvaluatingJavaScriptFromString("MyAppGetLinkHREFAtPoint(\(tapPostion.x),\(tapPostion.y));")
let src = self.webView.stringByEvaluatingJavaScriptFromString("MyAppGetLinkSRCAtPoint(\(tapPostion.x),\(tapPostion.y));")
print("tags: \(tags)\nhref: \(href)\nsrc: \(src)")
// handle the results, for example with an UIDocumentInteractionController
}
}
// Without this function, the customLongPressRecognizer would be replaced by the original UIWebView LongPressRecognizer
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
And thats it!