iOS 判断经纬度是否合法, Thread 1: Exception: "Invalid Region... <center: xx,xx span

//报错: Thread 1: Exception: "Invalid Region... <center: xx,xx span

//解决办法: latitude在[-90, 90]之间,  longitude在[-180, 180]之间
//地图设置中心
    func mapViewSetRegion(_ currentLocation: CLLocation) {
        let coordinate2D = CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
        let region = MKCoordinateRegion(center: coordinate2D, span: MKCoordinateSpan(latitudeDelta: 0.004, longitudeDelta: 0.004))
        if ( (region.center.latitude >= -90) && (region.center.latitude <= 90) && (region.center.longitude >= -180) && (region.center.longitude <= 180) ){
            mapView.setRegion(region, animated: true)
        }
    }


extension UIViewController {
    
    func regexLongitude(_ longitude: CLLocationDegrees ) -> Bool {
        return String(longitude.constraintPriorityTargetValue).match(pattern: "^-?((0|1?[0-8]?[0-9]?)(([.][0-9]{1,10})?)|180(([.][0]{1,10})?))$")
    }
    
    func regexLatitude(_ longitude: CLLocationDegrees ) -> Bool {
        return String(longitude.constraintPriorityTargetValue).match(pattern: "^-?((0|[1-8]?[0-9]?)(([.][0-9]{1,10})?)|90(([.][0]{1,10})?))$")
    }

}

extension CLLocationDegrees {
    
    var tudeSting: String {
        return String(self.constraintPriorityTargetValue)
    }

    var isLongitude: Bool {
        return self.tudeSting.match(pattern: "^-?((0|1?[0-8]?[0-9]?)(([.][0-9]{1,10})?)|180(([.][0]{1,10})?))$")
    }
    
    var isLatitude: Bool {
        return self.tudeSting.match(pattern: "^-?((0|1?[0-8]?[0-9]?)(([.][0-9]{1,10})?)|180(([.][0]{1,10})?))$")
    }

}

extension String {
    
    func regexLongitude() -> Bool {
        return self.match(pattern: "^-?((0|1?[0-8]?[0-9]?)(([.][0-9]{1,10})?)|180(([.][0]{1,10})?))$")
    }
    
    func regexLatitude() -> Bool {
        return self.match(pattern: "^-?((0|[1-8]?[0-9]?)(([.][0-9]{1,10})?)|90(([.][0]{1,10})?))$")
    }

    func match(pattern: String) -> Bool {
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
            return false
        }
        let resutlts = regex.matches(in: self, options: [], range: NSMakeRange(0, self.count))
        return resutlts.count > 0
    }

}

推荐阅读更多精彩内容