PhotosPicker를 이용해서 사용자로부터 사진을 입력받을 수 있다.
struct ContentView: View {
@State private var pickerItem: PhotosPickerItem?
@State private var selectedImage: Image?
var body: some View {
VStack {
PhotosPicker("Select a photo", selection: $pickerItem, matching: .images)
selectedImage?
.resizable()
.scaledToFit()
}
.onChange(of: pickerItem) {
Task {
selectedImage = try await pickerItem?.loadTransferable(type: Image.self)
}
}
}
}
혹은 다음처럼 배열로 설정해서 복수의 이미지를 입력받을 수도 있다.
struct ContentView: View {
@State private var pickerItems = [PhotosPickerItem]()
@State private var selectedImages = [Image]()
var body: some View {
VStack {
PhotosPicker("Select a photo", selection: $pickerItems, matching: .images)
ScrollView {
ForEach(0..<selectedImages.count, id: \.self) { index in
selectedImages[index]
.resizable()
.scaledToFit()
}
} }
.onChange(of: pickerItems) {
Task {
for item in pickerItems {
if let loadedImage = try await item.loadTransferable(type: Image.self) {
selectedImages.append(loadedImage)
}
}
}
}
}
}
아래 코드처럼 최대 선택 개수, 허용 사진 형태, label 등을 설정할 수 있다.
PhotosPicker(selection: $pickerItems, maxSelectionCount: 2, matching: .any(of: [.images, .not(.screenRecordings)])) {
VStack {
Image(systemName: "photo.fill")
Text("Select two images")
}
}
ShareLink를 통해 앱 내에서 다른 앱으로 공유를 할 수 있도록 설정할 수 있다.
![]() | ![]() |
---|
라벨은 간단히 텍스트로 설정할 수도 있고 다른 view로 설정할 수도 있다.
struct ContentView: View {
var body: some View {
ShareLink(item: URL(string: "https://www.youtube.com/watch?v=ZsCfVcBFlt4&list=PL-v5Ft0MHPi0kO89KThPO7yMu5eFr9qVJ&index=6")!, subject: Text("This is a great song."), message: Text("Do you want to try this?")) {
VStack {
Image(systemName: "music.note")
.font(.title)
Text("Share \"I've always get this way\"")
}
}
}
}
텍스트말고도 복잡한 데이터를 공유할 수 있도록 설정할 수 있는데, 이때 preview를 제공하는 것이 중요하다. 사진처럼 그 자체가 preview인 데이터에도 preview가 필요하다. 데이터와 preview를 중복으로 나타내지 않고 로컬 상수를 활용해서 간결하게 이용할 수 있다.
struct ContentView: View {
let cat = Image(.cat)
var body: some View {
ShareLink(item: cat, preview: SharePreview("cat image", image: cat)) {
Label("Click to share", systemImage: "cat.fill")
}
}
}
environment key 중 하나인 requestReview로 사용자가 앱스토어의 앱에 리뷰를 남길 수 있게 권유할 수 있다.
struct ContentView: View {
@Environment(\.requestReview) var requestReview
var body: some View {
Button("Leave your review") {
requestReview()
}
}
}
💡 다만 직접적으로 리뷰를 권유하는 것보다 사용자가 앱의 기능을 활용해보고 적절히 피드백을 줄 수 있도록 그 과정에 제공되는 것이 효과적이고 이상적이다.