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

天气应用开发疑问:UIImage无法显示图标数组+无法获取5天预报日期

Troubleshooting Your Weather App Issues: Dates & Icon Display

Hey there! Let's break down the two problems you're hitting with your weather app—getting those 5-day forecast dates to show up and getting UIImage to display your weather icons correctly.

1. Why You're Not Getting 5-Day Dates

The OpenWeather 5-day forecast API returns data in 3-hour intervals (40 entries total for 5 days), so you can't just pull entries directly—you need to parse and group them by date first. Here's what's missing in your current code:

  • You're not accessing the dt timestamp field: Each entry in the list array has a dt key that holds a UNIX timestamp. You need to convert this to a Date object, then extract just the date portion (ignoring the time) to avoid duplicates.
  • No date deduplication: Since multiple entries belong to the same day, you need to track which dates you've already added to your array.

Here's a quick fix to add to your loop:

// Add these at the top of your parsing logic
var dateSet = Set<String>()
var dateArray = [String]()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd" // Adjust format to your needs

// Inside your for loop over mainArray
if let dict = dict as? [String: Any], let dt = dict["dt"] as? TimeInterval {
    let forecastDate = Date(timeIntervalSince1970: dt)
    let dayString = dateFormatter.string(from: forecastDate)
    
    if !dateSet.contains(dayString) {
        dateSet.insert(dayString)
        dateArray.append(dayString)
    }
}

This will give you a clean array of 5 unique dates for your forecast.

2. Why UIImage Isn't Showing Weather Icons

Most likely, you're either not fetching the icon correctly from the API or not loading it properly. Here's what to check:

  • You need the icon code from the weather array: Each list entry has a weather array (usually with one element) that contains the icon key (e.g., "01d" for clear daytime sky).
  • Correctly build the icon URL: OpenWeather hosts icons at https://openweathermap.org/img/wn/[iconCode]@2x.png—you need to construct this URL properly.
  • Always load images asynchronously: Trying to load network images on the main thread can cause delays or prevent them from showing up entirely.

Add this to your loop to fetch and display the icon:

// Inside your for loop over mainArray
if let dict = dict as? [String: Any], 
   let weatherArray = dict["weather"] as? [[String: Any]], 
   let weatherData = weatherArray.first, 
   let iconCode = weatherData["icon"] as? String {
    
    let iconUrlString = "https://openweathermap.org/img/wn/\(iconCode)@2x.png"
    guard let iconUrl = URL(string: iconUrlString) else { return }
    
    // Async load the image
    URLSession.shared.dataTask(with: iconUrl) { data, _, error in
        guard let data = data, error == nil else { 
            // Handle error (e.g., set a placeholder image)
            return 
        }
        DispatchQueue.main.async {
            let weatherIcon = UIImage(data: data)
            // Assign this image to your UIImageView here
            // Example: self.weatherIconImageView.image = weatherIcon
        }
    }.resume()
}

Also, double-check:

  • Your app has network permissions (HTTPS should work by default, but if you run into issues, verify your Info.plist settings).
  • If using local assets instead of network icons, make sure the asset names exactly match the icon codes from the API (they're case-sensitive!).

Hopefully these fixes get your dates and icons working as expected!

内容的提问来源于stack exchange,提问作者Rich J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:32:15