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

如何使用Swift 4显示本地时区日落时间并替换Label文本

Hey there! Let's walk through how to grab the local timezone's sunset time and display it in a UILabel using Swift 4. Here's everything you need to know, step by step:

Step 1: Set Up CoreLocation

First, you'll need the CoreLocation framework—sunset time depends on geographic coordinates (not just timezone alone). Import it in your view controller, and don't forget to add permission descriptions to your Info.plist:

  • In your Info.plist, add the key NSLocationWhenInUseUsageDescription with a value like "We need your location to calculate local sunset time." This tells users why you're requesting location access.
Step 2: Implement the Location & Sunset Logic

Here's a complete view controller example that handles permissions, fetches the current location, calculates sunset time, and updates your label:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
    // Connect this outlet to your Text Label in Interface Builder
    @IBOutlet weak var sunsetTimeLabel: UILabel!
    private let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupLocationManager()
    }
    
    private func setupLocationManager() {
        locationManager.delegate = self
        // We don't need ultra-precise location for sunset calculations
        locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        // Request permission to access location while the app is in use
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
    
    // Triggered when we get a valid location update
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let currentLocation = locations.last else { return }
        // Stop updating location once we have what we need to save battery
        locationManager.stopUpdatingLocation()
        
        // Calculate and display the sunset time
        fetchAndDisplaySunsetTime(for: currentLocation)
    }
    
    // Handle changes to location permission status
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .authorizedWhenInUse, .authorizedAlways:
            locationManager.startUpdatingLocation()
        case .denied, .restricted:
            sunsetTimeLabel.text = "Location access denied — can't show sunset time"
        default:
            break
        }
    }
    
    // Handle location fetch errors
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        sunsetTimeLabel.text = "Failed to get location: \(error.localizedDescription)"
    }
    
    private func fetchAndDisplaySunsetTime(for location: CLLocation) {
        let currentDate = Date()
        let localTimeZone = TimeZone.current
        let calendar = Calendar.current
        
        // Calculate sunset time (iOS 10+ API)
        guard let sunsetDate = calendar.sunsetTime(for: location, date: currentDate, timeZone: localTimeZone) else {
            sunsetTimeLabel.text = "Couldn't calculate sunset time"
            return
        }
        
        // Format the time into a user-friendly string
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = localTimeZone
        // Use "HH:mm" for 24-hour format, or "h:mm a" for 12-hour with AM/PM
        dateFormatter.dateFormat = "h:mm a"
        let formattedSunset = dateFormatter.string(from: sunsetDate)
        
        // Update your label with the sunset time
        sunsetTimeLabel.text = "Today's Sunset: \(formattedSunset)"
    }
}
Step 3: Customize as Needed
  • If you need sunset time for a specific city (not the user's current location), create a fixed CLLocation with that city's coordinates:
    // Example: London coordinates
    let londonLocation = CLLocation(latitude: 51.5074, longitude: -0.1278)
    fetchAndDisplaySunsetTime(for: londonLocation)
    
  • Adjust the dateFormat in DateFormatter to match your preferred display style (e.g., "EEEE, MMM d, h:mm a" for full date + time).
Key Notes
  • The sunsetTime(for:date:timeZone:) API works on iOS 10 and later. If you need to support older versions, you'll have to implement manual sunset calculation logic (which is more complex).
  • Always handle permission denials gracefully so users understand why the feature isn't working.

内容的提问来源于stack exchange,提问作者Shahid Miah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:07:27