关于ios “<null>”的异常处理

本文介绍了一种在iOS开发中处理服务器返回数据中null值的方法。通过对AFNetwork库的定制修改,可以将null值替换为空字符串,从而避免应用崩溃。此外,还推荐了一个名为NullSafe的Category,可以在运行时将null值安全地转换为nil。

在iOS开发过程中经常需要与服务器进行数据通讯,但是在数据接通过程中会出现:null "<null>"等问题导致莫名其妙的崩溃。

相信你一定会写各种判断来处理这些异常,甚至你还会一个一个接口的去改,折让我们实在是心灰意冷。

再者可能你会写个分类 调它。这样也会让你非常的苦恼!

最近发现个处理的方法

如果你使用AFNetwork 这个库做网络请求的话,可以用以下代码,自动帮你去掉这个讨厌的空值:

self.removesKeysWithNullValues = YES;

这样就可以删除掉含有null指针的key-value。 
但有时候,我们想保留key,以便查看返回的字段有哪些。没关系,我们进入到这个框架的AFURLResponseSerialization.m类里,利用搜索功能定位到AFJSONObjectByRemovingKeysWithNullValues,贴出代码:

static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
    if ([JSONObject isKindOfClass:[NSArray class]]) { NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; for (id value in (NSArray *)JSONObject) { [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; } return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) { id value = (NSDictionary *)JSONObject[key]; if (!value || [value isEqual:[NSNull null]]) { //这里是本库作者的源代码 //[mutableDictionary removeObjectForKey:key]; //下面是改动后的,将空指针类型改为空字符串 mutableDictionary[key] = @""; } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); } } return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; } return JSONObject; }
将空指针value改为空字符串,空指针问题瞬间解决啦。


如果你没有用AF也没有关系下面我们来看看这个终极解决的办法:
终于找到了一劳永逸的方案,牛逼的老外写了一个Category,叫做NullSafe ,在运行时操作,把这个讨厌的空值置为nil,而nil是安全的,可以向nil对象发送任何message而不会奔溃。这个category使用起来非常方便,只要加入到了工程中就可以了,你其他的什么都不用做,对,就是这么简单。详细的请去Github上查看;
解压文件之后,直接将NullSafe.m文件导入到项目中就行了。

https://github.com/nicklockwood/NullSafe



 


转载于:https://www.cnblogs.com/walkingzmz/p/6085762.html

<?xml version="1.0" encoding="UTF-8"?> <jmeterTestPlan version="1.2" properties="5.0" jmeter="5.4.3"> <hashTree> <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="测试计划" enabled="true"> <boolProp name="TestPlan.functional_mode">false</boolProp> <boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp> <boolProp name="TestPlan.serialize_threadgroups">false</boolProp> <elementProp name="TestPlan.user_defined_variables" elementType="Arguments"> <collectionProp name="Arguments.arguments"/> </elementProp> </TestPlan> <hashTree> <Arguments guiclass="ArgumentsPanel" testclass="Arguments" testname="全局静态变量" enabled="true"> <collectionProp name="Arguments.arguments"> <elementProp name="Cookie" elementType="Argument"> <stringProp name="Argument.name">Cookie</stringProp> <stringProp name="Argument.value">SESSION=MzljMDlmNjUtMDVmZi00YTNiLTlkMWYtZmQ1YzJhOWEyZWRh; Hm_lvt_5734acaafaf7a1011672a1fef0933656=1691372752,1691977065,1692078269,1692669577; Hm_lpvt_5734acaafaf7a1011672a1fef0933656=1692944271</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> </collectionProp> </Arguments> <hashTree/> <Arguments guiclass="ArgumentsPanel" testclass="Arguments" testname="环境变量-FiF口语训练线上巡检-冯义" enabled="true"> <collectionProp name="Arguments.arguments"> <elementProp name="iplat" elementType="Argument"> <stringProp name="Argument.name">iplat</stringProp> <stringProp name="Argument.value">www.fifedu.com</stringProp> <stringProp name="Argument.metadata">=</stringProp> <stringProp name="Argument.desc">平台主域名</stringProp> </elementProp> <elementProp name="oral" elementType="Argument"> <stringProp name="Argument.name">oral</stringProp> <stringProp name="Argument.value">moral.fifedu.com</stringProp> <stringProp name="Argument.metadata">=</stringProp> <stringProp name="Argument.desc">口语主域名</stringProp> </elementProp> <elementProp name="ACCOUNTtea" elementType="Argument"> <stringProp name="Argument.name">ACCOUNTtea</stringProp> <stringProp name="Argument.value">csbfsuoralt01</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> <elementProp name="appVersiontea" elementType="Argument"> <stringProp name="Argument.name">appVersiontea</stringProp> <stringProp name="Argument.value">6.7.2</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> <elementProp name="schoolId" elementType="Argument"> <stringProp name="Argument.name">schoolId</stringProp> <stringProp name="Argument.value">2000000026000000001</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> <elementProp name="izuoye" elementType="Argument"> <stringProp name="Argument.name">izuoye</stringProp> <stringProp name="Argument.value">izuoye.fifedu.com</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> <elementProp name="oralenglish" elementType="Argument"> <stringProp name="Argument.name">oralenglish</stringProp> <stringProp name="Argument.value">oralenglish.fifedu.com</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> <elementProp name="ACCOUNTstu" elementType="Argument"> <stringProp name="Argument.name">ACCOUNTstu</stringProp> <stringProp name="Argument.value">csbfsuautostu01</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> <elementProp name="appVersionstu" elementType="Argument"> <stringProp name="Argument.name">appVersionstu</stringProp> <stringProp name="Argument.value">6.7.2</stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> </collectionProp> </Arguments> <hashTree/> <CookieManager guiclass="CookiePanel" testclass="CookieManager" testname="HTTP Cookie管理器" enabled="true"> <collectionProp name="CookieManager.cookies"/> <boolProp name="CookieManager.clearEachIteration">false</boolProp> <boolProp name="CookieManager.controlledByThreadGroup">false</boolProp> </CookieManager> <hashTree/> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="测试环境" enabled="true"> <intProp name="ThreadGroup.num_threads">1</intProp> <intProp name="ThreadGroup.ramp_time">1</intProp> <longProp name="ThreadGroup.delay">0</longProp> <longProp name="ThreadGroup.duration">0</longProp> <stringProp name="ThreadGroup.on_sample_error">continue</stringProp> <boolProp name="ThreadGroup.scheduler">false</boolProp> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="LoopController" enabled="true"> <boolProp name="LoopController.continue_forever">false</boolProp> <intProp name="LoopController.loops">1</intProp> </elementProp> </ThreadGroup> <hashTree> <org.apache.jmeter.control.UtpSimpleController guiclass="org.apache.jmeter.control.gui.UtpSimpleControlPanel" testclass="org.apache.jmeter.control.UtpSimpleController" testname="登录首页" enabled="true"> <stringProp name="STEP_ID">8dd8d36b-43bf-4184-9a48-63cac5a69c87</stringProp> </org.apache.jmeter.control.UtpSimpleController> <hashTree> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="登录" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments"> <collectionProp name="Arguments.arguments"> <elementProp name="" elementType="HTTPArgument"> <boolProp name="HTTPArgument.always_encode">false</boolProp> <stringProp name="Argument.value"></stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> </collectionProp> </elementProp> <stringProp name="STEP_ID">cc55eb23-36cb-4edb-af7d-b8c66372bd77</stringProp> <stringProp name="HTTPSampler.protocol">https</stringProp> <stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.path">https://ktest.fifedu.com/kyxl-app//account/userLogin?appNetwork=WIFI&appResolX=828&appResolY=1792&appType=1&appVer=6.7.2&loginName=AHHF71201&osType=2&osVer=18.5&password=cXlOOWFjaGkhQCM=&phoneModel=iPhone 11</stringProp> <stringProp name="HTTPSampler.contentEncoding">UTF-8</stringProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp> <stringProp name="HTTPSampler.method">POST</stringProp> <stringProp name="HTTPSampler.connect_timeout">60000</stringProp> <stringProp name="HTTPSampler.response_timeout">60000</stringProp> <boolProp name="HTTPSampler.follow_redirects">true</boolProp> <boolProp name="HTTPSampler.auto_redirects">false</boolProp> <boolProp name="HTTPSampler.postBodyRaw">true</boolProp> </HTTPSamplerProxy> <hashTree> <org.apache.jmeter.extractor.UtpExtractor guiclass="org.apache.jmeter.extractor.gui.UtpExtractorGui" testclass="org.apache.jmeter.extractor.UtpExtractor" testname="参数提取" enabled="true"> <stringProp name="STEP_ID">f747501a-be32-4ce6-87bb-a9c420c2b3ae</stringProp> <stringProp name="DC_TASK_ID"></stringProp> <stringProp name="UtpAssert.extractData">[ { "varName":"tokenstu", "expression":"$.data.token", "obj":"responseData", "defaultValue":"", "id":"b3256752-20af-f669-307b-70e2e72c0584", "globalVar":false, "type":"jsonPath", "matchNumber":1 } ]</stringProp> </org.apache.jmeter.extractor.UtpExtractor> <hashTree/> <org.apache.jmeter.extractor.UTPJSR223PostProcessor guiclass="TestBeanGUI" testclass="org.apache.jmeter.extractor.UTPJSR223PostProcessor" testname="后置脚本步骤" enabled="true"> <stringProp name="STEP_ID">9cd30030-bca2-49f0-bb7d-3f9d42244fc7</stringProp> <stringProp name="cacheKey">false</stringProp> <stringProp name="DC_TASK_ID">DC_TASK_FLAG0.36192556040486945</stringProp> <stringProp name="scriptLanguage">groovy</stringProp> <stringProp name="parameters"></stringProp> <stringProp name="script">import java.security.MessageDigest import java.math.BigInteger try { // 1. 确保获取 token 变量值的安全方式 String tokenstu = vars.get("tokenstu") ?: "" // 2. 定义固定参数值 String uid = "05973fecfd4904a4a93c8d7ee43eb074" String SECRET_KEY = "fifedu@2014-9999!@#_appId" // 3. 拼接加密字符串 String rawString = uid + tokenstu + SECRET_KEY // 4. MD5 加密处理 (明确编码格式) MessageDigest md = MessageDigest.getInstance("MD5") md.update(rawString.getBytes("UTF-8")) // 5. 生成十六进制哈希值并补零 String appId = new BigInteger(1, md.digest()).toString(16).padLeft(32, &apos;0&apos;) // 6. 关键:正确存储变量到 JMeter 上下文 vars.put("APPIDstu", appId) // 7. 验证变量是否存储成功 if (vars.get("APPIDstu") == appId) { log.info("✅ 变量存储成功! APPIDstu=${appId}") } else { log.error("❌ 变量存储失败!") } } catch (Exception e) { log.error("❌ 脚本执行错误: " + e.getMessage(), e) // 设置默认值避免后续引用失败 vars.put("APPIDstu", "ERROR_" + System.currentTimeMillis()) }</stringProp> </org.apache.jmeter.extractor.UTPJSR223PostProcessor> <hashTree/> <HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="请求头管理器" enabled="true"> <collectionProp name="HeaderManager.headers"/> </HeaderManager> <hashTree/> </hashTree> <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="自主学习列表selfTaskInfo" enabled="true"> <elementProp name="HTTPsampler.Arguments" elementType="Arguments"> <collectionProp name="Arguments.arguments"> <elementProp name="" elementType="HTTPArgument"> <boolProp name="HTTPArgument.always_encode">false</boolProp> <stringProp name="Argument.value"></stringProp> <stringProp name="Argument.metadata">=</stringProp> </elementProp> </collectionProp> </elementProp> <stringProp name="STEP_ID">f00b8a03-8910-ba7d-2915-278a2d0dfec6</stringProp> <stringProp name="HTTPSampler.protocol">https</stringProp> <stringProp name="HTTPSampler.domain"></stringProp> <stringProp name="HTTPSampler.path">https://ktest.fifedu.com/kyxl-app/stu/index/selfTaskInfo?userId=849d9c3856c548cdb831def88d220fe7</stringProp> <stringProp name="HTTPSampler.contentEncoding">UTF-8</stringProp> <boolProp name="HTTPSampler.use_keepalive">true</boolProp> <stringProp name="HTTPSampler.method">POST</stringProp> <stringProp name="HTTPSampler.connect_timeout">60000</stringProp> <stringProp name="HTTPSampler.response_timeout">60000</stringProp> <boolProp name="HTTPSampler.follow_redirects">true</boolProp> <boolProp name="HTTPSampler.auto_redirects">false</boolProp> <boolProp name="HTTPSampler.postBodyRaw">true</boolProp> </HTTPSamplerProxy> <hashTree> <org.apache.jmeter.modifiers.UTPJSR223PreProcessor guiclass="TestBeanGUI" testclass="org.apache.jmeter.modifiers.UTPJSR223PreProcessor" testname="前置脚本步骤_copy" enabled="true"> <stringProp name="STEP_ID">d907f085-cc60-a2f9-90a8-01ebb0ac6d98</stringProp> <stringProp name="cacheKey">false</stringProp> <stringProp name="DC_TASK_ID">DC_TASK_FLAG0.574227720764738</stringProp> <stringProp name="scriptLanguage">javascript</stringProp> <stringProp name="parameters"></stringProp> <stringProp name="script">// 导入必要的 Java 类 var URL = Java.type(&apos;java.net.URL&apos;); var URLDecoder = Java.type(&apos;java.net.URLDecoder&apos;); var MessageDigest = Java.type(&apos;java.security.MessageDigest&apos;); var UUID = Java.type(&apos;java.util.UUID&apos;); // 生成签名的函数 function generateSign(params, uuid, tokenstu) { var myKey = &apos;fifedu@2014-9999!@#&apos;; // 提取参数值并处理列表类型 var values = []; for (var key in params) { var value = params[key]; if (value instanceof java.util.List) { // 处理列表值:取第一个非空元素 for (var i = 0; i < value.size(); i++) { if (value.get(i) !== null && value.get(i).toString().trim() !== &apos;&apos;) { values.push(value.get(i).toString()); break; } } } else if (value !== null && value.toString().trim() !== &apos;&apos;) { // 处理普通值 values.push(value.toString()); } } // 排序并连接值 values.sort(); var text = values.join(&apos;&apos;) + myKey + tokenstu + uuid; vars.put(&apos;text_stu9&apos;, text); // 生成 MD5 签名 var md = MessageDigest.getInstance(&apos;MD5&apos;); var digest = md.digest(new java.lang.String(text).getBytes(&apos;UTF-8&apos;)); // 将字节数组转换为十六进制字符串 var hexString = &apos;&apos;; for (var i = 0; i < digest.length; i++) { var hex = (digest[i] & 0xFF).toString(16); if (hex.length === 1) { hex = &apos;0&apos; + hex; } hexString += hex; } return hexString; } // 1. 生成随机 UUID var generatedUuid = UUID.randomUUID().toString(); vars.put(&apos;uuid&apos;, generatedUuid); // 获取当前采样器的 URL 和查询参数 var samplerUrl = sampler.getUrl().toString(); var url = new URL(samplerUrl); var query = url.getQuery(); // 解析查询参数 var params = {}; if (query !== null) { var queryPairs = query.split(&apos;&&apos;); for (var i = 0; i < queryPairs.length; i++) { var pair = queryPairs[i].split(&apos;=&apos;, 2); var name = URLDecoder.decode(pair[0], &apos;UTF-8&apos;); var value = pair.length > 1 ? URLDecoder.decode(pair[1], &apos;UTF-8&apos;) : &apos;&apos;; params[name] = value; } } // 生成签名并存储变量 var tokenstu = vars.get(&apos;tokenstu&apos;) || &apos;&apos;; vars.put(&apos;signstu9&apos;, generateSign(params, generatedUuid, tokenstu)); vars.put(&apos;uuid_stu9&apos;, generatedUuid); vars.put(&apos;token_stu9&apos;, tokenstu); vars.put(&apos;params_stu9&apos;, JSON.stringify(params)); // 使用 JSON 代替 inspect()</stringProp> </org.apache.jmeter.modifiers.UTPJSR223PreProcessor> <hashTree/> <HeaderManager guiclass="HeaderPanel" testclass="HeaderManager" testname="请求头管理器" enabled="true"> <collectionProp name="HeaderManager.headers"> <elementProp name="UUID" elementType="Header"> <stringProp name="Header.name">UUID</stringProp> <stringProp name="Header.value">${uuid_stu9}</stringProp> </elementProp> <elementProp name="APPID" elementType="Header"> <stringProp name="Header.name">APPID</stringProp> <stringProp name="Header.value">${APPIDstu}</stringProp> </elementProp> <elementProp name="Authorization" elementType="Header"> <stringProp name="Header.name">Authorization</stringProp> <stringProp name="Header.value">Basic ${tokenstu}</stringProp> </elementProp> <elementProp name="APPTYPE" elementType="Header"> <stringProp name="Header.name">APPTYPE</stringProp> <stringProp name="Header.value">kyxl_student_app_ios</stringProp> </elementProp> <elementProp name="Accept" elementType="Header"> <stringProp name="Header.name">Accept</stringProp> <stringProp name="Header.value">*/*</stringProp> </elementProp> <elementProp name="appVersion" elementType="Header"> <stringProp name="Header.name">appVersion</stringProp> <stringProp name="Header.value">6.7.2</stringProp> </elementProp> <elementProp name="schoolId" elementType="Header"> <stringProp name="Header.name">schoolId</stringProp> <stringProp name="Header.value">2811000226000000690</stringProp> </elementProp> <elementProp name="Accept-Language" elementType="Header"> <stringProp name="Header.name">Accept-Language</stringProp> <stringProp name="Header.value">zh-Hans-CN;q=1, ru-CN;q=0.9</stringProp> </elementProp> <elementProp name="Accept-Encoding" elementType="Header"> <stringProp name="Header.name">Accept-Encoding</stringProp> <stringProp name="Header.value">gzip, deflate, br</stringProp> </elementProp> <elementProp name="TOKEN" elementType="Header"> <stringProp name="Header.name">TOKEN</stringProp> <stringProp name="Header.value">${tokenstu}</stringProp> </elementProp> <elementProp name="Content-Type" elementType="Header"> <stringProp name="Header.name">Content-Type</stringProp> <stringProp name="Header.value">application/x-www-form-urlencoded</stringProp> </elementProp> <elementProp name="LANGUAGE" elementType="Header"> <stringProp name="Header.name">LANGUAGE</stringProp> <stringProp name="Header.value">ENGLISH</stringProp> </elementProp> <elementProp name="User-Agent" elementType="Header"> <stringProp name="Header.name">User-Agent</stringProp> <stringProp name="Header.value">kyxl/6.7.2 (iPhone; iOS 18.5; Scale/2.00)</stringProp> </elementProp> <elementProp name="Content-Length" elementType="Header"> <stringProp name="Header.name">Content-Length</stringProp> <stringProp name="Header.value">39</stringProp> </elementProp> <elementProp name="Connection" elementType="Header"> <stringProp name="Header.name">Connection</stringProp> <stringProp name="Header.value">keep-alive</stringProp> </elementProp> <elementProp name="ACCOUNT" elementType="Header"> <stringProp name="Header.name">ACCOUNT</stringProp> <stringProp name="Header.value">AHHF71201</stringProp> </elementProp> <elementProp name="roleName" elementType="Header"> <stringProp name="Header.name">roleName</stringProp> <stringProp name="Header.value">STU</stringProp> </elementProp> <elementProp name="SIGN" elementType="Header"> <stringProp name="Header.name">SIGN</stringProp> <stringProp name="Header.value">${signstu9}</stringProp> </elementProp> </collectionProp> </HeaderManager> <hashTree/> </hashTree> </hashTree> </hashTree> <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="查看结果树"> <boolProp name="ResultCollector.error_logging">false</boolProp> <objProp> <name>saveConfig</name> <value class="SampleSaveConfiguration"> <time>true</time> <latency>true</latency> <timestamp>true</timestamp> <success>true</success> <label>true</label> <code>true</code> <message>true</message> <threadName>true</threadName> <dataType>true</dataType> <encoding>false</encoding> <assertions>true</assertions> <subresults>true</subresults> <responseData>false</responseData> <samplerData>false</samplerData> <xml>false</xml> <fieldNames>true</fieldNames> <responseHeaders>false</responseHeaders> <requestHeaders>false</requestHeaders> <responseDataOnError>false</responseDataOnError> <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage> <assertionsResultsToSave>0</assertionsResultsToSave> <bytes>true</bytes> <sentBytes>true</sentBytes> <url>true</url> <threadCounts>true</threadCounts> <idleTime>true</idleTime> <connectTime>true</connectTime> </value> </objProp> </ResultCollector> <hashTree/> </hashTree> </hashTree> </jmeterTestPlan> 不要省略,把修改后的脚本完整输出出来
最新发布
08-26
using Cysharp.Threading.Tasks; using System.IO; using UnityEngine; using UnityEngine.Networking; using RenderHeads.Media.AVProVideo; using Excel; using LitJson; using System.Collections.Generic; using System.Data; public class StreamingAssetsLoader : MonoBehaviour { /// <summary> /// 从StreamingAssets文件夹异步加载文件并返回byte数组 /// </summary> /// <param name="filePath">文件在StreamingAssets文件夹中的路径</param> /// <returns>返回文件的byte数组,若加载失败则返回null</returns> public static async UniTask<byte[]> LoadFileFromStreamingAssets(string filePath) { // 拼接完整路径 string fullPath = Application.streamingAssetsPath + filePath; if (!File.Exists(fullPath)) return null; Debug.Log("Streaming加载器:" + fullPath); using (UnityWebRequest www = UnityWebRequest.Get(fullPath)) { www.certificateHandler = new WebReqSkipCert(); // 等待请求完成 await www.SendWebRequest(); // 检查请求结果 if (www.result != UnityWebRequest.Result.Success) { // 记录错误信息 Debug.LogError(www.error); return null; } // 返回下载的数据 return www.downloadHandler.data; } } /// <summary> /// 从StreamingAssets文件夹异步加载图片并返回Texture2D对象 /// </summary> /// <param name="filePath">文件在StreamingAssets文件夹中的路径</param> /// <returns>返回加载的Texture2D对象,若加载失败则返回null</returns> public static async UniTask<Texture2D> LoadIMGFromStreamingAssets(string filePath) { // 加载文件并获取byte数组 byte[] bytes = await LoadFileFromStreamingAssets(filePath)??null; if (bytes is null) { return null; } // 创建一个新的Texture2D对象 Texture2D texture = new Texture2D(1, 1); // 加载图片数据到Texture2D对象中 texture.LoadImage(bytes); return texture; } /// <summary> /// 从StreamingAssets文件夹异步加载图片并返回Sprite对象 /// </summary> /// <param name="filePath">文件在Streami
03-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值