티스토리 뷰

공부합시다/Swift

[SwiftUI] imagePicker 사용기

신규_유저 2022. 11. 14. 23:50

사진 추가하기 시도해봄

 

1. ImagePicker.swift

import SwiftUI
import PhotosUI

@MainActor
class ImagePicker: ObservableObject {
    
    @Published var image: Image?
    @Published var images: [Image] = []
    
    @Published var imageSelection: PhotosPickerItem? {
        didSet {
            if let imageSelection {
                Task {
                    try await loadTransferable(from: imageSelection)
                }
            }
        }
    }
    
    @Published var imageSelections: [PhotosPickerItem] = [] {
        didSet {
            Task {
                if !imageSelections.isEmpty {
                    try await loadTransferable(from: imageSelections)
                    imageSelections = []
                }
            }
        }
    }
    
    func loadTransferable(from imageSelections: [PhotosPickerItem]) async throws {
        do {
            for imageSelection in imageSelections {
                if let data = try await imageSelection.loadTransferable(type: Data.self) {
                    if let uiImage = UIImage(data: data) {
                        self.images.append(Image(uiImage: uiImage))
                    }
                }
            }
        } catch {
            print(error.localizedDescription)
        }
    }
    
    func loadTransferable(from imageSelection: PhotosPickerItem?) async throws {
//        print(Image.transferRepresentation)
        do {
            if let data = try await imageSelection?.loadTransferable(type: Data.self) {
                if let uiImage = UIImage(data: data) {
                    self.image = Image(uiImage: uiImage)
                }
            }
        } catch {
            print(error.localizedDescription)
            image = nil
        }
    }
}

 

2. View에 기능 추가

import SwiftUI
import PhotosUI

struct ImagePickerView: View {
    @StateObject var imagePicker = ImagePicker()
 
... 생략 ...

HStack {
	if let image = imagePicker.image {
    		image
            .resizable()
            .frame(width: 100, height: 100)
            .scaledToFit()
            .clipShape(RoundedRectangle(cornerRadius: 8))
    }
    Button(action: {}) {
		PhotosPicker(selection: $imagePicker.imageSelection,
            matching: .images,
            photoLibrary: .shared()) {
                Image(systemName: "plus.circle.fill")
                    .resizable()
                    .frame(width: 30, height: 30)
                    .tint(.primaryRed)
                }
        	}
            .frame(width: 100, height: 100)
            .background(
            	RoundedRectangle(cornerRadius: 8)
            	.fill(Color.navGray)
            )
    }
... 생략 ...

 

사진 선택해봄

 

참고 링크

반응형
LIST
댓글
링크
공지사항
최근에 올라온 글