美文网首页iOS开发知识小集
iOS检测本机是否安装某个App

iOS检测本机是否安装某个App

作者: 单线程Jack | 来源:发表于2019-06-03 14:09 被阅读31次
    两种检测方式

    1.bundle ID —— 包名,是每个应用的唯一识别码(换言之,这个值是一定会有的)
    2.URL Scheme —— 供APP 之间跳转(打开应用)使用,需要在下面的配置中去手动添加(换言之,如果我没有配置他,他也没有默认值,实际上我是无法通过外部应用打开的)

    Bundle ID

    缺点:方法一消耗一定的性能(手机安装APP比较多的话),APP 审核必被拒
    优点:跳过了iOS9.0 对canOpenURL这个API使用限制

    #include <objc/runtime.h>
    Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
     NSObject* workspace = [LSApplicationWorkspace_class performSelector:@selector(defaultWorkspace)];
    NSArray *allApplications = [workspace performSelector:@selector(allApplications)];//这样就能获取到手机中安装的所有App
    NSLog(@"设备上安装的所有app:%@",allApplications);    NSInteger zlConnt = 0;
    for (NSString *appStr in allApplications) {
          NSString *app = [NSString stringWithFormat:@"%@",appStr];//转换成字符串
            NSRange range = [app rangeOfString:@"你要查询App的bundle ID"];//是否包含这个bundle ID
             if (range.length > 1) {
                    zlConnt ++;
             }
        }
        if (zlConnt >= 1) {
            NSLog(@"已安装");
        }
    
    URL Scheme

    1.必须要提前知道打开APP的列表,也就是白名单,并配置到工程的 info.plist中去。
    2.无法动态更新列表(每次新增都需要去更改这个列表)

    配置的方法:

    1.用 source code 的方式打开工程的 info.plist, 找到(如果没有就添加)LSApplicationQueriesSchemes ,加入对应的 URL Scheme

    <key>LSApplicationQueriesSchemes</key>
      <array>
          <string>wechat</string>
          <string>weixin</string>
          <string>twitter</string>
      </array>
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"IOSDevApp://"]]){
                //说明此设备有安装app
        }else{
                //说明此设备没有安装app
        }
    

    2.假设我们要检测微信是否已安装,那么通过下面这段代码(swift为例). 务必在 string的末尾加上

    func detectInstalled(URLString: String?) -> URL? {
      if let URLString = URLString, let exsistURL = URL(string: URLString), UIApplication.shared.canOpenURL(exsistURL) {
          return exsistURL
      } else {
          return nil
      }
    }
     
    detectInstalled(URLString: "weixin://")
    

    相关文章

      网友评论

        本文标题:iOS检测本机是否安装某个App

        本文链接:https://www.haomeiwen.com/subject/vadcxctx.html