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

Swift中UIImage与String互转及用户信息存储传输问题咨询

Hey there! Let's tackle your two Swift development questions one by one, using the code snippets you provided as a starting point.

1. UIImage ↔ String (Base64) Conversion

Since your code already uses Base64 encoding for the image, we'll focus on robust, modern Swift implementations for both directions:

UIImage to Base64 String

Convert your image to raw data first, then encode it to a Base64 string. We'll handle optional values to avoid crashes:

// Convert UIImage to a Base64-encoded String
func imageToBase64(_ image: UIImage) -> String? {
    // Use jpegData for smaller file sizes, or pngData for lossless quality
    guard let imageData = image.jpegData(compressionQuality: 1.0) else {
        print("Failed to convert image to data")
        return nil
    }
    return imageData.base64EncodedString()
}

Pro tip: Adjust the compressionQuality parameter (0.0 to 1.0) to balance image quality and file size for your use case.

Base64 String to UIImage

Reverse the process by decoding the Base64 string back to data, then converting it to a UIImage:

// Convert a Base64-encoded String back to UIImage
func base64ToImage(_ base64String: String) -> UIImage? {
    guard let imageData = Data(base64Encoded: base64String) else {
        print("Invalid Base64 string")
        return nil
    }
    return UIImage(data: imageData)
}
2. Storing User Info in UserDefaults, Sending to Server, and Retrieving in Another ViewController

Let's fix and expand your existing code to make it safe, maintainable, and complete:

Step 1: Fix the UserDefaults Saving Logic

Your original code had optional type gaps—here's a polished version that handles nil values properly:

@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var profileUserPhotoImage: UIImageView!

func saveUserInfoToDefaults() {
    // Guard against empty name or missing image
    guard let userName = userNameLabel.text, !userName.isEmpty,
          let profileImage = profileUserPhotoImage.image else {
        print("Error: Missing user name or profile image")
        return
    }
    
    // Convert image to Base64
    guard let base64Image = imageToBase64(profileImage) else { return }
    
    // Create user dictionary
    let userDict: [String: String] = ["name": userName, "image": base64Image]
    
    // Retrieve existing array (or initialize empty if none exists)
    var userArray = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]] ?? []
    
    // Add new user and save back to UserDefaults
    userArray.append(userDict)
    UserDefaults.standard.set(userArray, forKey: "userInfo")
    UserDefaults.standard.synchronize() // Ensures immediate save (optional but safe)
}

Step 2: Send the User Array to a Website

Use URLSession to send the UserDefaults array as JSON to your server:

func sendUserArrayToServer() {
    guard let userArray = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]],
          !userArray.isEmpty else {
        print("No user data to send")
        return
    }
    
    // Convert array to JSON data
    guard let jsonData = try? JSONSerialization.data(withJSONObject: userArray, options: []) else {
        print("Failed to convert user array to JSON")
        return
    }
    
    // Replace with your actual server endpoint
    guard let url = URL(string: "https://your-server-url.com/api/users") else {
        print("Invalid server URL")
        return
    }
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData
    
    // Execute the network request
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print("Network error: \(error.localizedDescription)")
            return
        }
        
        // Check for successful response
        if let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) {
            print("User data sent successfully!")
            // Optional: Parse server response if needed
            if let data = data, let responseJSON = try? JSONSerialization.jsonObject(with: data) {
                print("Server response: \(responseJSON)")
            }
        } else {
            print("Server error: Invalid response code")
        }
    }
    task.resume()
}

Step 3: Retrieve the User Array in Another ViewController

Fetch the saved data and convert it back to usable values in your target view controller:

override func viewDidLoad() {
    super.viewDidLoad()
    loadUserInfoFromDefaults()
}

func loadUserInfoFromDefaults() {
    guard let userArray = UserDefaults.standard.array(forKey: "userInfo") as? [[String: String]],
          !userArray.isEmpty else {
        print("No user data found in UserDefaults")
        return
    }
    
    // Loop through users to use their data (e.g., populate a table view)
    for user in userArray {
        if let name = user["name"], let base64Image = user["image"] {
            if let image = base64ToImage(base64Image) {
                // Use name and image here (e.g., add to a data source)
                print("Loaded user: \(name)")
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:29:48