我們在寫程序的時候有時候避免不了要加載web頁面,當然也避免不了要與web進行交互了,有時候一個比較好看規整的界面
我們iOS 在前端要花很大一會要擺控件,要適配,要賦值等操作,但是加載別人寫好的web頁面速度快,效率高,界面好,
但是就必須交互,如果交互性很強的地方用原生的比較好
簡單的談談我用到的js交互
我們的控制器加載UIWebView之後,交互中這個方法很重要
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
1.js向iOS傳值
我在這個方法裏面先截取url
NSString *requestString = [[requestURL] absoluteString];
NSArray *components = [requestStringcomponentsSeparatedByString:@":"];
我可愛的後臺人員給我們這樣的方法
gozhusu這個就是方法名,加號後面的一串都是參數,也就是說現在可愛的後臺人員要給我傳值,那麼我在iOS裏面怎麼接收呢
我現在截取到url同時根據@":"截取url字符串放進數組裏面
結果如下:
現在,我就要獲取後臺給我的值,如下
if ([componentscount] > 1 && [(NSString *)[componentsobjectAtIndex:0]isEqualToString:@"gozhusu"]) {
if([(NSString *)[componentsobjectAtIndex:1]isEqualToString:@"arg"])
{
NSString *parma = [[NSStringalloc]initWithString:[componentsobjectAtIndex:2]];
NSArray *array = [parma componentsSeparatedByString:@","];
PatientInfoVC *patientInfo = [[PatientInfoVCalloc]init];
NSString *nam = [ array[2]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *sex = [array[1]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
patientInfo.sex= sex;
patientInfo.name = nam;
patientInfo.appointid = array[0];
[self.navigationControllerpushViewController:patientInfo animated:YES];
}
return NO;
}
2.ios 向js傳值,相同的道理stringByEvaluatingJavaScriptFromString是非常有用的if ([componentscount] > 1 && [(NSString *)[componentsobjectAtIndex:0]isEqualToString:@"getauthid"]) {
if([(NSString *)[componentsobjectAtIndex:1]isEqualToString:@"arg"])
{
if (hosiptalArr) {
[webView stringByEvaluatingJavaScriptFromString:[NSStringstringWithFormat:@"authid('%@');",[UserConfiggetInstance].authorityId]];
}
}
return NO;
}
我將[UserConfig getInstance].authorityId]這個值通過authid方法就傳給js了