天气应用开发疑问:UIImage无法显示图标数组+无法获取5天预报日期
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
dttimestamp field: Each entry in thelistarray has adtkey that holds a UNIX timestamp. You need to convert this to aDateobject, 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
iconcode from theweatherarray: Eachlistentry has aweatherarray (usually with one element) that contains theiconkey (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.plistsettings). - If using local assets instead of network icons, make sure the asset names exactly match the
iconcodes from the API (they're case-sensitive!).
Hopefully these fixes get your dates and icons working as expected!
内容的提问来源于stack exchange,提问作者Rich J

