Swift 4中获取特定登录用户个人资料数据失败求助
问题分析与解决方案
看起来你在通过API获取公司资料并匹配当前用户ID时遇到了瓶颈,我先帮你拆解下现有代码里的几个关键问题,再给出修复后的版本:
核心问题点
- 强制解包风险:
empURL!会在URL构造失败时直接崩溃,应该先做安全校验 - UI更新逻辑混乱:你在遍历
getCompanyArray的每一项时都重复去UserDefaults取ID、过滤数组,而且最终给companyName_lbl赋值用的是遍历项mainArr,完全没用到过滤后的getComData,这根本达不到匹配用户ID的目的 - 数据类型不匹配隐患:如果
company_id是Int类型,但你从UserDefaults取到的userID是String,那==比较永远不成立,这很可能是你拿不到对应数据的核心原因 - 错误处理不完整:没检查
data是否为nil,也没验证HTTP响应的状态码(比如是否是200成功)
修复后的代码
func getCompanyFunc() { // 1. 安全构造URL,避免强制解包崩溃 guard let empURL = URL(string: "http://172.16.1.22/Get-Company-API/get-companies/") else { print("Failed to construct API URL") return } URLSession.shared.dataTask(with: empURL) { [weak self] (data, response, error) in // 2. 先处理网络错误 if let error = error { print("Network error: \(error.localizedDescription)") return } // 3. 验证HTTP响应状态码是否合法 guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { print("Invalid HTTP response or status code") return } // 4. 安全解包返回数据 guard let data = data else { print("No data received from API") return } do { // 5. 解析JSON数据 let companyArray = try JSONDecoder().decode([CompanyDataProfile].self, from: data) print("****Employee Data****\(companyArray)") // 6. 获取当前用户ID,提前取出避免重复操作 guard let userID = UserDefaults.standard.string(forKey: "user_type_id") else { print("User ID not found in UserDefaults") return } print("Company ID Profile=\(userID)") // 7. 过滤匹配的公司数据——注意这里要确认company_id的类型! // 如果company_id是Int,需要把userID转成Int:Int(userID) let matchedCompanies = companyArray.filter { $0.company_id == userID } // 8. 回到主线程更新UI,使用过滤后的结果 DispatchQueue.main.async { guard let self = self else { return } self.getCompanyArray = companyArray self.getComData = matchedCompanies // 取第一个匹配的公司(如果有)更新标签 if let matchedCompany = matchedCompanies.first { self.companyName_lbl.text = matchedCompany.company_name } else { self.companyName_lbl.text = "No company found" } } } catch { print("Error decoding JSON Data: \(error)") } }.resume() }
额外调试建议
- 确认数据类型一致性:检查
CompanyDataProfile里的company_id是String还是Int,如果是Int,记得把userID转成Int再比较:guard let userIDInt = Int(userID) else { print("User ID is not a valid integer") return } let matchedCompanies = companyArray.filter { $0.company_id == userIDInt } - 添加调试日志:在过滤后打印
matchedCompanies.count,看看是否有匹配结果,方便快速定位问题 - 避免内存泄漏:闭包里使用
[weak self]并在主线程解包self,防止循环引用
内容的提问来源于stack exchange,提问作者Audrey Rozario
相关产品推荐
相关产品推荐

