iOS获取设备名称

在线工具-获取iOS设备名称JSON数据 https://www.cnblogs.com/wgb1234/articles/17555311.html

2022年7月22日 星期五 20时27分35秒更新, 自从发现油猴脚本这个好东西之后,一发不可收, 就总想着写点工作上用得着的东西, 于是用处来了
直接上代码:

// ==UserScript==
// @name         翻译iOS设备名称
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://xxxx.com.cn/tracking?uuid=*
// @icon         https://www.google.com/s2/favicons 
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    const jsonData = [{
            "name": "iPhone 2G",
            "identifier": "iPhone1,1",

        }, //此处略去众多数据量
        {
            "name": "iPhone 3G",
            "identifier": "iPhone1,2",

        }
    ];


    var targetNode = document.getElementById('dataList');
    var config = { attributes: true, childList: true, subtree: true };
    var callback = function(mutationsList) {
        mutationsList.forEach(function(item, index) {
            if (item.type == 'childList') {
                if (index < 1) {//避免频繁调用
                    setTimeout(function() {
                        const idf = targetNode.innerHTML.match(/iPhone[0-9]+\,[0-9]+/);
                        const iphoneId = idf.shift();
                        var filterArr = jsonData.filter(function(item) {
                            return iphoneId == item.identifier;
                        });
                        const repStr = filterArr[0].name;
                        if (repStr.length > 0) {
                            var tds = document.getElementsByTagName('td');
                            for (var i = 0; i < tds.length; i++) {
                                var td = tds[i];
                                td.innerHTML = td.innerHTML.replace(/iPhone[0-9]+\,[0-9]+/g, repStr);
                            }
                        }
                    }, 100);
                }
            }
        });
    };
    var observer = new MutationObserver(callback);
    observer.observe(targetNode, config);

})();

以上代码,会在列表页面刷新后实时监听页面变化,页面刷新之后通过正则取出id匹配对应的设备name并完成替换,就是这么个原理

2022年 4月22日 星期五 19时42分53秒 更新 https://github.com/WangGuibin/Alfred-iOSDeviceName 写了个Alfred插件方便查找
我的使用场景是这样的,原先是写了翻译代码在SDK内部的,仅仅只是为了优化管理后台看埋点信息定位问题而已,直到业务部门提需求过来说要优化SDK包的大小,于是从LinkMap分析,
再到可执行文件的优化,编译选项设置各种尝试之后,无奈只能删减不是很必要的代码了,因为类似iPhone11,8 这样的字符串就足够定位到机型了,但是人脑要记住这一系列玩意儿还是比较费劲的,实在记不住,就想着能不能造个轮子,查问题的时候直接翻译出来 这样就省事儿多了~
当然,如果后端配置json数据去匹配是最好不过的了

苹果在获取设备名称这一点上做的确实不够人性化,比如我的设备是iPhone XR,根据#import <sys/utsname.h>框架获取的字段是iPhone11,8,这一般人看不出什么门道,实际上它代表的是手机固件的版本

struct utsname systemInfo;
    uname(&systemInfo);
    // 获取设备标识Identifier即类似于"iPhone11,8"这种字符串
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];

网上很多维护通过Identifier去翻译设备名称的胶水代码,新出的机型很多文章或者代码都不及时更新的,毕竟维护成本在那里,确实没啥特别好的办法,但是有没有什么一劳永逸的办法呢,好像目前并没有~
但是所幸找到以下两个网站比较全面且可以作为参考的:
https://www.theiphonewiki.com/wiki/Models
https://ipsw.me
以及API接口 https://api.ipsw.me/v4/devices

通过下面👇下载的json文件转成plist即可通过命令行工具转一下,或者直接json解析最是直接

fileSubffix=${1##*.} #后缀名
if [[ "${fileSubffix}"x == "json"x ]] ;
then
    plutil -convert xml1 "${1}" -o "${1%.*}".plist
fi  

if [[ "${fileSubffix}"x == "plist"x ]] ;
then
 plutil -convert json "${1}" -o "${1%.*}".json
fi  
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Desktop/iOSDevices.plist"];
        NSLog(@"%@",filePath);
        NSArray *dataArr = [NSArray arrayWithContentsOfFile:filePath];
        NSLog(@"dataArr.count=%ld",dataArr.count);
        NSMutableArray *dataM = [NSMutableArray array];
        for (NSDictionary *dic in dataArr) {
            NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
            dicM[@"deviceName"] = dic[@"name"];
            dicM[@"identifier"] = dic[@"identifier"];
            if([dic[@"name"] hasPrefix:@"iP"]){
                [dataM addObject:dicM];
            }
        }
        
        NSString *targetPath = [NSHomeDirectory() stringByAppendingFormat:@"/Desktop/AllDeviceInfo.plist"];

        [dataM writeToFile:targetPath atomically:YES];
        
        
       NSLog(@"dataM.count= %ld \n %@",dataM.count,dataM);

        
    }
    return 0;
}

等苹果发布新品之后,一般这些网站会同步更新,只要对着更新对应的匹配规则即可
通过上面<sys/utsname.h>可以拿到类似iPhone11,8这种Identifier字段可以遍历匹配https://api.ipsw.me/v4/devices 这个接口返回的数据,请求一次缓存起来使用即可,有新品发布时再搞更新策略啥的
//类似于这样通过identifier匹配对应的name字段即可

[
    {
        "name": "iPhone 2G",
        "identifier": "iPhone1,1",
        "boards": [
            {
                "boardconfig": "m68ap",
                "platform": "s5l8900x",
                "cpid": 35072,
                "bdid": 0
            }
        ],
        "boardconfig": "m68ap",
        "platform": "s5l8900x",
        "cpid": 35072,
        "bdid": 0
    },
    {
        "name": "iPhone 3G",
        "identifier": "iPhone1,2",
        "boards": [
            {
                "boardconfig": "n82ap",
                "platform": "s5l8900x",
                "cpid": 35072,
                "bdid": 4
            }
        ],
        "boardconfig": "n82ap",
        "platform": "s5l8900x",
        "cpid": 35072,
        "bdid": 4
    }
]
<!-- run -->
<style> 
.bg{
           display: flex;
            flex-direction: row;
            justify-content: flex-start;
}
  .btn{
           box-shadow: 2px 2px 3px #999;
            margin: 20px;
            background: linear-gradient(90deg, #00ff11 ,#ff0000);
            color: white;
            font-size: 15px;
            border-radius: 20px;
            width: 150px;
            height: 40px;
            line-height: 40px;
            text-align: center;
  }
</style>
<div class="bg"> 
<button class="btn" id="get-data-btn"> 获取最新数据 </button>
<button class="btn" id="download-btn"  onclick="downloadJSON()"> 下载JSON数据 </button>
<div id="tips" style="color:red;"> 正在请求数据中...  </div>
</div>

<div id="show-json">
 </div>
<script>
function openDownloadDialog(url, saveName)
{
	if(typeof url == 'object' && url instanceof Blob)
	{
		url = URL.createObjectURL(url); // 创建blob地址
	}
	var aLink = document.createElement('a');
	aLink.href = url;
	aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
	var event;
	if(window.MouseEvent) event = new MouseEvent('click');
	else
	{
		event = document.createEvent('MouseEvents');
		event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	}
	aLink.dispatchEvent(event);
}
function downloadJSON() {
         var json = document.getElementById('my-json').innerText;
          var blob = new Blob([json], {
                type: 'text/json,charset=UTF-8'
            });
           openDownloadDialog(blob, 'iOSDevices.json');
}
            var downloadBtn = document.getElementById('download-btn');
            var tipsLabel = document.getElementById('tips');
            tipsLabel.style.display = 'none';
            downloadBtn.style.display = 'none';

 window.onload = function() {
            var getDataBtn = document.getElementById('get-data-btn');
           getDataBtn.onclick = function () {
                 tipsLabel.style.display = 'block';
                 var linkUrl = "https://api.ipsw.me/v4/devices"
            var xmlhttp = new XMLHttpRequest();
            var type = "GET"; 
            xmlhttp.open(type, linkUrl, true); 
            xmlhttp.send(); 
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
                   tipsLabel.style.display = 'none';
                   downloadBtn.style.display = 'block';
                    var result = JSON.parse(xmlhttp.response); //获取到的json数据
                     var div = document.getElementById('show-json')
                    div.innerHTML = `  <div class="copyItem" style="position: relative;">
                    <div class="codeType">json</div>
                    <div class="clipboard-button" id="copy_btn_4"  data-clipboard-target="#post_copy_target_4"  title="复制">
                    </div><pre class="language-json" id="post_copy_target_4" highlighted="true">
                    <code  class="language-json" id="my-json" style="font-family: 'mono-font' !important;">${JSON.stringify(result,null,4)}</code></pre></div> `;
                }
            }
       }   
    }
</script>

Alfred插件github地址

posted @ 2022-02-24 20:38  CoderWGB  阅读(812)  评论(0编辑  收藏  举报