簡體   English   中英

如何將數據從 javascript 傳遞到 IOS Objective-c 中的 Z5A98E2840FD0141780D854E48C608D?

[英]how to pass data from javascript to IOS Objective-c in webview?

I have a web app which i am using as Web-view app for android and IOS app.I need to pass user data to the web-view app which i achieved for android but i have no knowledge on how to do it for IOS web -看法。 I have my IOS code in x-code which is in objective-c and i need to send data from frontend javascript to Objective-c, which can access it. 下面是我的 javascript 代碼


var myAppName = 'myfakeappname';
var myActionType = 'myJavascriptActionType';
var myActionParameters = {}; // put extra info into a dict if you need it

// (separating the actionType from parameters makes it easier to parse in ObjC.)
var jsonString = (JSON.stringify(myActionParameters));
var escapedJsonParameters = escape(jsonString);
var url = myAppName + '://' + myActionType + "#" + escapedJsonParameters;
document.location.href = url;

下面是我來自 Viewcontroller.m 的代碼

#import "ViewController.h"
#import <WebKit/WebKit.h>


@interface ViewController ()<WKNavigationDelegate>
@property (weak, nonatomic) IBOutlet WKWebView *vwWeb;
@property (weak, nonatomic) IBOutlet UIView *vwLoading;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];


    self.vwWeb.navigationDelegate = self;
    NSURL *nsurl=[NSURL URLWithString:@"http://localhost:3000"];
    NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
    [self.vwWeb loadRequest:nsrequest];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{

    self.vwLoading.hidden = YES;
}




//below is the code i copy pasted from various resourses i found from forums

- (BOOL)webView:( WKWebView *)webView
        shouldStartLoadWithRequest:(NSURLRequest *)request
                    navigationType:(UIWebViewNavigationType)navigationType {

    // these need to match the values defined in your JavaScript
    NSString *myAppScheme = @"myfakeappname";
    NSString *myActionType = @"myJavascriptActionType";

    // ignore legit webview requests so they load normally
    if (![request.URL.scheme isEqualToString:myAppScheme]) {
        return YES;
    }

    // get the action from the path
    NSString *actionType = request.URL.host;
    // deserialize the request JSON
    NSString *jsonDictString = [request.URL.fragment stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
    NSLog(@"Hello, World!");
    // look at the actionType and do whatever you want here
    if ([actionType isEqualToString:myActionType]) {
        NSLog(@"Missing function name");
        // do something in response to your javascript action
        // if you used an action parameters dict, deserialize and inspect it here
    }


    // make sure to return NO so that your webview doesn't try to load your made-up URL
    return NO;
}


@end

任何幫助或建議將不勝感激。

如果您的參數在 url 中,請通過此屬性navigationAction.request.url在此 function 中提取它以獲取參數:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)

就像你開始的那樣:

  1. 在 JavaScript 中,需要在 iOS 應用程序上觸發某些東西的按鈕/鏈接應該這樣做: window.location="myappname://func1";

  2. Javascript 還應該有一個可訪問的方法(例如,應該可以從瀏覽器控制台訪問) myobject.jsfunc()

  3. 在 iOS WebView 上,您使用 myappname:// URL 攔截請求,例如:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    NSURL *URL = [request URL];
    NSString *requestStr = [[request URL] absoluteString]; //Get the URL
    //NSLog(@"Native method call '%@'", requestStr);

    if ([requestStr hasPrefix:@"openpanzer"]) {
        //The [URL host] is the next part of the link so we can use that like a selector
        NSString *selectorName = [URL host];
        id data = nil;        
        NSMutableArray *parameters = [NSMutableArray array];
        if ( ![[URL path] isEqualToString:@""] )
        {
            selectorName =  [NSString stringWithFormat:@"%@:", selectorName];
            parameters = [NSMutableArray arrayWithArray: [[URL path] componentsSeparatedByString:@"/"] ];
            [parameters removeObjectAtIndex:0]; //first object is just a slash "/"
            if ( [parameters count] == 0 ) {
                data = nil;
                NSLog(@"NIL parameter call");
            }
            else if ( [parameters count] == 1 ) {
                data = [parameters objectAtIndex:0];
                NSLog(@"Single parameter call %@", data);
            }
            else {
                data = parameters;
            }
        }

        SEL method = NSSelectorFromString( selectorName );
        if ([nativeGlue respondsToSelector:method]) {
            if (data == nil)
                [nativeGlue performSelector:method];
            else
                [nativeGlue performSelector:method withObject:data];
        }
        else {
            NSLog(@"Can't find native method '%@' with param '%@'", selectorName, data);
        }


        return NO;
    }
    return YES;
}
  1. 在 iOS(WebViewDelegate 或 AppDelegate)上定義您的 func1 即: - (void) func1

  2. 如果您需要將結果發送回您的 javascript 應用程序,請使用:

[webView callJSFunction: jsFunc];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM