欢迎你们关注个人公众号,我会按期分享一些我在项目中遇到问题的解决办法和一些iOS实用的技巧,现阶段主要是整理出一些基础的知识记录下来
git
文章也会同步更新到个人博客:
ppsheep.comgithub
以前写了一篇关于APP之间跳转的文章,期间有同窗说可否出一个相似于微信登陆或者支付宝支付之类的,跳转到支付宝得到消息再调回源程序,而且带上信息。今天咱们就再来聊聊,实现这样一种效果,没看过以前应用跳转的,请移步:
ppsheep.com/2016/10/27/…数组
以前咱们说到APP之间的跳转,其实就是经过一个URL Schemes进行跳转,APP之间的传值,其实也是经过这个URL进行传值。微信
再有咱们想跳回原来程序,那么咱们还须要知道源程序的URL Schemes,这样咱们才能跳回到源程序,因此在传递参数的时候 咱们还须要把源程序的URL Schemes传递过去。app
咱们须要传递的参数:ui
还有一个重要的事情,由于咱们须要从APP2跳回APP1,因此咱们还须要设置APP1的URL Schemes,怎么设置,我这里就不写出来了,具体能够看上一篇跳转解析url
咱们以前知道 打开另外一个APP,是打开一个URL
APP2://相似于这种,那咱们会想到通常咱们http有一种方式携带参数 http://url?name=?&age=?spa
咱们APP之间的传递参数方式其实也是这样的方式code
//获取APP2的URL Scheme 还须要带上当前App的APP1
NSString *URLScheme = @"APP2://APP1";
//咱们参数须要穿name age
NSString *params = @"name=yq&age=23";
//接下来加上咱们须要携带的参数
NSString *realURL = [NSString stringWithFormat:@"%@?%@",URLScheme,params];
NSURL *appURL = [NSURL URLWithString:realURL];
//判断手机中是否安装了APP2
if ([[UIApplication sharedApplication] canOpenURL:appURL]) {
//打开APP2ViewController2
[[UIApplication sharedApplication] openURL:appURL];
}else{
NSLog(@"没有安装APP2");
}复制代码
咱们最终的appURL 是: component
APP2://APP1?name=yq&age=23复制代码
咱们在APP2中处理这个跳转的URL
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
if ([url.absoluteString containsString:@"APP1"]){
NSLog(@"%@",url);
//拿到源程序的
NSString * urlschemes = [[url.absoluteString componentsSeparatedByString:@"//"][1] componentsSeparatedByString:@"?"][0];
//拿到参数
NSRange range = [url.absoluteString rangeOfString:@"?"];
NSString *paramStr = [url.absoluteString substringFromIndex:range.location+1];//去除问号
NSArray *params = [paramStr componentsSeparatedByString:@"&"];
NSLog(@"%@",params);
//跳回源程序
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 延时3s模拟处理后回调指定的 URL Schemes并传递结果
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"APP2://"]]) {
NSLog(@"跳转成功");
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@://back?name=back&code=200",urlschemes]]];
}else{
NSLog(@"跳转失败");
NSLog(@"未安装应用!");
}
});
}
}复制代码
在APP2中 咱们拿到了APP1传递的参数 放在了params数组中,一样的 咱们在APP1中再处理从APP2跳回来的信息
/** 跳转回来 */ -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary*)options{ if ([url.absoluteString containsString:@"back"]) { //拿到参数 NSRange range = [url.absoluteString rangeOfString:@"?"]; NSString *paramStr = [url.absoluteString substringFromIndex:range.location+1];//去除问号 NSArray *params = [paramStr componentsSeparatedByString:@"&"]; NSLog(@"%@",params); } return YES; } 复制代码
这样咱们也拿到了APP2跳回来的数据
在iOS10中跳转的API有更新,具体的变化能够看API 我这里就不列出来了
源代码放在: