ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“Œ UIImage ๋ฅผ Data ๋กœ ๋ณ€ํ™˜ํ•ด์„œ UserDefaults ์— ์ €์žฅํ•˜๋Š” ๊ฒƒ์€ ๋ถ€์ ํ•ฉํ•˜๋‹ค?

UIImage ๋ฅผ Data ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๊ฒƒ์— ์˜๋ฌธ์„ ๊ฐ€์ง„ ๊ฒŒ์‹œ๊ธ€์ด ์žˆ์—ˆ๋‹ค. ์ฐธ๊ณ ํ•ด๋ณด์ž.

How to Save an Image in User Defaults in Swift

๊ทธ ์ด์œ ๋Š” UserDefaults ๋ฅผ ์ด๋ฏธ์ง€ ๋ฐ์ดํ„ฐ์™€ ๊ฐ™์ด ๋Œ€๋Ÿ‰์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๋Š”๋ฐ ์‚ฌ์šฉํ•˜๊ธฐ์—๋Š” ๋ถ€์ ํ•ฉํ•˜๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

๊ทธ๋ฆฌ๊ณ  ๋‚˜๋Š” ์ด๋Ÿฌํ•œ ๋ฌธ์ œ๋ฅผ ๋ฐ”๋กœ ์ตœ๊ทผ์— ์ง๋ฉดํ–ˆ์—ˆ๋‹ค.

iOS) UserDefaults ์— image ์ €์žฅํ•˜๊ธฐ

๐Ÿ“Œ ๊ทธ๋ ‡๋‹ค๋ฉด?

์œ„์˜ ๊ธ€์—์„œ๋Š” ์ด๋ ‡๊ฒŒ ์ œ์•ˆํ•œ๋‹ค.

application's sandbox ์— ์ด๋ฏธ์ง€๋ฅผ ์ €์žฅํ•˜๊ณ  UserDefaults ์— ์ด๋ฏธ์ง€์˜ ์œ„์น˜๋ฅผ ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ์ฆ‰, FileManager ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ด๋ฏธ์ง€๋ฅผ ์ €์žฅํ•˜๊ณ  ๊ทธ ๊ฒฝ๋กœ๋ฅผ UserDefaults ์— ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

import UIKit

// Load Image
let image = UIImage(named: "image_name")

// Convert to Data
if let data = image?.pngData() {
    // Create URL
    let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let url = documents.appendingPathComponent("image_name.png")

    do {
        // Write to Disk
        try data.write(to: url)

        // Store URL in User Defaults
        UserDefaults.standard.set(url, forKey: "image")

    } catch {
        print("Unable to Write Data to Disk (\(error))")
    }
}
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
๋งํฌ
Total
Today
Yesterday