You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中CoreLocation遇kCLErrorDomain Code=1错误的解决方案咨询

解决CoreLocation错误Error Domain=kCLErrorDomain Code=1 "(null)"

错误原因解析

kCLErrorDomain Code=1对应CLError.denied,本质是用户拒绝了位置访问权限,或是App未在Info.plist中配置必要的权限描述文本,导致系统直接拦截位置请求。

排查与修复方案

1. 补充Info.plist权限配置

CoreLocation强制要求在Info.plist中添加权限说明,否则权限请求会被系统驳回。根据你使用的requestWhenInUseAuthorization(),必须添加以下键:

  • NSLocationWhenInUseUsageDescription:填写App需要位置权限的原因(例如"获取你的位置以展示当地实时天气")

若后续需要后台定位能力,还需补充NSLocationAlwaysAndWhenInUseUsageDescription(适配iOS 11+)和NSLocationUsageDescription(适配旧系统)。

添加方式:在Info.plist右键选择「Add Row」,输入上述键名后填写对应描述文本。

2. 新增权限状态回调处理

你的代码缺少对权限请求结果的监听,需在CLLocationManagerDelegate中实现didChangeAuthorization方法,根据权限状态执行对应逻辑:

extension WeatherViewController:CLLocationManagerDelegate{
    // 添加权限状态变化回调
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .authorizedWhenInUse, .authorizedAlways:
            manager.requestLocation() // 权限通过后再发起位置请求
        case .denied, .restricted:
            // 提示用户前往设置开启权限
            let alert = UIAlertController(title: "位置权限被拒绝", message: "请在设置中开启位置权限以获取当地天气", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "去设置", style: .default, handler: { _ in
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
            }))
            alert.addAction(UIAlertAction(title: "取消", style: .cancel))
            present(alert, animated: true)
        case .notDetermined:
            manager.requestWhenInUseAuthorization() // 未授权时再次发起权限请求
        @unknown default:
            break
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            let lat = location.coordinate.latitude
            let lon = location.coordinate.longitude
            print(lat)
            print(lon)
            weathermanager.fetchWeather(latitute: lat, longitute: lon)
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
}

3. 调整viewDidLoad中的逻辑

原代码在请求权限后立即调用requestLocation(),但此时用户尚未确认权限,需移除该行代码,交由didChangeAuthorization回调处理位置请求:

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    // 仅发起权限请求,不直接调用位置获取
    locationManager.requestWhenInUseAuthorization()

    weathermanager.delegate = self
    searchTextField.delegate = self
}

用户提供的原始代码

import UIKit
import CoreLocation

class WeatherViewController: UIViewController {
    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var TempratureLabel: UILabel!
    @IBOutlet weak var CityLabel: UILabel!
    
    var locationManager = CLLocationManager()
    var weathermanager = WeatherManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()

        weathermanager.delegate = self
        searchTextField.delegate = self
    }
}

// MARK: - UITextFieldDelegate
extension WeatherViewController:UITextFieldDelegate{
    @IBAction func searchButtonPressed(_ sender: UIButton) {
        searchTextField.endEditing(true)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        searchTextField.endEditing(true)
        return true
    }
    
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if textField.text != "" {
            return true
        }else{
            textField.placeholder = "Write Valid Location"
            return false
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if let cityname = textField.text {
            weathermanager.fetchWeather(cityname: cityname)
        }else{
            print("invalid city name typed")
        }
        searchTextField.text = ""
    }
}

// MARK: - WeatherManagerDelegate
extension WeatherViewController:WeatherManagerDelegate {
    func didupdateWeather(weather:WeatherModel){
        DispatchQueue.main.async {
            self.TempratureLabel.text = weather.tempratureString
            self.CityLabel.text = weather.cityname
            self.conditionImageView.image = UIImage(systemName: weather.conditionName)
        }
    }
}

extension WeatherViewController:CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            let lat = location.coordinate.latitude
            let lon = location.coordinate.longitude
            print(lat)
            print(lon)
            weathermanager.fetchWeather( latitute:lat, longitute:lon)
        }
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {
        print(error)
    }
}

内容的提问来源于stack exchange,提问作者Kundan ios

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 14:03:14