如果可能,那麼我如何在我的代碼中使用JavaScript?是否可以在Objective-C(iphone)中使用JavaScript?
1
A
回答
3
可以在UIWebView中注入JavaScript。
NSString * result = [myUIWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('foo').className"];
1
爲了增加j_freyre的回答,這表明你如何出來的Javascript從目標C執行並獲取數據,也可以從JavaScript調用在一個UIWebView運行目標C代碼。這需要多一點工作,並且有點冒險。
在JavaScript端:
var call_stack = new Array(); //This will hold our Objective C function calls
function addWithObjC(a,b){
call_stack.splice(0,0,"add:"+a+":"+b); //We separate the components of the call (function name, parameters) by a colon, but it could be anything.
window.location.href = "::ObjCcall::";
}
function multiplyWithObjC(a,b){
call_stack.splice(0,0,"multiply:"+a+":"+b);
window.location.href = "::ObjCcall::";
}
這將嘗試加載一個虛假的URL。 「:: ObjCcall ::」可以是任何不是可能有效的url。現在的關鍵是要趕上目的C.申請假設你有一個UIWebView和相應的UIViewController,在UIViewController接口註明:
@interface MyWebViewController : UIViewController <UIWebViewDelegate>{
//declare stuff
}
在實現方面,地方:
[(UIWebView *)self.view setDelegate:self];
你然後通過執行以下操作來捕獲請求:
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *url = [[request URL] absoluteString]; //Our potentially bogus request url
if([url hasSuffix:@"::ObjCcall::"]){ //We're trying to call Objective C code
NSString *command; //Our specially formatted function call
//While our call stack is not empty...
while(![command = [webView stringByEvaluatingJavaScriptFromString:@"call_stack.pop()"]isEqualToString:@""]){
//Break the function call into its compoments
NSArray *segments = [command componentsSeparatedByString:@":"];
//We found a call we respond to
if(([[segments objectAtIndex:0] isEqualToString:@"add"])&&([segments count] > 2)){
//Here is where the Objective C action takes place
float result = [[segments objectAtIndex:1]floatValue] + [[segments objectAtIndex:2]floatValue];
//Do something with the results...
}
else if(([[segments objectAtIndex:0] isEqualToString:@"multiply"])&&([segments count] > 2)){
//Another function
float result = [[segments objectAtIndex:1]floatValue] * [[segments objectAtIndex:2]floatValue];
}
//Add more checks as needed
[segments release];
return NO; //This tells the UIWebView to not try to load the page
}
}
else{
return YES; //This is a valid URL request, load the page
}
}
這比看起來似乎有點複雜一點。但是,UIWebView並不喜歡連續快速更改window.location.href。我們實現一個調用堆棧以確保沒有呼叫被跳過。
設置比Objective C中的Javascript更多的工作,當然,一旦你設置了樣板,你需要做的就是在shouldStartLoadWithRequest中的while循環中添加檢查。
通過在Objective-C代碼中使用JavaScript,究竟是什麼意思?他們完全是兩種不同的語言;我能想到的唯一地方就是網絡視圖。 – BoltClock 2011-03-18 07:07:14