위 글은 유튜브 정대리님의 SwiftUI fundamental Tutorial 강좌를 보고 작성한 정리글로
자세한 내용은 유튜브를 통해 확인하시길 권장합니다.
211006 상세페이지 딥링크 수정 필요함.......
DeepLink란? 고유 URL(스키마) 주소로 앱을 열 수 있도록 함, 앱에 대한 고유의 URL을 정할 수 있음
초기 세팅 화면 만들어보기 (과제)
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView{
TabView{
List{
ForEach(1...20, id: \.self){ index in
NavigationLink(
destination: Text("details of \(index) "),
label: {
Text("TODO \(index)")
}
)
}
}
.tabItem {
Image(systemName: "list.dash")
Text("TODO")
}
.tag(0)
Rectangle()
.foregroundColor(.blue)
.frame(width: 100, height: 100)
.tabItem {
Image(systemName: "person.crop.circle")
Text("Profile")
}
.tag(1)
}.navigationTitle("TODO LIST")
}
}
}
아 너무 오랜만에 공부해서 이거 만드는데도 와리가리 함... (처음에 TabView에다가 NavigationView를 감 쌈;;) 정신 차리자...
DeepLink 만들기
나는 ContentView에서 탭이랑 리스트를 한꺼번에 처리했는데 강의에선 뷰를 각각 따로 나눠서 구현함
TodosView.swift
import Foundation
import SwiftUI
// 데이터 모델 만들기
struct TodoItem : Identifiable, Hashable {
var id : UUID
var title : String
}
// 데이터 더미 생성 함수
// TodoItem 데이터 배열 변환
func prepareData() -> [TodoItem]{
print("prepareData() called")
var newList = [TodoItem]()
for i in 0...20 {
let newTodo = TodoItem(id: UUID(), title: "TODO \(i)")
print("newTodo.id : \(newTodo.id) / title: \(newTodo.title)")
// 위에서 만든 빈 배열 (newList)를 append 해서 새로 만든 아이템을 붙여줌
newList.append(newTodo)
}
return newList
}
struct TodosView: View {
// State를 통해 데이터를 가지게 끔 함
@State var todoItems = [TodoItem]()
// 옵셔널로 처리
@State var activeUUID: UUID?
// 생성자 메소드
init() {
// todoItems에 prepareData를 통해 데이터가 들어감
_todoItems = State(initialValue: prepareData())
}
var body: some View{
NavigationView {
List(todoItems) { todoItem in
NavigationLink(
destination: Text("\(todoItem.title)"),
tag: todoItem.id,
//activeUUID 값이 변경되면 해당하는 링크로 이동
selection: $activeUUID,
label: {
Text("\(todoItem.title )")
})
}
.navigationTitle(Text("TODO LIST"))
.onOpenURL(perform: { url in
if case .todoItem(let id) = url.detailPage{
print("Over on ID: \(id)")
activeUUID = id
}
})
}
}
}
ProfileView
import Foundation
import SwiftUI
struct ProfileView: View{
var body: some View{
Rectangle()
.foregroundColor(.blue)
.frame(width: 100, height: 100)
.cornerRadius(15)
.overlay(
Text("Profile")
.font(.system(size: 23))
.fontWeight(.bold)
.foregroundColor(.white)
)
}
}
DeepLink.App.swiftui
import SwiftUI
@main
struct DeepLinkApp: App {
@State var selectedTab = TabIendtifier.todos
var body: some Scene {
WindowGroup {
TabView(selection: $selectedTab,
content: {
TodosView().tabItem {
VStack{
Image(systemName: "list.bullet")
Text("TODO")
}
}.tag(TabIendtifier.todos)
ProfileView().tabItem {
VStack{
Image(systemName: "person.circle.fill")
Text("Profile")
}
}.tag(TabIendtifier.profile)
})
.onOpenURL(perform: { url in
// 열려야 하는 url 처리
guard let tabId = url.tabIdentifier else { return }
selectedTab = tabId
})
}
}
}
struct DeepLink_Previews: PreviewProvider{
static var previews: some View{
Text("HELLO WORLD")
}
}
// 어떤 탭이 선택되었는지
enum TabIendtifier : Hashable{
case todos
case profile
}
// 어떤 페이지를 가져 와야 하는지
enum PageIdentifier : Hashable{
case todoItem(id: UUID)
}
// URL을 extension하여 확장
extension URL{
// deeplink-swiftui 스키마가 url로 들어왔다면 true로 반환
// info에서 추가한 딥링크가 들어왔는지 여부
var isDeeplink : Bool{
return scheme == "deeplink-swiftui"
}
// url 들어오는 것으로 어떤 타입의 탭을 보여줘야 하는지 가져오기
var tabIdentifier: TabIendtifier? {
guard isDeeplink else { return nil }
// deeplink-swiftui://[host]
switch host {
case "todos":
return .todos
case "profile":
return .profile
default:
return nil
}
}
var detailPage: PageIdentifier?{
// deeplink-swiftui://[host]/[pathComponents]/인 경우
// ["/", "id"] 형식으로 들어옴
print("pathComponents: \(pathComponents)")
guard let tabId = tabIdentifier, pathComponents.count > 1,
let uuid = UUID(uuidString: pathComponents[1])
else { return nil }
switch tabId {
case .todos:
return .todoItem(id: uuid)
default:
return nil
}
}
}
테스트할 때 UUID로 상세페이지 딥링크 타고 들어가는 것 까지 확인 했는데 포스팅용 영상 따려고 하니까 갑자기 상세페이지 딥링크로 안들어가지고 그냥 TODO 카테고리로만 들어가짐... 지금 두시간째 만지고 있는데 ㅜ 하 눙물만 한가득.... 나중에 다시 수정해야겠음
'강의 > etc' 카테고리의 다른 글
[SwiftUI fundamental Tutorial] LazyVGrid (0) | 2021.10.07 |
---|---|
[SwiftUI fundamental Tutorial] Menu (0) | 2021.10.07 |
[SwiftUI fundamental Tutorial] Picker, SegmentedStyle (0) | 2021.10.05 |
[SwiftUI fundamental Tutorial] Toast, Popup (0) | 2021.09.16 |
[SwiftUI fundamental Tutorial] TextField, SecureField (0) | 2021.09.14 |