From ba88b2ffa3af0dd71bb01d5a57eb43def3528039 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Tue, 29 Aug 2023 15:43:02 +0900 Subject: [PATCH 01/42] =?UTF-8?q?=ED=83=AD=20=EB=B0=94=20=EC=97=B0?= =?UTF-8?q?=EA=B2=B0=20=EC=88=98=EC=A0=95=20=EB=B0=8F=20View=EC=9D=98=20?= =?UTF-8?q?=EB=B0=B0=EA=B2=BD=EC=83=89=EC=83=81=20=EC=84=A4=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp/Controllers/DetailDiaryViewController.swift | 1 + DiaryApp/Controllers/DiaryCalenderViewController.swift | 1 + DiaryApp/Controllers/DiaryListViewController.swift | 1 + DiaryApp/Controllers/DiaryProgressViewController.swift | 1 + DiaryApp/Controllers/EditDiaryViewController.swift | 1 + DiaryApp/Controllers/HomeViewController.swift | 1 + DiaryApp/Controllers/NewDiaryViewController.swift | 1 + DiaryApp/Controllers/ProfileViewController.swift | 1 + DiaryApp/Controllers/ProgressListViewController.swift | 1 + DiaryApp/Resources/SceneDelegate.swift | 2 +- 10 files changed, 10 insertions(+), 1 deletion(-) diff --git a/DiaryApp/Controllers/DetailDiaryViewController.swift b/DiaryApp/Controllers/DetailDiaryViewController.swift index 860de8f..ef0f52f 100644 --- a/DiaryApp/Controllers/DetailDiaryViewController.swift +++ b/DiaryApp/Controllers/DetailDiaryViewController.swift @@ -10,5 +10,6 @@ import UIKit class DetailDiaryViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .systemBackground } } diff --git a/DiaryApp/Controllers/DiaryCalenderViewController.swift b/DiaryApp/Controllers/DiaryCalenderViewController.swift index f7a70a2..41e69b3 100644 --- a/DiaryApp/Controllers/DiaryCalenderViewController.swift +++ b/DiaryApp/Controllers/DiaryCalenderViewController.swift @@ -10,5 +10,6 @@ import UIKit class DiaryCalenderViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .systemBackground } } diff --git a/DiaryApp/Controllers/DiaryListViewController.swift b/DiaryApp/Controllers/DiaryListViewController.swift index ab85548..6dc2824 100644 --- a/DiaryApp/Controllers/DiaryListViewController.swift +++ b/DiaryApp/Controllers/DiaryListViewController.swift @@ -10,5 +10,6 @@ import UIKit class DiaryListViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .systemBackground } } diff --git a/DiaryApp/Controllers/DiaryProgressViewController.swift b/DiaryApp/Controllers/DiaryProgressViewController.swift index c52ed74..d9d7542 100644 --- a/DiaryApp/Controllers/DiaryProgressViewController.swift +++ b/DiaryApp/Controllers/DiaryProgressViewController.swift @@ -10,5 +10,6 @@ import UIKit class DiaryProgressViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .systemBackground } } diff --git a/DiaryApp/Controllers/EditDiaryViewController.swift b/DiaryApp/Controllers/EditDiaryViewController.swift index 119f0bc..1378a6a 100644 --- a/DiaryApp/Controllers/EditDiaryViewController.swift +++ b/DiaryApp/Controllers/EditDiaryViewController.swift @@ -10,5 +10,6 @@ import UIKit class EditDiaryViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .systemBackground } } diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index 06a56c7..87a4139 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -10,5 +10,6 @@ import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .systemBackground } } diff --git a/DiaryApp/Controllers/NewDiaryViewController.swift b/DiaryApp/Controllers/NewDiaryViewController.swift index a22f69d..d0092ba 100644 --- a/DiaryApp/Controllers/NewDiaryViewController.swift +++ b/DiaryApp/Controllers/NewDiaryViewController.swift @@ -10,5 +10,6 @@ import UIKit class NewDiaryViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .systemBackground } } diff --git a/DiaryApp/Controllers/ProfileViewController.swift b/DiaryApp/Controllers/ProfileViewController.swift index 103969e..1add78a 100644 --- a/DiaryApp/Controllers/ProfileViewController.swift +++ b/DiaryApp/Controllers/ProfileViewController.swift @@ -10,5 +10,6 @@ import UIKit class ProfileViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .systemBackground } } diff --git a/DiaryApp/Controllers/ProgressListViewController.swift b/DiaryApp/Controllers/ProgressListViewController.swift index dec3de7..0e1653a 100644 --- a/DiaryApp/Controllers/ProgressListViewController.swift +++ b/DiaryApp/Controllers/ProgressListViewController.swift @@ -10,5 +10,6 @@ import UIKit class ProgressListViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .systemBackground } } diff --git a/DiaryApp/Resources/SceneDelegate.swift b/DiaryApp/Resources/SceneDelegate.swift index a775bd1..5b21290 100644 --- a/DiaryApp/Resources/SceneDelegate.swift +++ b/DiaryApp/Resources/SceneDelegate.swift @@ -20,7 +20,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { let tabs: [(root: UIViewController, icon: String)] = [ (HomeViewController(), "house"), (DiaryListViewController(), "list.bullet"), - (DiaryCalenderViewController(), "plus.square"), + (NewDiaryViewController(), "plus.square"), (DiaryProgressViewController(), "tag.fill"), (ProfileViewController(), "person.fill"), ] From 82002248375902d6b60fbd7362eb801f96b3ad2e Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Tue, 29 Aug 2023 16:08:40 +0900 Subject: [PATCH 02/42] =?UTF-8?q?Git=20Convention=20=20=EB=82=B4=EC=9A=A9?= =?UTF-8?q?=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4e6a088..d2f8682 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,17 @@ - develop : 개발용 default 브랜치로, 이 브랜치를 기준으로 feature 브랜치를 따고, 각 feature를 합치는 브랜치 - feature: 단위 기능 개발용 브랜치 -> feature/작업할페이지컨트롤러명 -### 참고 -1. 커밋은 기능 단위로!! -> 한 번에 모아서 올리면, 무슨 기능인지 분간이 안됨. -2. 맡은 작업 페이지 외에 다른 작업은 건드리지 말 것!! +### Git Conventions +Commit Message는 아래와 같은 규칙을 따릅니다. +- [FEAT]: 새로운 기능을 추가 +[FIX]: 잔잔바리 수정 +- [DESIGN]: UI 디자인 변경 +- [STYLE]: 코드 포맷 변경, 세미 콜론 누락, 코드 수정이 없는 경우 +- [DOCS]: 문서 수정, 필요한 주석 추가 및 변경 +- [RENAME]: 파일 혹은 폴더명을 수정하거나 옮기는 작업만인 경우 +- [REMOVE]: 파일을 삭제하는 작업만 수행한 경우 +- [MERGE] : 병합 +- [CONFLICT]: 병합 시 충돌 해결 +- [COMPLETION]: 작업을 완료하고 마지막 커밋을 작성하는 경우 +Pull Requests는 Commit Message와 동일하게 써서 올립니다. From f716405a945541e75f1ebc2ddd47cfdd46d5e3b0 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Tue, 29 Aug 2023 19:30:55 +0900 Subject: [PATCH 03/42] =?UTF-8?q?[FEAT]:=20feature/DiaryList-Page=20?= =?UTF-8?q?=EB=B8=8C=EB=9E=9C=EC=B9=98=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp/Controllers/DiaryListViewController.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/DiaryApp/Controllers/DiaryListViewController.swift b/DiaryApp/Controllers/DiaryListViewController.swift index 6dc2824..7abe9f3 100644 --- a/DiaryApp/Controllers/DiaryListViewController.swift +++ b/DiaryApp/Controllers/DiaryListViewController.swift @@ -13,3 +13,4 @@ class DiaryListViewController: UIViewController { view.backgroundColor = .systemBackground } } + From 6e8bbbc97374ce41b31e58445e2e3bf85256174a Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Tue, 29 Aug 2023 19:39:07 +0900 Subject: [PATCH 04/42] =?UTF-8?q?[FEAT]:=20=20feature/home-Page=20?= =?UTF-8?q?=EB=B8=8C=EB=9F=B0=EC=B9=98=20=EB=B3=91=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 12 +++ DiaryApp/Controllers/HomeViewController.swift | 93 +++++++++++++++++++ DiaryApp/Resources/SceneDelegate.swift | 2 +- DiaryApp/Views/CustomCollectionView.swift | 20 ++++ DiaryApp/Views/CustomImageView.swift | 21 +++++ DiaryApp/Views/HomeFeedCell.swift | 45 +++++++++ 6 files changed, 192 insertions(+), 1 deletion(-) create mode 100644 DiaryApp/Views/CustomCollectionView.swift create mode 100644 DiaryApp/Views/CustomImageView.swift create mode 100644 DiaryApp/Views/HomeFeedCell.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 1631a8b..63f0209 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -23,6 +23,9 @@ 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B52A9CAA16003052D3 /* ProfileViewController.swift */; }; 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B72A9CAD27003052D3 /* User.swift */; }; 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B92A9CAD60003052D3 /* Weather.swift */; }; + 4E98A3BD2A9CB918003052D3 /* CustomCollectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */; }; + 4E98A3BF2A9CBA1B003052D3 /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */; }; + 4E98A3C12A9CCFB8003052D3 /* CustomImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -44,6 +47,9 @@ 4E98A3B52A9CAA16003052D3 /* ProfileViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileViewController.swift; sourceTree = ""; }; 4E98A3B72A9CAD27003052D3 /* User.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; 4E98A3B92A9CAD60003052D3 /* Weather.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Weather.swift; sourceTree = ""; }; + 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomCollectionView.swift; sourceTree = ""; }; + 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeFeedCell.swift; sourceTree = ""; }; + 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomImageView.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -115,6 +121,9 @@ isa = PBXGroup; children = ( 4E98A3992A9CA57E003052D3 /* LaunchScreen.storyboard */, + 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */, + 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, + 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, ); path = Views; sourceTree = ""; @@ -199,6 +208,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 4E98A3BD2A9CB918003052D3 /* CustomCollectionView.swift in Sources */, 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */, 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */, 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */, @@ -208,10 +218,12 @@ 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, + 4E98A3BF2A9CBA1B003052D3 /* HomeFeedCell.swift in Sources */, 4E98A3AE2A9CA748003052D3 /* DetailDiaryViewController.swift in Sources */, 4E98A3AC2A9CA70B003052D3 /* DiaryListViewController.swift in Sources */, 4E98A3B02A9CA762003052D3 /* DiaryProgressViewController.swift in Sources */, 4E98A3A62A9CA6A6003052D3 /* NewDiaryViewController.swift in Sources */, + 4E98A3C12A9CCFB8003052D3 /* CustomImageView.swift in Sources */, 4E98A3AA2A9CA6F6003052D3 /* ProgressListViewController.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index 87a4139..3d2b6e2 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -7,9 +7,102 @@ import UIKit +private enum Const { + static let itemSize = CGSize(width: 300, height: 550) + static let itemSpacing = 46.0 + + static var insetX: CGFloat { + (UIScreen.main.bounds.width - Self.itemSize.width) / 2.0 + } + + static var collectionViewContentInset: UIEdgeInsets { + UIEdgeInsets(top: 40, left: Self.insetX, bottom: 10, right: Self.insetX) + } +} + class HomeViewController: UIViewController { + private let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) + override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground + configureCollectionView() + configureLayout() + addSearchBar() + } + + private let collectionViewFlowLayout: UICollectionViewFlowLayout = { + let layout = UICollectionViewFlowLayout() + layout.scrollDirection = .horizontal + layout.itemSize = Const.itemSize + layout.minimumLineSpacing = Const.itemSpacing + layout.minimumInteritemSpacing = 0 + return layout + }() + + private func configureCollectionView() { + collectionView.register(HomeFeedCell.self, forCellWithReuseIdentifier: HomeFeedCell.identifier) + collectionView.delegate = self + collectionView.dataSource = self + + collectionView.isScrollEnabled = true + collectionView.showsHorizontalScrollIndicator = false + collectionView.showsVerticalScrollIndicator = true + collectionView.backgroundColor = .clear + collectionView.clipsToBounds = true + collectionView.register(HomeFeedCell.self, forCellWithReuseIdentifier: HomeFeedCell.identifier) + collectionView.isPagingEnabled = false + collectionView.contentInsetAdjustmentBehavior = .never + collectionView.contentInset = Const.collectionViewContentInset + collectionView.decelerationRate = .fast + + collectionView.collectionViewLayout = collectionViewFlowLayout + } + + private func configureLayout() { + view.addSubview(collectionView) + + NSLayoutConstraint.activate([ + collectionView.topAnchor.constraint(equalTo: view.topAnchor), + collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), + collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), + collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + } + + private func addSearchBar() { + let searchController = UISearchController(searchResultsController: nil) + searchController.hidesNavigationBarDuringPresentation = false + searchController.searchBar.placeholder = "Search" + searchController.navigationItem.hidesSearchBarWhenScrolling = true + navigationItem.searchController = searchController + } +} + +extension HomeViewController: UICollectionViewDataSource { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return 3 + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeFeedCell.identifier, for: indexPath) as? HomeFeedCell else { return UICollectionViewCell() } + cell.backgroundColor = .systemOrange + cell.layer.cornerRadius = 20 + return cell + } +} + +extension HomeViewController: UICollectionViewDelegate {} + +extension HomeViewController: UICollectionViewDelegateFlowLayout { + func scrollViewWillEndDragging( + _ scrollView: UIScrollView, + withVelocity velocity: CGPoint, + targetContentOffset: UnsafeMutablePointer + ) { + let scrolledOffsetX = targetContentOffset.pointee.x + scrollView.contentInset.left + let cellWidth = Const.itemSize.width + Const.itemSpacing + let index = round(scrolledOffsetX / cellWidth) + targetContentOffset.pointee = CGPoint(x: index * cellWidth - scrollView.contentInset.left, y: scrollView.contentInset.top) } } diff --git a/DiaryApp/Resources/SceneDelegate.swift b/DiaryApp/Resources/SceneDelegate.swift index 5b21290..e0f906e 100644 --- a/DiaryApp/Resources/SceneDelegate.swift +++ b/DiaryApp/Resources/SceneDelegate.swift @@ -24,7 +24,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { (DiaryProgressViewController(), "tag.fill"), (ProfileViewController(), "person.fill"), ] - + tabBarController.setViewControllers(tabs.map { root, icon in let navigationController = UINavigationController(rootViewController: root) let tabBarItem = UITabBarItem(title: nil, image: .init(systemName: icon), selectedImage: .init(systemName: "\(icon).fill")) diff --git a/DiaryApp/Views/CustomCollectionView.swift b/DiaryApp/Views/CustomCollectionView.swift new file mode 100644 index 0000000..b74407e --- /dev/null +++ b/DiaryApp/Views/CustomCollectionView.swift @@ -0,0 +1,20 @@ +// +// CustomCollectionView.swift +// CollectionWithoutSB +// +// Created by (^ㅗ^)7 iMac on 2023/08/23. +// + +import UIKit + +final class CustomCollectionView: UICollectionView { + override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { + super.init(frame: frame, collectionViewLayout: layout) + self.translatesAutoresizingMaskIntoConstraints = false + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/DiaryApp/Views/CustomImageView.swift b/DiaryApp/Views/CustomImageView.swift new file mode 100644 index 0000000..6a0f6c3 --- /dev/null +++ b/DiaryApp/Views/CustomImageView.swift @@ -0,0 +1,21 @@ +// +// CustomImageView.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/28. +// + +import UIKit + +final class CustomImageView: UIImageView { + override init(frame: CGRect) { + super.init(frame: frame) + self.image = nil + self.translatesAutoresizingMaskIntoConstraints = false + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/DiaryApp/Views/HomeFeedCell.swift b/DiaryApp/Views/HomeFeedCell.swift new file mode 100644 index 0000000..0b2bdc4 --- /dev/null +++ b/DiaryApp/Views/HomeFeedCell.swift @@ -0,0 +1,45 @@ +// +// HomeFeedCell.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/28. +// + +import UIKit + +final class HomeFeedCell: UICollectionViewCell { + static let identifier = "HomeFeedCell" + + private let myView = CustomImageView(frame: .zero) + private let weatherImage = CustomImageView(frame: .zero) + + let sizeWidth = 70.0 + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override init(frame: CGRect) { + super.init(frame: frame) + + self.contentView.addSubview(self.myView) + + self.weatherImage.backgroundColor = .systemBlue + self.weatherImage.layer.cornerRadius = CGFloat(self.sizeWidth / 2) + + self.myView.addSubview(self.weatherImage) + + NSLayoutConstraint.activate([ + self.myView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor), + self.myView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor), + self.myView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), + self.myView.topAnchor.constraint(equalTo: self.contentView.topAnchor), + + self.weatherImage.trailingAnchor.constraint(equalTo: self.myView.trailingAnchor, constant: -30), + self.weatherImage.bottomAnchor.constraint(equalTo: self.myView.bottomAnchor, constant: -30), + self.weatherImage.heightAnchor.constraint(equalToConstant: self.sizeWidth), + self.weatherImage.widthAnchor.constraint(equalToConstant: self.sizeWidth), + ]) + } +} From 86bb7de352828c35587fe180226c6e13af10711f Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Tue, 29 Aug 2023 20:14:13 +0900 Subject: [PATCH 05/42] =?UTF-8?q?[STYLE]:=20=EC=BD=9C=EB=A0=89=EC=85=98?= =?UTF-8?q?=EB=B7=B0=20=EB=A0=88=EC=9D=B4=EC=95=84=EC=9B=83=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 4 + .../Controllers/DiaryListViewController.swift | 75 +++++++++++++++++++ DiaryApp/Controllers/HomeViewController.swift | 8 +- DiaryApp/Views/DiaryListCell.swift | 20 +++++ 4 files changed, 103 insertions(+), 4 deletions(-) create mode 100644 DiaryApp/Views/DiaryListCell.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 63f0209..da88814 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550832A9E049100C8A500 /* DiaryListCell.swift */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -29,6 +30,7 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 4E1550832A9E049100C8A500 /* DiaryListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListCell.swift; sourceTree = ""; }; 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiaryApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; @@ -122,6 +124,7 @@ children = ( 4E98A3992A9CA57E003052D3 /* LaunchScreen.storyboard */, 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */, + 4E1550832A9E049100C8A500 /* DiaryListCell.swift */, 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, ); @@ -215,6 +218,7 @@ 4E98A3A32A9CA634003052D3 /* HomeViewController.swift in Sources */, 4E98A3B22A9CA781003052D3 /* DiaryCalenderViewController.swift in Sources */, 4E98A3A82A9CA6B6003052D3 /* EditDiaryViewController.swift in Sources */, + 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */, 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, diff --git a/DiaryApp/Controllers/DiaryListViewController.swift b/DiaryApp/Controllers/DiaryListViewController.swift index 7abe9f3..7a7d613 100644 --- a/DiaryApp/Controllers/DiaryListViewController.swift +++ b/DiaryApp/Controllers/DiaryListViewController.swift @@ -8,9 +8,84 @@ import UIKit class DiaryListViewController: UIViewController { + private let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) + override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground + configureCollectionView() + configureLayout() + } + + private let collectionViewFlowLayout: UICollectionViewFlowLayout = { + let layout = UICollectionViewFlowLayout() + layout.scrollDirection = .vertical + layout.itemSize = Const.itemSize + layout.minimumLineSpacing = Const.itemSpacing + layout.minimumInteritemSpacing = 0 + return layout + }() + + private func configureCollectionView() { + collectionView.register(DiaryListCell.self, forCellWithReuseIdentifier: DiaryListCell.identifier) + collectionView.delegate = self + collectionView.dataSource = self + + collectionView.isScrollEnabled = true + collectionView.showsHorizontalScrollIndicator = false + collectionView.showsVerticalScrollIndicator = true + collectionView.backgroundColor = .clear + collectionView.clipsToBounds = true + collectionView.isPagingEnabled = false + collectionView.contentInsetAdjustmentBehavior = .never + collectionView.contentInset = Const.collectionViewContentInset + collectionView.decelerationRate = .fast + + collectionView.collectionViewLayout = collectionViewFlowLayout + } + + private func configureLayout() { + view.addSubview(collectionView) + + NSLayoutConstraint.activate([ + collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), + collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), + collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), + ]) } } +extension DiaryListViewController: UICollectionViewDataSource { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return 10 + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DiaryListCell.identifier, for: indexPath) as? DiaryListCell else { return UICollectionViewCell() } + cell.backgroundColor = .systemPink + cell.layer.cornerRadius = 20 + return cell + } +} + +extension DiaryListViewController: UICollectionViewDelegate {} + +extension DiaryListViewController: UICollectionViewDelegateFlowLayout { + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + let interItemSpacing: CGFloat = 10 + let padding: CGFloat = 10 + let width = (collectionView.bounds.width - interItemSpacing * 3 - padding * 2) + print("### \(width)") + let height = width / 3 + return CGSize(width: width, height: height) + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { + return 10 + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { + return 10 + } +} diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index 3d2b6e2..a54be2d 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -7,7 +7,7 @@ import UIKit -private enum Const { +enum Const { static let itemSize = CGSize(width: 300, height: 550) static let itemSpacing = 46.0 @@ -16,7 +16,7 @@ private enum Const { } static var collectionViewContentInset: UIEdgeInsets { - UIEdgeInsets(top: 40, left: Self.insetX, bottom: 10, right: Self.insetX) + UIEdgeInsets(top: 0, left: Self.insetX, bottom: 0, right: Self.insetX) } } @@ -63,10 +63,10 @@ class HomeViewController: UIViewController { view.addSubview(collectionView) NSLayoutConstraint.activate([ - collectionView.topAnchor.constraint(equalTo: view.topAnchor), + collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), - collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20), ]) } diff --git a/DiaryApp/Views/DiaryListCell.swift b/DiaryApp/Views/DiaryListCell.swift new file mode 100644 index 0000000..949a951 --- /dev/null +++ b/DiaryApp/Views/DiaryListCell.swift @@ -0,0 +1,20 @@ +// +// DiaryListCell.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/29. +// + +import UIKit + +final class DiaryListCell: UICollectionViewCell { + static let identifier = "DiaryListCell" + + override init(frame: CGRect) { + super.init(frame: frame) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} From 91697bba5cb1ae51a55b6cf4dea683adee3ddd07 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 12:29:00 +0900 Subject: [PATCH 06/42] =?UTF-8?q?[STYLE]:=20=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20=EC=97=86=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 20 +++++++++-- DiaryApp/Views/Cells/DiaryListCell.swift | 35 +++++++++++++++++++ DiaryApp/Views/{ => Cells}/HomeFeedCell.swift | 0 ...{DiaryListCell.swift => CustomLabel.swift} | 13 +++---- DiaryApp/Views/CustomStackView.swift | 20 +++++++++++ 5 files changed, 80 insertions(+), 8 deletions(-) create mode 100644 DiaryApp/Views/Cells/DiaryListCell.swift rename DiaryApp/Views/{ => Cells}/HomeFeedCell.swift (100%) rename DiaryApp/Views/{DiaryListCell.swift => CustomLabel.swift} (55%) create mode 100644 DiaryApp/Views/CustomStackView.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index da88814..78ae35d 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -8,6 +8,8 @@ /* Begin PBXBuildFile section */ 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550832A9E049100C8A500 /* DiaryListCell.swift */; }; + 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; + 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -31,6 +33,8 @@ /* Begin PBXFileReference section */ 4E1550832A9E049100C8A500 /* DiaryListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListCell.swift; sourceTree = ""; }; + 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomStackView.swift; sourceTree = ""; }; + 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomLabel.swift; sourceTree = ""; }; 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiaryApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; @@ -65,6 +69,15 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 4E1550852A9E0BBB00C8A500 /* Cells */ = { + isa = PBXGroup; + children = ( + 4E1550832A9E049100C8A500 /* DiaryListCell.swift */, + 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, + ); + path = Cells; + sourceTree = ""; + }; 4E98A3822A9CA57B003052D3 = { isa = PBXGroup; children = ( @@ -124,9 +137,10 @@ children = ( 4E98A3992A9CA57E003052D3 /* LaunchScreen.storyboard */, 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */, - 4E1550832A9E049100C8A500 /* DiaryListCell.swift */, - 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, + 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */, + 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */, + 4E1550852A9E0BBB00C8A500 /* Cells */, ); path = Views; sourceTree = ""; @@ -222,6 +236,8 @@ 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, + 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */, + 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */, 4E98A3BF2A9CBA1B003052D3 /* HomeFeedCell.swift in Sources */, 4E98A3AE2A9CA748003052D3 /* DetailDiaryViewController.swift in Sources */, 4E98A3AC2A9CA70B003052D3 /* DiaryListViewController.swift in Sources */, diff --git a/DiaryApp/Views/Cells/DiaryListCell.swift b/DiaryApp/Views/Cells/DiaryListCell.swift new file mode 100644 index 0000000..b5f4822 --- /dev/null +++ b/DiaryApp/Views/Cells/DiaryListCell.swift @@ -0,0 +1,35 @@ +// +// DiaryListCell.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/29. +// + +import UIKit + +final class DiaryListCell: UICollectionViewCell { + static let identifier = "DiaryListCell" + + let stackView = CustomStackView(frame: .zero) + + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + setupLayout() + } + + func setupUI() { + stackView.axis = .vertical + } + + func setupLayout() { + contentView.addSubview(stackView) + NSLayoutConstraint.activate([ + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/DiaryApp/Views/HomeFeedCell.swift b/DiaryApp/Views/Cells/HomeFeedCell.swift similarity index 100% rename from DiaryApp/Views/HomeFeedCell.swift rename to DiaryApp/Views/Cells/HomeFeedCell.swift diff --git a/DiaryApp/Views/DiaryListCell.swift b/DiaryApp/Views/CustomLabel.swift similarity index 55% rename from DiaryApp/Views/DiaryListCell.swift rename to DiaryApp/Views/CustomLabel.swift index 949a951..326414e 100644 --- a/DiaryApp/Views/DiaryListCell.swift +++ b/DiaryApp/Views/CustomLabel.swift @@ -1,19 +1,20 @@ // -// DiaryListCell.swift +// CustomLabel.swift // DiaryApp // // Created by (^ㅗ^)7 iMac on 2023/08/29. // -import UIKit - -final class DiaryListCell: UICollectionViewCell { - static let identifier = "DiaryListCell" +import Foundation +final class CustomLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) + self.textColor = .black + self.translatesAutoresizingMaskIntoConstraints = false } - + + @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/DiaryApp/Views/CustomStackView.swift b/DiaryApp/Views/CustomStackView.swift new file mode 100644 index 0000000..b68a694 --- /dev/null +++ b/DiaryApp/Views/CustomStackView.swift @@ -0,0 +1,20 @@ +// +// CustomStackView.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/29. +// + +import UIKit + +final class CustomStackView: UIStackView { + override init(frame: CGRect) { + super.init(frame: frame) + self.translatesAutoresizingMaskIntoConstraints = false + } + + @available(*, unavailable) + required init(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} From 5765151635ddd738ad0794504dee559d7a1e1a5e Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 12:32:03 +0900 Subject: [PATCH 07/42] =?UTF-8?q?[FEAT]:=20Snapkit=20=ED=8C=A8=ED=82=A4?= =?UTF-8?q?=EC=A7=80=20=EC=B6=94=EA=B0=80=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 27 +++++++++++++++++++ .../xcshareddata/swiftpm/Package.resolved | 14 ++++++++++ 2 files changed, 41 insertions(+) create mode 100644 DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 1631a8b..7fb802b 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -51,6 +52,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -145,6 +147,9 @@ dependencies = ( ); name = DiaryApp; + packageProductDependencies = ( + 4E6138AF2A9EEF50003A2B37 /* SnapKit */, + ); productName = DiaryApp; productReference = 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */; productType = "com.apple.product-type.application"; @@ -173,6 +178,9 @@ Base, ); mainGroup = 4E98A3822A9CA57B003052D3; + packageReferences = ( + 4E6138AE2A9EEF50003A2B37 /* XCRemoteSwiftPackageReference "SnapKit" */, + ); productRefGroup = 4E98A38C2A9CA57B003052D3 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -422,6 +430,25 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 4E6138AE2A9EEF50003A2B37 /* XCRemoteSwiftPackageReference "SnapKit" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/SnapKit/SnapKit.git"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 5.0.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 4E6138AF2A9EEF50003A2B37 /* SnapKit */ = { + isa = XCSwiftPackageProductDependency; + package = 4E6138AE2A9EEF50003A2B37 /* XCRemoteSwiftPackageReference "SnapKit" */; + productName = SnapKit; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 4E98A3832A9CA57B003052D3 /* Project object */; } diff --git a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..009c162 --- /dev/null +++ b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "snapkit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/SnapKit/SnapKit.git", + "state" : { + "revision" : "f222cbdf325885926566172f6f5f06af95473158", + "version" : "5.6.0" + } + } + ], + "version" : 2 +} From c36bda326d496d9b05c6f22bcd6dfb7495932789 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 12:38:33 +0900 Subject: [PATCH 08/42] =?UTF-8?q?[CONFLICT]:=20=EB=B3=91=ED=95=A9=20?= =?UTF-8?q?=EC=8B=9C=20=EC=B6=A9=EB=8F=8C=20=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 78ae35d..dc7ebc7 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -7,9 +7,13 @@ objects = { /* Begin PBXBuildFile section */ +<<<<<<< HEAD 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550832A9E049100C8A500 /* DiaryListCell.swift */; }; 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; +======= + 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; +>>>>>>> 5765151 ([FEAT]: Snapkit 패키지 추가가) 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -63,6 +67,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -171,6 +176,9 @@ dependencies = ( ); name = DiaryApp; + packageProductDependencies = ( + 4E6138AF2A9EEF50003A2B37 /* SnapKit */, + ); productName = DiaryApp; productReference = 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */; productType = "com.apple.product-type.application"; @@ -199,6 +207,9 @@ Base, ); mainGroup = 4E98A3822A9CA57B003052D3; + packageReferences = ( + 4E6138AE2A9EEF50003A2B37 /* XCRemoteSwiftPackageReference "SnapKit" */, + ); productRefGroup = 4E98A38C2A9CA57B003052D3 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -454,6 +465,25 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 4E6138AE2A9EEF50003A2B37 /* XCRemoteSwiftPackageReference "SnapKit" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/SnapKit/SnapKit.git"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 5.0.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 4E6138AF2A9EEF50003A2B37 /* SnapKit */ = { + isa = XCSwiftPackageProductDependency; + package = 4E6138AE2A9EEF50003A2B37 /* XCRemoteSwiftPackageReference "SnapKit" */; + productName = SnapKit; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 4E98A3832A9CA57B003052D3 /* Project object */; } From 29e09f6a8d28790ba0fe0eeeec502fcc3e5d8582 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 15:28:46 +0900 Subject: [PATCH 09/42] =?UTF-8?q?[STYLE]:=20=EC=BD=94=EB=93=9C=20=EB=A0=88?= =?UTF-8?q?=EC=9D=B4=EC=95=84=EC=9B=83=20Snapkit=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 3 --- .../xcshareddata/swiftpm/Package.resolved | 14 ++++++++++++++ .../Controllers/DiaryListViewController.swift | 16 ++++++++++------ DiaryApp/Views/CustomLabel.swift | 2 +- 4 files changed, 25 insertions(+), 10 deletions(-) create mode 100644 DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index dc7ebc7..5ea7647 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -7,13 +7,10 @@ objects = { /* Begin PBXBuildFile section */ -<<<<<<< HEAD 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550832A9E049100C8A500 /* DiaryListCell.swift */; }; 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; -======= 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; ->>>>>>> 5765151 ([FEAT]: Snapkit 패키지 추가가) 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; diff --git a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..009c162 --- /dev/null +++ b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "snapkit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/SnapKit/SnapKit.git", + "state" : { + "revision" : "f222cbdf325885926566172f6f5f06af95473158", + "version" : "5.6.0" + } + } + ], + "version" : 2 +} diff --git a/DiaryApp/Controllers/DiaryListViewController.swift b/DiaryApp/Controllers/DiaryListViewController.swift index 7a7d613..fb70692 100644 --- a/DiaryApp/Controllers/DiaryListViewController.swift +++ b/DiaryApp/Controllers/DiaryListViewController.swift @@ -5,6 +5,7 @@ // Created by (^ㅗ^)7 iMac on 2023/08/28. // +import SnapKit import UIKit class DiaryListViewController: UIViewController { @@ -47,12 +48,15 @@ class DiaryListViewController: UIViewController { private func configureLayout() { view.addSubview(collectionView) - NSLayoutConstraint.activate([ - collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), - collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), - collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), - collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), - ]) + collectionView.snp.makeConstraints { make in + make.top.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) + } +// NSLayoutConstraint.activate([ +// collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), +// collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), +// collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), +// collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), +// ]) } } diff --git a/DiaryApp/Views/CustomLabel.swift b/DiaryApp/Views/CustomLabel.swift index 326414e..7c09492 100644 --- a/DiaryApp/Views/CustomLabel.swift +++ b/DiaryApp/Views/CustomLabel.swift @@ -5,7 +5,7 @@ // Created by (^ㅗ^)7 iMac on 2023/08/29. // -import Foundation +import UIKit final class CustomLabel: UILabel { override init(frame: CGRect) { From 42e224869a93d21ea8388028fda748cab1b9df8a Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 18:07:22 +0900 Subject: [PATCH 10/42] =?UTF-8?q?[FEAT]:=20=ED=94=84=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EB=9E=98=EC=8A=A4=EB=B0=94=20&=20=EC=BD=9C=EB=A0=89=EC=85=98?= =?UTF-8?q?=EB=B7=B0=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 4 + .../Controllers/DiaryListViewController.swift | 12 +- DiaryApp/Views/Cells/DiaryListCell.swift | 130 +++++++++++++++++- .../Views/Cells/DiaryListThumbnailCell.swift | 34 +++++ 4 files changed, 168 insertions(+), 12 deletions(-) create mode 100644 DiaryApp/Views/Cells/DiaryListThumbnailCell.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 5ea7647..65a3e57 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -11,6 +11,7 @@ 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; + 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -36,6 +37,7 @@ 4E1550832A9E049100C8A500 /* DiaryListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListCell.swift; sourceTree = ""; }; 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomStackView.swift; sourceTree = ""; }; 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomLabel.swift; sourceTree = ""; }; + 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListThumbnailCell.swift; sourceTree = ""; }; 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiaryApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; @@ -75,6 +77,7 @@ isa = PBXGroup; children = ( 4E1550832A9E049100C8A500 /* DiaryListCell.swift */, + 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */, 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, ); path = Cells; @@ -239,6 +242,7 @@ 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */, 4E98A3A32A9CA634003052D3 /* HomeViewController.swift in Sources */, 4E98A3B22A9CA781003052D3 /* DiaryCalenderViewController.swift in Sources */, + 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */, 4E98A3A82A9CA6B6003052D3 /* EditDiaryViewController.swift in Sources */, 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */, 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, diff --git a/DiaryApp/Controllers/DiaryListViewController.swift b/DiaryApp/Controllers/DiaryListViewController.swift index fb70692..4a98878 100644 --- a/DiaryApp/Controllers/DiaryListViewController.swift +++ b/DiaryApp/Controllers/DiaryListViewController.swift @@ -51,12 +51,6 @@ class DiaryListViewController: UIViewController { collectionView.snp.makeConstraints { make in make.top.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) } -// NSLayoutConstraint.activate([ -// collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), -// collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), -// collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), -// collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), -// ]) } } @@ -67,7 +61,13 @@ extension DiaryListViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DiaryListCell.identifier, for: indexPath) as? DiaryListCell else { return UICollectionViewCell() } + cell.diaryTitleLabel.text = "Hello World" + cell.startDayLabel.text = "2023.08.30" + cell.endDayLabel.text = "2023.09.30" + cell.backgroundColor = .systemPink + cell.collectionView.backgroundColor = .systemBlue + cell.collectionView.layer.cornerRadius = 10 cell.layer.cornerRadius = 20 return cell } diff --git a/DiaryApp/Views/Cells/DiaryListCell.swift b/DiaryApp/Views/Cells/DiaryListCell.swift index b5f4822..d12400e 100644 --- a/DiaryApp/Views/Cells/DiaryListCell.swift +++ b/DiaryApp/Views/Cells/DiaryListCell.swift @@ -5,27 +5,121 @@ // Created by (^ㅗ^)7 iMac on 2023/08/29. // +import SnapKit import UIKit -final class DiaryListCell: UICollectionViewCell { +class DiaryListCell: UICollectionViewCell { static let identifier = "DiaryListCell" - let stackView = CustomStackView(frame: .zero) + let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewLayout()) + private let collectionViewFlowLayout: UICollectionViewFlowLayout = { + let layout = UICollectionViewFlowLayout() + layout.scrollDirection = .horizontal + layout.itemSize = CGSize(width: 40, height: 40) + layout.minimumLineSpacing = 5 + layout.minimumInteritemSpacing = 2 + layout.estimatedItemSize = .zero + return layout + }() + + private let stackView = CustomStackView(frame: .zero) + private let labelStackView = CustomStackView(frame: .zero) + + lazy var diaryTitleLabel = CustomLabel(frame: .zero) + lazy var startDayLabel = CustomLabel(frame: .zero) + lazy var endDayLabel = CustomLabel(frame: .zero) + private let spaceLabel = CustomLabel(frame: .zero) + + lazy var progressView: UIProgressView = { + let view = UIProgressView() + view.translatesAutoresizingMaskIntoConstraints = false + /// progress 배경 색상 + view.trackTintColor = .lightGray + /// progress 진행 색상 + view.progressTintColor = .systemBlue + view.progress = 0.5 + return view + }() override init(frame: CGRect) { super.init(frame: frame) setupUI() setupLayout() + configureCollectionView() } - func setupUI() { + private func setupUI() { stackView.axis = .vertical + stackView.backgroundColor = .systemOrange + stackView.distribution = .fillProportionally + stackView.spacing = 0 + + labelStackView.axis = .horizontal + labelStackView.backgroundColor = .systemBlue + labelStackView.distribution = .fillProportionally + + diaryTitleLabel.font = .systemFont(ofSize: 20, weight: .bold) + + startDayLabel.adjustsFontSizeToFitWidth = true + + spaceLabel.text = " ~ " + + endDayLabel.adjustsFontSizeToFitWidth = true + endDayLabel.textAlignment = .center + + collectionView.backgroundColor = .systemRed } - func setupLayout() { + private func setupLayout() { + contentView.addSubview(collectionView) + + collectionView.snp.makeConstraints { make in + make.top.equalTo(contentView.safeAreaLayoutGuide).inset(12) + make.bottom.equalTo(contentView.safeAreaLayoutGuide).inset(10) + make.leading.equalTo(contentView.safeAreaLayoutGuide).inset(25) + make.trailing.equalTo(contentView.safeAreaLayoutGuide).inset(210) + make.width.height.equalTo(50) + } + contentView.addSubview(stackView) - NSLayoutConstraint.activate([ - ]) + stackView.snp.makeConstraints { make in + make.top.trailing.bottom.equalTo(contentView.safeAreaLayoutGuide).inset(20) + make.leading.equalTo(collectionView.snp.trailing).offset(10) + } + + [diaryTitleLabel, progressView, labelStackView].forEach { + stackView.addArrangedSubview($0) + } + + progressView.snp.makeConstraints { make in + make.bottom.equalTo(labelStackView.snp.top).offset(-5) + make.height.equalTo(15) + } + + labelStackView.snp.makeConstraints { make in + make.height.equalTo(20) + } + + [startDayLabel, spaceLabel, endDayLabel].forEach { + labelStackView.addArrangedSubview($0) + } + } + + private func configureCollectionView() { + collectionView.register(DiaryListThumbnailCell.self, forCellWithReuseIdentifier: DiaryListThumbnailCell.identifier) + collectionView.dataSource = self + + collectionView.isScrollEnabled = false + collectionView.showsHorizontalScrollIndicator = false + collectionView.showsVerticalScrollIndicator = true + collectionView.backgroundColor = .clear + collectionView.clipsToBounds = true + collectionView.isPagingEnabled = false + collectionView.contentInsetAdjustmentBehavior = .never + collectionView.contentInset = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 5) + collectionView.decelerationRate = .fast + + collectionView.collectionViewLayout = collectionViewFlowLayout } @available(*, unavailable) @@ -33,3 +127,27 @@ final class DiaryListCell: UICollectionViewCell { fatalError("init(coder:) has not been implemented") } } + +extension DiaryListCell: UICollectionViewDataSource { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return 4 + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DiaryListThumbnailCell.identifier, for: indexPath) as? DiaryListThumbnailCell else { return UICollectionViewCell() } + cell.backgroundColor = .systemGreen + cell.layer.cornerRadius = 5 + cell.thumbNailImage.image = UIImage(systemName: "bell") + return cell + } +} + +extension DiaryListCell: UICollectionViewDelegateFlowLayout { + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + let interItemSpacing: CGFloat = 10 + let padding: CGFloat = 10 + let width = (collectionView.bounds.width - interItemSpacing * 3 - padding * 2) / 3 + let height = width + return CGSize(width: width, height: height) + } +} diff --git a/DiaryApp/Views/Cells/DiaryListThumbnailCell.swift b/DiaryApp/Views/Cells/DiaryListThumbnailCell.swift new file mode 100644 index 0000000..1a4c00f --- /dev/null +++ b/DiaryApp/Views/Cells/DiaryListThumbnailCell.swift @@ -0,0 +1,34 @@ +// +// DiaryListThumbnailCell.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/30. +// + +import SnapKit +import UIKit + +class DiaryListThumbnailCell: UICollectionViewCell { + static let identifier = "DiaryListThumbnailCell" + + lazy var thumbNailImage = CustomImageView(frame: .zero) + + override init(frame: CGRect) { + super.init(frame: frame) + configure() + } + + private func configure() { + thumbNailImage.contentMode = .scaleToFill + + contentView.addSubview(thumbNailImage) + thumbNailImage.snp.makeConstraints { make in + make.top.leading.trailing.bottom.equalTo(contentView) + } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} From 46195f1deee59c397ffb438bd3cc3062cfcfa5c5 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 18:14:12 +0900 Subject: [PATCH 11/42] =?UTF-8?q?[FEAT]:=20Diary-Progress-Page=20=EB=B8=8C?= =?UTF-8?q?=EB=9F=B0=EC=B9=98=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp/Controllers/DiaryProgressViewController.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/DiaryApp/Controllers/DiaryProgressViewController.swift b/DiaryApp/Controllers/DiaryProgressViewController.swift index d9d7542..9808beb 100644 --- a/DiaryApp/Controllers/DiaryProgressViewController.swift +++ b/DiaryApp/Controllers/DiaryProgressViewController.swift @@ -11,5 +11,6 @@ class DiaryProgressViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground + } } From 52e45b55d817827e1eb2136f5a59295b2a9b85ae Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 19:18:09 +0900 Subject: [PATCH 12/42] =?UTF-8?q?[FEAT]:=20DiaryProgressCell=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 4 ++++ .../Controllers/DiaryProgressViewController.swift | 13 ++++++++++++- DiaryApp/Resources/SceneDelegate.swift | 2 +- DiaryApp/Views/Cells/DiaryProgressCell.swift | 10 ++++++++++ 4 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 DiaryApp/Views/Cells/DiaryProgressCell.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 65a3e57..f413b2a 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -12,6 +12,7 @@ 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */; }; + 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -38,6 +39,7 @@ 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomStackView.swift; sourceTree = ""; }; 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomLabel.swift; sourceTree = ""; }; 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListThumbnailCell.swift; sourceTree = ""; }; + 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryProgressCell.swift; sourceTree = ""; }; 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiaryApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; @@ -78,6 +80,7 @@ children = ( 4E1550832A9E049100C8A500 /* DiaryListCell.swift */, 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */, + 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */, 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, ); path = Cells; @@ -248,6 +251,7 @@ 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, + 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */, 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */, 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */, 4E98A3BF2A9CBA1B003052D3 /* HomeFeedCell.swift in Sources */, diff --git a/DiaryApp/Controllers/DiaryProgressViewController.swift b/DiaryApp/Controllers/DiaryProgressViewController.swift index 9808beb..19021ad 100644 --- a/DiaryApp/Controllers/DiaryProgressViewController.swift +++ b/DiaryApp/Controllers/DiaryProgressViewController.swift @@ -8,9 +8,20 @@ import UIKit class DiaryProgressViewController: UIViewController { + private let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) + override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground - + } +} + +extension DiaryProgressViewController: UICollectionViewDataSource { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return 10 + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + return UICollectionViewCell() } } diff --git a/DiaryApp/Resources/SceneDelegate.swift b/DiaryApp/Resources/SceneDelegate.swift index e0f906e..5b21290 100644 --- a/DiaryApp/Resources/SceneDelegate.swift +++ b/DiaryApp/Resources/SceneDelegate.swift @@ -24,7 +24,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { (DiaryProgressViewController(), "tag.fill"), (ProfileViewController(), "person.fill"), ] - + tabBarController.setViewControllers(tabs.map { root, icon in let navigationController = UINavigationController(rootViewController: root) let tabBarItem = UITabBarItem(title: nil, image: .init(systemName: icon), selectedImage: .init(systemName: "\(icon).fill")) diff --git a/DiaryApp/Views/Cells/DiaryProgressCell.swift b/DiaryApp/Views/Cells/DiaryProgressCell.swift new file mode 100644 index 0000000..f95e0eb --- /dev/null +++ b/DiaryApp/Views/Cells/DiaryProgressCell.swift @@ -0,0 +1,10 @@ +// +// DiaryProgressCell.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/30. +// + +import Cocoa + +final class DiaryProgressCell: UICollectionViewCell {} From 681413b1b1b6ca7486db62431066b5da575368a0 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 22:45:23 +0900 Subject: [PATCH 13/42] =?UTF-8?q?[STYLE]:=20=EC=9E=91=EC=97=85=20=EB=82=B4?= =?UTF-8?q?=EC=97=AD=20=EC=A0=80=EC=9E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 4 ++ .../DiaryProgressViewController.swift | 67 ++++++++++++++++++- DiaryApp/Views/Cells/DiaryProgressCell.swift | 33 ++++++++- DiaryApp/Views/CircleProgressBar.swift | 61 +++++++++++++++++ 4 files changed, 161 insertions(+), 4 deletions(-) create mode 100644 DiaryApp/Views/CircleProgressBar.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index f413b2a..34dac76 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -13,6 +13,7 @@ 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */; }; 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */; }; + 4E6138B62A9F56E0003A2B37 /* CircleProgressBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B52A9F56E0003A2B37 /* CircleProgressBar.swift */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -40,6 +41,7 @@ 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomLabel.swift; sourceTree = ""; }; 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListThumbnailCell.swift; sourceTree = ""; }; 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryProgressCell.swift; sourceTree = ""; }; + 4E6138B52A9F56E0003A2B37 /* CircleProgressBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CircleProgressBar.swift; sourceTree = ""; }; 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiaryApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; @@ -148,6 +150,7 @@ 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */, 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */, + 4E6138B52A9F56E0003A2B37 /* CircleProgressBar.swift */, 4E1550852A9E0BBB00C8A500 /* Cells */, ); path = Views; @@ -243,6 +246,7 @@ 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */, 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */, 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */, + 4E6138B62A9F56E0003A2B37 /* CircleProgressBar.swift in Sources */, 4E98A3A32A9CA634003052D3 /* HomeViewController.swift in Sources */, 4E98A3B22A9CA781003052D3 /* DiaryCalenderViewController.swift in Sources */, 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */, diff --git a/DiaryApp/Controllers/DiaryProgressViewController.swift b/DiaryApp/Controllers/DiaryProgressViewController.swift index 19021ad..17a33e4 100644 --- a/DiaryApp/Controllers/DiaryProgressViewController.swift +++ b/DiaryApp/Controllers/DiaryProgressViewController.swift @@ -5,23 +5,86 @@ // Created by (^ㅗ^)7 iMac on 2023/08/28. // +import SnapKit import UIKit class DiaryProgressViewController: UIViewController { private let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) +// private let collectionViewFlowLayout: UICollectionViewFlowLayout = { +// let layout = UICollectionViewFlowLayout() +// layout.scrollDirection = .vertical +// layout.itemSize = Const.itemSize +// layout.minimumLineSpacing = Const.itemSpacing +// layout.minimumInteritemSpacing = 0 +// return layout +// }() + override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground + setupUI() + configureCollectionView() + } + + private func setupUI() { + view.addSubview(collectionView) + + collectionView.snp.makeConstraints { make in + make.top.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) + } + } + + private func configureCollectionView() { + collectionView.register(DiaryProgressCell.self, forCellWithReuseIdentifier: DiaryProgressCell.identifier) + collectionView.dataSource = self + collectionView.delegate = self + + collectionView.isScrollEnabled = true + collectionView.showsHorizontalScrollIndicator = false + collectionView.showsVerticalScrollIndicator = true + collectionView.backgroundColor = .clear + collectionView.clipsToBounds = true + collectionView.isPagingEnabled = false + collectionView.contentInsetAdjustmentBehavior = .never + collectionView.contentInset = Const.collectionViewContentInset + collectionView.decelerationRate = .fast + + if let flowlayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { + flowlayout.estimatedItemSize = .zero + } +// collectionView.collectionViewLayout = collectionViewFlowLayout } } extension DiaryProgressViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - return 10 + return 15 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - return UICollectionViewCell() + guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DiaryProgressCell.identifier, for: indexPath) as? DiaryProgressCell else { return UICollectionViewCell() } + + cell.backgroundColor = .systemPink + return cell + } +} + +extension DiaryProgressViewController: UICollectionViewDelegateFlowLayout { + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + let interItemSpacing: CGFloat = 10 + let padding: CGFloat = 16 + let width = (collectionView.bounds.width - interItemSpacing * 2 - padding * 2) / 2 + print("### \(width)") + let height = width + return CGSize(width: width, height: height) + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { + return 10 + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { + return 10 } } diff --git a/DiaryApp/Views/Cells/DiaryProgressCell.swift b/DiaryApp/Views/Cells/DiaryProgressCell.swift index f95e0eb..6b7af22 100644 --- a/DiaryApp/Views/Cells/DiaryProgressCell.swift +++ b/DiaryApp/Views/Cells/DiaryProgressCell.swift @@ -5,6 +5,35 @@ // Created by (^ㅗ^)7 iMac on 2023/08/30. // -import Cocoa +import SnapKit +import UIKit -final class DiaryProgressCell: UICollectionViewCell {} +final class DiaryProgressCell: UICollectionViewCell { + static let identifier = "DiaryProgressCell" + + lazy var circularProgressBarView = CircleProgressBar(frame: .zero) + lazy var percentLabel = CustomLabel(frame: .zero) + + override init(frame: CGRect) { + super.init(frame: frame) + setUpCircularProgressBarView() + } + + func setUpCircularProgressBarView() { + circularProgressBarView.translatesAutoresizingMaskIntoConstraints = false + + circularProgressBarView.center = contentView.center + circularProgressBarView.progressAnimation(duration: 30) + percentLabel.text = "100%" + + contentView.addSubview(circularProgressBarView) + circularProgressBarView.snp.makeConstraints { make in + make.centerX.centerY.equalTo(contentView) + } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/DiaryApp/Views/CircleProgressBar.swift b/DiaryApp/Views/CircleProgressBar.swift new file mode 100644 index 0000000..4be6935 --- /dev/null +++ b/DiaryApp/Views/CircleProgressBar.swift @@ -0,0 +1,61 @@ +// +// CircleProgressBar.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/30. +// + +import SnapKit +import UIKit + +final class CircleProgressBar: UIView { + private var circleLayer = CAShapeLayer() + private var progressLayer = CAShapeLayer() + private var startPoint = CGFloat(-Double.pi / 2) + private var endPoint = CGFloat(3 * Double.pi / 2) + + override init(frame: CGRect) { + super.init(frame: frame) + createCircularPath() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func createCircularPath() { + let circularPath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: 80, startAngle: startPoint, endAngle: endPoint, clockwise: true) + // circleLayer path defined to circularPath + circleLayer.path = circularPath.cgPath + // ui edits + circleLayer.fillColor = UIColor.clear.cgColor + circleLayer.lineCap = .round + circleLayer.lineWidth = 20.0 + circleLayer.strokeEnd = 1.0 + circleLayer.strokeColor = UIColor.systemGray6.cgColor + // added circleLayer to layer + layer.addSublayer(circleLayer) + // progressLayer path defined to circularPath + progressLayer.path = circularPath.cgPath + // ui edits + progressLayer.fillColor = UIColor.clear.cgColor + progressLayer.lineCap = .round + progressLayer.lineWidth = 10.0 + progressLayer.strokeEnd = 0 + progressLayer.strokeColor = UIColor.systemOrange.cgColor + // added progressLayer to layer + layer.addSublayer(progressLayer) + } + + func progressAnimation(duration: TimeInterval) { + // created circularProgressAnimation with keyPath + let circularProgressAnimation = CABasicAnimation(keyPath: "strokeEnd") + // set the end time + circularProgressAnimation.duration = 30 + circularProgressAnimation.toValue = 10.0 + circularProgressAnimation.fillMode = .forwards + circularProgressAnimation.isRemovedOnCompletion = false + progressLayer.add(circularProgressAnimation, forKey: "progressAnim") + } +} From 70454b6b7f9a761a087118c0e97384a1cea17d6b Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 23:12:31 +0900 Subject: [PATCH 14/42] =?UTF-8?q?FEAT]:=20=ED=94=84=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EB=9E=98=EC=8A=A4=EB=B0=94=20UI=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DiaryProgressViewController.swift | 11 ++++--- DiaryApp/Views/Cells/DiaryProgressCell.swift | 7 +++- DiaryApp/Views/CircleProgressBar.swift | 33 ++++++++++--------- 3 files changed, 29 insertions(+), 22 deletions(-) diff --git a/DiaryApp/Controllers/DiaryProgressViewController.swift b/DiaryApp/Controllers/DiaryProgressViewController.swift index 17a33e4..2f00330 100644 --- a/DiaryApp/Controllers/DiaryProgressViewController.swift +++ b/DiaryApp/Controllers/DiaryProgressViewController.swift @@ -47,7 +47,7 @@ class DiaryProgressViewController: UIViewController { collectionView.clipsToBounds = true collectionView.isPagingEnabled = false collectionView.contentInsetAdjustmentBehavior = .never - collectionView.contentInset = Const.collectionViewContentInset + collectionView.contentInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) collectionView.decelerationRate = .fast if let flowlayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { @@ -59,13 +59,14 @@ class DiaryProgressViewController: UIViewController { extension DiaryProgressViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - return 15 + return 7 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DiaryProgressCell.identifier, for: indexPath) as? DiaryProgressCell else { return UICollectionViewCell() } - - cell.backgroundColor = .systemPink + cell.backgroundColor = .clear + cell.circularProgressBarView.createCircularPath(0.3) + cell.percentLabel.text = "\(30)%" return cell } } @@ -73,7 +74,7 @@ extension DiaryProgressViewController: UICollectionViewDataSource { extension DiaryProgressViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let interItemSpacing: CGFloat = 10 - let padding: CGFloat = 16 + let padding: CGFloat = 10 let width = (collectionView.bounds.width - interItemSpacing * 2 - padding * 2) / 2 print("### \(width)") let height = width diff --git a/DiaryApp/Views/Cells/DiaryProgressCell.swift b/DiaryApp/Views/Cells/DiaryProgressCell.swift index 6b7af22..e0ac2fc 100644 --- a/DiaryApp/Views/Cells/DiaryProgressCell.swift +++ b/DiaryApp/Views/Cells/DiaryProgressCell.swift @@ -23,13 +23,18 @@ final class DiaryProgressCell: UICollectionViewCell { circularProgressBarView.translatesAutoresizingMaskIntoConstraints = false circularProgressBarView.center = contentView.center - circularProgressBarView.progressAnimation(duration: 30) +// circularProgressBarView.progressAnimation(duration: 30) percentLabel.text = "100%" contentView.addSubview(circularProgressBarView) circularProgressBarView.snp.makeConstraints { make in make.centerX.centerY.equalTo(contentView) } + + circularProgressBarView.addSubview(percentLabel) + percentLabel.snp.makeConstraints { make in + make.centerX.centerY.equalTo(circularProgressBarView) + } } @available(*, unavailable) diff --git a/DiaryApp/Views/CircleProgressBar.swift b/DiaryApp/Views/CircleProgressBar.swift index 4be6935..92043e5 100644 --- a/DiaryApp/Views/CircleProgressBar.swift +++ b/DiaryApp/Views/CircleProgressBar.swift @@ -13,10 +13,11 @@ final class CircleProgressBar: UIView { private var progressLayer = CAShapeLayer() private var startPoint = CGFloat(-Double.pi / 2) private var endPoint = CGFloat(3 * Double.pi / 2) + var dayCount: Double? override init(frame: CGRect) { super.init(frame: frame) - createCircularPath() + createCircularPath(dayCount ?? 0) } @available(*, unavailable) @@ -24,8 +25,8 @@ final class CircleProgressBar: UIView { fatalError("init(coder:) has not been implemented") } - func createCircularPath() { - let circularPath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: 80, startAngle: startPoint, endAngle: endPoint, clockwise: true) + func createCircularPath(_ strokeEnd: Double) { + let circularPath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: 65, startAngle: startPoint, endAngle: endPoint, clockwise: true) // circleLayer path defined to circularPath circleLayer.path = circularPath.cgPath // ui edits @@ -41,21 +42,21 @@ final class CircleProgressBar: UIView { // ui edits progressLayer.fillColor = UIColor.clear.cgColor progressLayer.lineCap = .round - progressLayer.lineWidth = 10.0 - progressLayer.strokeEnd = 0 - progressLayer.strokeColor = UIColor.systemOrange.cgColor + progressLayer.lineWidth = 20.0 + progressLayer.strokeEnd = strokeEnd + progressLayer.strokeColor = UIColor.systemBlue.cgColor // added progressLayer to layer layer.addSublayer(progressLayer) } - func progressAnimation(duration: TimeInterval) { - // created circularProgressAnimation with keyPath - let circularProgressAnimation = CABasicAnimation(keyPath: "strokeEnd") - // set the end time - circularProgressAnimation.duration = 30 - circularProgressAnimation.toValue = 10.0 - circularProgressAnimation.fillMode = .forwards - circularProgressAnimation.isRemovedOnCompletion = false - progressLayer.add(circularProgressAnimation, forKey: "progressAnim") - } +// func progressAnimation(duration: TimeInterval) { +// // created circularProgressAnimation with keyPath +// let circularProgressAnimation = CABasicAnimation(keyPath: "strokeEnd") +// // set the end time +// circularProgressAnimation.duration = 30 +// circularProgressAnimation.toValue = 3 +// circularProgressAnimation.fillMode = .forwards +// circularProgressAnimation.isRemovedOnCompletion = false +// progressLayer.add(circularProgressAnimation, forKey: "progressAnim") +// } } From 2a6ba115932c62550871b94723c0a5377a8a75ec Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 23:28:42 +0900 Subject: [PATCH 15/42] =?UTF-8?q?[STYLE]:=20=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=EC=9D=B4=20=EC=97=86=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp/Controllers/DiaryListViewController.swift | 3 ++- DiaryApp/Controllers/HomeViewController.swift | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/DiaryApp/Controllers/DiaryListViewController.swift b/DiaryApp/Controllers/DiaryListViewController.swift index 4a98878..16dcca9 100644 --- a/DiaryApp/Controllers/DiaryListViewController.swift +++ b/DiaryApp/Controllers/DiaryListViewController.swift @@ -49,7 +49,8 @@ class DiaryListViewController: UIViewController { view.addSubview(collectionView) collectionView.snp.makeConstraints { make in - make.top.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) + make.top.leading.trailing.equalTo(view.safeAreaLayoutGuide) + make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-10) } } } diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index a54be2d..b86b144 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -25,7 +25,7 @@ class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - view.backgroundColor = .systemBackground + view.backgroundColor = .systemGray6 configureCollectionView() configureLayout() addSearchBar() From a7964007579da625d0384a3e8785f0dca839ce5b Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 23:43:31 +0900 Subject: [PATCH 16/42] =?UTF-8?q?[MERGE]=20:=20=EB=B3=91=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 4 ++++ .../xcshareddata/swiftpm/Package.resolved | 14 -------------- 2 files changed, 4 insertions(+), 14 deletions(-) delete mode 100644 DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 34dac76..3201e58 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ +<<<<<<< HEAD 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550832A9E049100C8A500 /* DiaryListCell.swift */; }; 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; @@ -14,6 +15,9 @@ 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */; }; 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */; }; 4E6138B62A9F56E0003A2B37 /* CircleProgressBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B52A9F56E0003A2B37 /* CircleProgressBar.swift */; }; +======= + 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; +>>>>>>> 5765151 ([FEAT]: Snapkit 패키지 추가가) 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; diff --git a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved deleted file mode 100644 index 009c162..0000000 --- a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ /dev/null @@ -1,14 +0,0 @@ -{ - "pins" : [ - { - "identity" : "snapkit", - "kind" : "remoteSourceControl", - "location" : "https://github.com/SnapKit/SnapKit.git", - "state" : { - "revision" : "f222cbdf325885926566172f6f5f06af95473158", - "version" : "5.6.0" - } - } - ], - "version" : 2 -} From 1472db483b5b22f30c24b2ae536a8ce485be8723 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 23:46:41 +0900 Subject: [PATCH 17/42] =?UTF-8?q?[MERGE]=20:=20=EB=B3=91=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 3201e58..1985749 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -7,17 +7,11 @@ objects = { /* Begin PBXBuildFile section */ -<<<<<<< HEAD 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550832A9E049100C8A500 /* DiaryListCell.swift */; }; 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; - 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */; }; - 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */; }; - 4E6138B62A9F56E0003A2B37 /* CircleProgressBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B52A9F56E0003A2B37 /* CircleProgressBar.swift */; }; -======= - 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; ->>>>>>> 5765151 ([FEAT]: Snapkit 패키지 추가가) +>>>>>>> 29e09f6 ([STYLE]: 코드 레이아웃 Snapkit으로 변경) 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -43,9 +37,6 @@ 4E1550832A9E049100C8A500 /* DiaryListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListCell.swift; sourceTree = ""; }; 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomStackView.swift; sourceTree = ""; }; 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomLabel.swift; sourceTree = ""; }; - 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListThumbnailCell.swift; sourceTree = ""; }; - 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryProgressCell.swift; sourceTree = ""; }; - 4E6138B52A9F56E0003A2B37 /* CircleProgressBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CircleProgressBar.swift; sourceTree = ""; }; 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiaryApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; @@ -85,8 +76,6 @@ isa = PBXGroup; children = ( 4E1550832A9E049100C8A500 /* DiaryListCell.swift */, - 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */, - 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */, 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, ); path = Cells; @@ -154,7 +143,6 @@ 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */, 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */, - 4E6138B52A9F56E0003A2B37 /* CircleProgressBar.swift */, 4E1550852A9E0BBB00C8A500 /* Cells */, ); path = Views; @@ -250,10 +238,8 @@ 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */, 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */, 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */, - 4E6138B62A9F56E0003A2B37 /* CircleProgressBar.swift in Sources */, 4E98A3A32A9CA634003052D3 /* HomeViewController.swift in Sources */, 4E98A3B22A9CA781003052D3 /* DiaryCalenderViewController.swift in Sources */, - 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */, 4E98A3A82A9CA6B6003052D3 /* EditDiaryViewController.swift in Sources */, 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */, 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, From dcef2d0522f9230e76709fcc66a7d5f0bfc0f386 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 23:48:14 +0900 Subject: [PATCH 18/42] =?UTF-8?q?[MERGE]=20:=20=EB=B3=91=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 1985749..eca51c5 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -11,7 +11,8 @@ 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; ->>>>>>> 29e09f6 ([STYLE]: 코드 레이아웃 Snapkit으로 변경) + 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */; }; + 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; From 1431699e0bf0b207499a79986212825137b0f597 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 23:30:14 +0900 Subject: [PATCH 19/42] =?UTF-8?q?[STYLE]:=20=ED=83=AD=EB=B0=94=EC=BB=A8?= =?UTF-8?q?=ED=8A=B8=EB=A1=A4=EB=9F=AC=20=EC=95=84=EC=9D=B4=EC=BD=98?= =?UTF-8?q?=ED=91=9C=ED=98=84=20=EC=BD=94=EB=93=9C=20=ED=8F=AC=EB=A7=B7=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp/Resources/SceneDelegate.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DiaryApp/Resources/SceneDelegate.swift b/DiaryApp/Resources/SceneDelegate.swift index 5b21290..28a72e8 100644 --- a/DiaryApp/Resources/SceneDelegate.swift +++ b/DiaryApp/Resources/SceneDelegate.swift @@ -21,8 +21,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { (HomeViewController(), "house"), (DiaryListViewController(), "list.bullet"), (NewDiaryViewController(), "plus.square"), - (DiaryProgressViewController(), "tag.fill"), - (ProfileViewController(), "person.fill"), + (DiaryProgressViewController(), "tag"), + (ProfileViewController(), "person"), ] tabBarController.setViewControllers(tabs.map { root, icon in From 510df131d7b7c039cfb0486dd5986ef0dc62fe64 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 23:50:43 +0900 Subject: [PATCH 20/42] =?UTF-8?q?[MERGE]=20:=20=EB=B3=91=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 8 ++++ DiaryApp/Controllers/HomeViewController.swift | 4 +- DiaryApp/Resources/SceneDelegate.swift | 2 +- DiaryApp/Views/HomeFeedCell.swift | 45 +++++++++++++++++++ 4 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 DiaryApp/Views/HomeFeedCell.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index eca51c5..a00dec0 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -141,10 +141,15 @@ children = ( 4E98A3992A9CA57E003052D3 /* LaunchScreen.storyboard */, 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */, +<<<<<<< HEAD 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */, 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */, 4E1550852A9E0BBB00C8A500 /* Cells */, +======= + 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, + 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, +>>>>>>> d8ba701 ([FEAT]: feature/home-Page 브런치 병합) ); path = Views; sourceTree = ""; @@ -246,9 +251,12 @@ 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, +<<<<<<< HEAD 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */, 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */, 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */, +======= +>>>>>>> d8ba701 ([FEAT]: feature/home-Page 브런치 병합) 4E98A3BF2A9CBA1B003052D3 /* HomeFeedCell.swift in Sources */, 4E98A3AE2A9CA748003052D3 /* DetailDiaryViewController.swift in Sources */, 4E98A3AC2A9CA70B003052D3 /* DiaryListViewController.swift in Sources */, diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index b86b144..46df91f 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -7,7 +7,7 @@ import UIKit -enum Const { +private enum Const { static let itemSize = CGSize(width: 300, height: 550) static let itemSpacing = 46.0 @@ -25,7 +25,7 @@ class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - view.backgroundColor = .systemGray6 + view.backgroundColor = .systemBackground configureCollectionView() configureLayout() addSearchBar() diff --git a/DiaryApp/Resources/SceneDelegate.swift b/DiaryApp/Resources/SceneDelegate.swift index 28a72e8..298ead0 100644 --- a/DiaryApp/Resources/SceneDelegate.swift +++ b/DiaryApp/Resources/SceneDelegate.swift @@ -24,7 +24,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { (DiaryProgressViewController(), "tag"), (ProfileViewController(), "person"), ] - + tabBarController.setViewControllers(tabs.map { root, icon in let navigationController = UINavigationController(rootViewController: root) let tabBarItem = UITabBarItem(title: nil, image: .init(systemName: icon), selectedImage: .init(systemName: "\(icon).fill")) diff --git a/DiaryApp/Views/HomeFeedCell.swift b/DiaryApp/Views/HomeFeedCell.swift new file mode 100644 index 0000000..0b2bdc4 --- /dev/null +++ b/DiaryApp/Views/HomeFeedCell.swift @@ -0,0 +1,45 @@ +// +// HomeFeedCell.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/28. +// + +import UIKit + +final class HomeFeedCell: UICollectionViewCell { + static let identifier = "HomeFeedCell" + + private let myView = CustomImageView(frame: .zero) + private let weatherImage = CustomImageView(frame: .zero) + + let sizeWidth = 70.0 + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override init(frame: CGRect) { + super.init(frame: frame) + + self.contentView.addSubview(self.myView) + + self.weatherImage.backgroundColor = .systemBlue + self.weatherImage.layer.cornerRadius = CGFloat(self.sizeWidth / 2) + + self.myView.addSubview(self.weatherImage) + + NSLayoutConstraint.activate([ + self.myView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor), + self.myView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor), + self.myView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), + self.myView.topAnchor.constraint(equalTo: self.contentView.topAnchor), + + self.weatherImage.trailingAnchor.constraint(equalTo: self.myView.trailingAnchor, constant: -30), + self.weatherImage.bottomAnchor.constraint(equalTo: self.myView.bottomAnchor, constant: -30), + self.weatherImage.heightAnchor.constraint(equalToConstant: self.sizeWidth), + self.weatherImage.widthAnchor.constraint(equalToConstant: self.sizeWidth), + ]) + } +} From c4faefaaae13345bbcd18fb5ca26693af44703c1 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 23:28:42 +0900 Subject: [PATCH 21/42] =?UTF-8?q?[STYLE]:=20=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=EC=9D=B4=20=EC=97=86=EC=9D=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp/Controllers/HomeViewController.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index 46df91f..928a1dc 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -25,7 +25,7 @@ class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - view.backgroundColor = .systemBackground + view.backgroundColor = .systemGray6 configureCollectionView() configureLayout() addSearchBar() From bdf3c91de821e4314ab1c34293990d8bc3dd10c5 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Thu, 31 Aug 2023 00:01:40 +0900 Subject: [PATCH 22/42] =?UTF-8?q?[FIX]=20=EB=B3=91=ED=95=A9=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=20=ED=95=B4=EA=B2=B0=20=EC=A4=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp/Controllers/HomeViewController.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index 928a1dc..46df91f 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -25,7 +25,7 @@ class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - view.backgroundColor = .systemGray6 + view.backgroundColor = .systemBackground configureCollectionView() configureLayout() addSearchBar() From 5225cacd8de4cf1e78db1cbe0b5ff22199c3160e Mon Sep 17 00:00:00 2001 From: MOMO <89556301+jakkujakku@users.noreply.github.com> Date: Thu, 31 Aug 2023 00:31:37 +0900 Subject: [PATCH 23/42] Update project.pbxproj MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [FIX] : Conflict 해결 중 --- DiaryApp.xcodeproj/project.pbxproj | 6 ------ 1 file changed, 6 deletions(-) diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index a00dec0..be4e761 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -141,15 +141,12 @@ children = ( 4E98A3992A9CA57E003052D3 /* LaunchScreen.storyboard */, 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */, -<<<<<<< HEAD 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */, 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */, 4E1550852A9E0BBB00C8A500 /* Cells */, -======= 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, ->>>>>>> d8ba701 ([FEAT]: feature/home-Page 브런치 병합) ); path = Views; sourceTree = ""; @@ -251,12 +248,9 @@ 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, -<<<<<<< HEAD 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */, 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */, 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */, -======= ->>>>>>> d8ba701 ([FEAT]: feature/home-Page 브런치 병합) 4E98A3BF2A9CBA1B003052D3 /* HomeFeedCell.swift in Sources */, 4E98A3AE2A9CA748003052D3 /* DetailDiaryViewController.swift in Sources */, 4E98A3AC2A9CA70B003052D3 /* DiaryListViewController.swift in Sources */, From 40a991b28aece414fe9acc0283567005b96dd986 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Thu, 31 Aug 2023 01:11:31 +0900 Subject: [PATCH 24/42] =?UTF-8?q?[FIX]=20:=20Git=20Pull=20Merge=20Conflict?= =?UTF-8?q?=20=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 50 +++++++++---------- .../contents.xcworkspacedata | 2 +- .../xcshareddata/swiftpm/Package.resolved | 14 ++++++ DiaryApp/Controllers/HomeViewController.swift | 2 +- .../LaunchScreen.storyboard | 0 DiaryApp/Views/HomeFeedCell.swift | 45 ----------------- 6 files changed, 41 insertions(+), 72 deletions(-) create mode 100644 DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved rename DiaryApp/{Views/Base.lproj => Resources}/LaunchScreen.storyboard (100%) delete mode 100644 DiaryApp/Views/HomeFeedCell.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index be4e761..cf9a89a 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -11,13 +11,16 @@ 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; - 4E6138B22A9F2664003A2B37 /* DiaryListThumbnailCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B12A9F2664003A2B37 /* DiaryListThumbnailCell.swift */; }; - 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138B32A9F4E87003A2B37 /* DiaryProgressCell.swift */; }; + 4E6138C02A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138BD2A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift */; }; + 4E6138C12A9F9E8B003A2B37 /* DiaryProgressCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138BE2A9F9E8B003A2B37 /* DiaryProgressCell.swift */; }; + 4E6138C22A9F9E8B003A2B37 /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138BF2A9F9E8B003A2B37 /* HomeFeedCell.swift */; }; + 4E6138C42A9F9FBA003A2B37 /* CircleProgressBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138C32A9F9FBA003A2B37 /* CircleProgressBar.swift */; }; + 4E6138C62A9F9FDE003A2B37 /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138C52A9F9FDE003A2B37 /* HomeFeedCell.swift */; }; + 4E6138C92A9FA164003A2B37 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4E6138C82A9FA164003A2B37 /* LaunchScreen.storyboard */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; 4E98A3982A9CA57E003052D3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 4E98A3972A9CA57E003052D3 /* Assets.xcassets */; }; - 4E98A39B2A9CA57E003052D3 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4E98A3992A9CA57E003052D3 /* LaunchScreen.storyboard */; }; 4E98A3A32A9CA634003052D3 /* HomeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3A22A9CA634003052D3 /* HomeViewController.swift */; }; 4E98A3A62A9CA6A6003052D3 /* NewDiaryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3A52A9CA6A6003052D3 /* NewDiaryViewController.swift */; }; 4E98A3A82A9CA6B6003052D3 /* EditDiaryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3A72A9CA6B6003052D3 /* EditDiaryViewController.swift */; }; @@ -30,7 +33,6 @@ 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B72A9CAD27003052D3 /* User.swift */; }; 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B92A9CAD60003052D3 /* Weather.swift */; }; 4E98A3BD2A9CB918003052D3 /* CustomCollectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */; }; - 4E98A3BF2A9CBA1B003052D3 /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */; }; 4E98A3C12A9CCFB8003052D3 /* CustomImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */; }; /* End PBXBuildFile section */ @@ -38,12 +40,17 @@ 4E1550832A9E049100C8A500 /* DiaryListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListCell.swift; sourceTree = ""; }; 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomStackView.swift; sourceTree = ""; }; 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomLabel.swift; sourceTree = ""; }; + 4E6138BD2A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DiaryListThumbnailCell.swift; sourceTree = ""; }; + 4E6138BE2A9F9E8B003A2B37 /* DiaryProgressCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DiaryProgressCell.swift; sourceTree = ""; }; + 4E6138BF2A9F9E8B003A2B37 /* HomeFeedCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HomeFeedCell.swift; sourceTree = ""; }; + 4E6138C32A9F9FBA003A2B37 /* CircleProgressBar.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CircleProgressBar.swift; sourceTree = ""; }; + 4E6138C52A9F9FDE003A2B37 /* HomeFeedCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HomeFeedCell.swift; sourceTree = ""; }; + 4E6138C82A9FA164003A2B37 /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = ""; }; 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiaryApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; 4E98A3922A9CA57B003052D3 /* TabBarController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TabBarController.swift; sourceTree = ""; }; 4E98A3972A9CA57E003052D3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 4E98A39A2A9CA57E003052D3 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 4E98A39C2A9CA57E003052D3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 4E98A3A22A9CA634003052D3 /* HomeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeViewController.swift; sourceTree = ""; }; 4E98A3A52A9CA6A6003052D3 /* NewDiaryViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewDiaryViewController.swift; sourceTree = ""; }; @@ -57,7 +64,6 @@ 4E98A3B72A9CAD27003052D3 /* User.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; 4E98A3B92A9CAD60003052D3 /* Weather.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Weather.swift; sourceTree = ""; }; 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomCollectionView.swift; sourceTree = ""; }; - 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeFeedCell.swift; sourceTree = ""; }; 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomImageView.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -77,7 +83,10 @@ isa = PBXGroup; children = ( 4E1550832A9E049100C8A500 /* DiaryListCell.swift */, - 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, + 4E6138BD2A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift */, + 4E6138BE2A9F9E8B003A2B37 /* DiaryProgressCell.swift */, + 4E6138C52A9F9FDE003A2B37 /* HomeFeedCell.swift */, + 4E6138BF2A9F9E8B003A2B37 /* HomeFeedCell.swift */, ); path = Cells; sourceTree = ""; @@ -139,14 +148,12 @@ 4E98A3B42A9CA7AD003052D3 /* Views */ = { isa = PBXGroup; children = ( - 4E98A3992A9CA57E003052D3 /* LaunchScreen.storyboard */, 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */, - 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */, 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */, - 4E1550852A9E0BBB00C8A500 /* Cells */, - 4E98A3BE2A9CBA1B003052D3 /* HomeFeedCell.swift */, + 4E6138C32A9F9FBA003A2B37 /* CircleProgressBar.swift */, 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */, + 4E1550852A9E0BBB00C8A500 /* Cells */, ); path = Views; sourceTree = ""; @@ -157,6 +164,7 @@ 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */, 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */, 4E98A3972A9CA57E003052D3 /* Assets.xcassets */, + 4E6138C82A9FA164003A2B37 /* LaunchScreen.storyboard */, ); path = Resources; sourceTree = ""; @@ -225,8 +233,8 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 4E98A39B2A9CA57E003052D3 /* LaunchScreen.storyboard in Resources */, 4E98A3982A9CA57E003052D3 /* Assets.xcassets in Resources */, + 4E6138C92A9FA164003A2B37 /* LaunchScreen.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -237,6 +245,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 4E6138C62A9F9FDE003A2B37 /* HomeFeedCell.swift in Sources */, 4E98A3BD2A9CB918003052D3 /* CustomCollectionView.swift in Sources */, 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */, 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */, @@ -245,16 +254,18 @@ 4E98A3B22A9CA781003052D3 /* DiaryCalenderViewController.swift in Sources */, 4E98A3A82A9CA6B6003052D3 /* EditDiaryViewController.swift in Sources */, 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */, + 4E6138C02A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift in Sources */, 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, + 4E6138C22A9F9E8B003A2B37 /* HomeFeedCell.swift in Sources */, 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */, + 4E6138C12A9F9E8B003A2B37 /* DiaryProgressCell.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, - 4E6138B42A9F4E87003A2B37 /* DiaryProgressCell.swift in Sources */, 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */, 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */, - 4E98A3BF2A9CBA1B003052D3 /* HomeFeedCell.swift in Sources */, 4E98A3AE2A9CA748003052D3 /* DetailDiaryViewController.swift in Sources */, 4E98A3AC2A9CA70B003052D3 /* DiaryListViewController.swift in Sources */, 4E98A3B02A9CA762003052D3 /* DiaryProgressViewController.swift in Sources */, + 4E6138C42A9F9FBA003A2B37 /* CircleProgressBar.swift in Sources */, 4E98A3A62A9CA6A6003052D3 /* NewDiaryViewController.swift in Sources */, 4E98A3C12A9CCFB8003052D3 /* CustomImageView.swift in Sources */, 4E98A3AA2A9CA6F6003052D3 /* ProgressListViewController.swift in Sources */, @@ -263,17 +274,6 @@ }; /* End PBXSourcesBuildPhase section */ -/* Begin PBXVariantGroup section */ - 4E98A3992A9CA57E003052D3 /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 4E98A39A2A9CA57E003052D3 /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - /* Begin XCBuildConfiguration section */ 4E98A39D2A9CA57E003052D3 /* Debug */ = { isa = XCBuildConfiguration; diff --git a/DiaryApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/DiaryApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 919434a..1bd1958 100644 --- a/DiaryApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/DiaryApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "self:../DiaryApp/Views"> diff --git a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..009c162 --- /dev/null +++ b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "snapkit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/SnapKit/SnapKit.git", + "state" : { + "revision" : "f222cbdf325885926566172f6f5f06af95473158", + "version" : "5.6.0" + } + } + ], + "version" : 2 +} diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index 46df91f..a54be2d 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -7,7 +7,7 @@ import UIKit -private enum Const { +enum Const { static let itemSize = CGSize(width: 300, height: 550) static let itemSpacing = 46.0 diff --git a/DiaryApp/Views/Base.lproj/LaunchScreen.storyboard b/DiaryApp/Resources/LaunchScreen.storyboard similarity index 100% rename from DiaryApp/Views/Base.lproj/LaunchScreen.storyboard rename to DiaryApp/Resources/LaunchScreen.storyboard diff --git a/DiaryApp/Views/HomeFeedCell.swift b/DiaryApp/Views/HomeFeedCell.swift deleted file mode 100644 index 0b2bdc4..0000000 --- a/DiaryApp/Views/HomeFeedCell.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// HomeFeedCell.swift -// DiaryApp -// -// Created by (^ㅗ^)7 iMac on 2023/08/28. -// - -import UIKit - -final class HomeFeedCell: UICollectionViewCell { - static let identifier = "HomeFeedCell" - - private let myView = CustomImageView(frame: .zero) - private let weatherImage = CustomImageView(frame: .zero) - - let sizeWidth = 70.0 - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - override init(frame: CGRect) { - super.init(frame: frame) - - self.contentView.addSubview(self.myView) - - self.weatherImage.backgroundColor = .systemBlue - self.weatherImage.layer.cornerRadius = CGFloat(self.sizeWidth / 2) - - self.myView.addSubview(self.weatherImage) - - NSLayoutConstraint.activate([ - self.myView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor), - self.myView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor), - self.myView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), - self.myView.topAnchor.constraint(equalTo: self.contentView.topAnchor), - - self.weatherImage.trailingAnchor.constraint(equalTo: self.myView.trailingAnchor, constant: -30), - self.weatherImage.bottomAnchor.constraint(equalTo: self.myView.bottomAnchor, constant: -30), - self.weatherImage.heightAnchor.constraint(equalToConstant: self.sizeWidth), - self.weatherImage.widthAnchor.constraint(equalToConstant: self.sizeWidth), - ]) - } -} From 89306790615b3bd37cdfc5385e53e0d8ce9a7e05 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Thu, 31 Aug 2023 19:43:54 +0900 Subject: [PATCH 25/42] =?UTF-8?q?[FEAT]=20:=20feature/Progress-List-Page?= =?UTF-8?q?=20=EB=B8=8C=EB=9F=B0=EC=B9=98=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DiaryApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/DiaryApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 1bd1958..919434a 100644 --- a/DiaryApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/DiaryApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "self:"> From a06054b6386835d868a456ae4d5f426402bf750b Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Thu, 31 Aug 2023 19:54:42 +0900 Subject: [PATCH 26/42] =?UTF-8?q?[FEAT]=20:=20DiaryListViewController=20->?= =?UTF-8?q?=20ProgressListViewController=20=EB=84=A4=EB=B9=84=EA=B2=8C?= =?UTF-8?q?=EC=9D=B4=EC=85=98=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp/Controllers/DiaryListViewController.swift | 7 ++++++- DiaryApp/Controllers/ProgressListViewController.swift | 2 ++ DiaryApp/Views/Cells/DiaryListCell.swift | 10 ---------- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/DiaryApp/Controllers/DiaryListViewController.swift b/DiaryApp/Controllers/DiaryListViewController.swift index 16dcca9..92bcb12 100644 --- a/DiaryApp/Controllers/DiaryListViewController.swift +++ b/DiaryApp/Controllers/DiaryListViewController.swift @@ -74,7 +74,12 @@ extension DiaryListViewController: UICollectionViewDataSource { } } -extension DiaryListViewController: UICollectionViewDelegate {} +extension DiaryListViewController: UICollectionViewDelegate { + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + let vc = ProgressListViewController() + navigationController?.pushViewController(vc, animated: true) + } +} extension DiaryListViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { diff --git a/DiaryApp/Controllers/ProgressListViewController.swift b/DiaryApp/Controllers/ProgressListViewController.swift index 0e1653a..1d0fdd4 100644 --- a/DiaryApp/Controllers/ProgressListViewController.swift +++ b/DiaryApp/Controllers/ProgressListViewController.swift @@ -8,6 +8,8 @@ import UIKit class ProgressListViewController: UIViewController { + static let identifier = "ProgressListViewController" + override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground diff --git a/DiaryApp/Views/Cells/DiaryListCell.swift b/DiaryApp/Views/Cells/DiaryListCell.swift index d12400e..81fbbd4 100644 --- a/DiaryApp/Views/Cells/DiaryListCell.swift +++ b/DiaryApp/Views/Cells/DiaryListCell.swift @@ -141,13 +141,3 @@ extension DiaryListCell: UICollectionViewDataSource { return cell } } - -extension DiaryListCell: UICollectionViewDelegateFlowLayout { - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - let interItemSpacing: CGFloat = 10 - let padding: CGFloat = 10 - let width = (collectionView.bounds.width - interItemSpacing * 3 - padding * 2) / 3 - let height = width - return CGSize(width: width, height: height) - } -} From cd6d5b986a128fcb0b96c2667ebac13db597b436 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Thu, 31 Aug 2023 20:09:04 +0900 Subject: [PATCH 27/42] =?UTF-8?q?[FEAT]:=20ProgressListCell=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=20=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 4 + .../ProgressListViewController.swift | 73 ++++++++++++++++++- DiaryApp/Views/Cells/ProgressListCell.swift | 12 +++ 3 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 DiaryApp/Views/Cells/ProgressListCell.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index cf9a89a..3426ad1 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -17,6 +17,7 @@ 4E6138C42A9F9FBA003A2B37 /* CircleProgressBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138C32A9F9FBA003A2B37 /* CircleProgressBar.swift */; }; 4E6138C62A9F9FDE003A2B37 /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138C52A9F9FDE003A2B37 /* HomeFeedCell.swift */; }; 4E6138C92A9FA164003A2B37 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4E6138C82A9FA164003A2B37 /* LaunchScreen.storyboard */; }; + 4E7A15042AA0A9C8005FCD9C /* ProgressListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15032AA0A9C8005FCD9C /* ProgressListCell.swift */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -46,6 +47,7 @@ 4E6138C32A9F9FBA003A2B37 /* CircleProgressBar.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CircleProgressBar.swift; sourceTree = ""; }; 4E6138C52A9F9FDE003A2B37 /* HomeFeedCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HomeFeedCell.swift; sourceTree = ""; }; 4E6138C82A9FA164003A2B37 /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = ""; }; + 4E7A15032AA0A9C8005FCD9C /* ProgressListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProgressListCell.swift; sourceTree = ""; }; 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiaryApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; @@ -87,6 +89,7 @@ 4E6138BE2A9F9E8B003A2B37 /* DiaryProgressCell.swift */, 4E6138C52A9F9FDE003A2B37 /* HomeFeedCell.swift */, 4E6138BF2A9F9E8B003A2B37 /* HomeFeedCell.swift */, + 4E7A15032AA0A9C8005FCD9C /* ProgressListCell.swift */, ); path = Cells; sourceTree = ""; @@ -258,6 +261,7 @@ 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, 4E6138C22A9F9E8B003A2B37 /* HomeFeedCell.swift in Sources */, 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */, + 4E7A15042AA0A9C8005FCD9C /* ProgressListCell.swift in Sources */, 4E6138C12A9F9E8B003A2B37 /* DiaryProgressCell.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */, diff --git a/DiaryApp/Controllers/ProgressListViewController.swift b/DiaryApp/Controllers/ProgressListViewController.swift index 1d0fdd4..f0e97c5 100644 --- a/DiaryApp/Controllers/ProgressListViewController.swift +++ b/DiaryApp/Controllers/ProgressListViewController.swift @@ -6,12 +6,83 @@ // import UIKit +import SnapKit class ProgressListViewController: UIViewController { - static let identifier = "ProgressListViewController" + private let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground + configureCollectionView() + configureLayout() + } + + private let collectionViewFlowLayout: UICollectionViewFlowLayout = { + let layout = UICollectionViewFlowLayout() + layout.scrollDirection = .vertical + layout.itemSize = Const.itemSize + layout.minimumLineSpacing = Const.itemSpacing + layout.minimumInteritemSpacing = 0 + return layout + }() + + private func configureCollectionView() { + collectionView.register(ProgressListCell.self, forCellWithReuseIdentifier: ProgressListCell.identifier) + collectionView.dataSource = self + collectionView.delegate = self + + collectionView.isScrollEnabled = true + collectionView.showsHorizontalScrollIndicator = false + collectionView.showsVerticalScrollIndicator = true + collectionView.backgroundColor = .clear + collectionView.clipsToBounds = true + collectionView.isPagingEnabled = false + collectionView.contentInsetAdjustmentBehavior = .never + collectionView.contentInset = Const.collectionViewContentInset + collectionView.decelerationRate = .fast + + collectionView.collectionViewLayout = collectionViewFlowLayout + } + + private func configureLayout() { + view.addSubview(collectionView) + + collectionView.snp.makeConstraints { make in + make.top.leading.trailing.equalTo(view.safeAreaLayoutGuide) + make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-10) + } + } +} + +extension ProgressListViewController: UICollectionViewDataSource { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return 7 + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProgressListCell.identifier, for: indexPath) as? ProgressListCell else { return UICollectionViewCell() } + cell.backgroundColor = .systemRed + cell.layer.cornerRadius = 20 + return cell + } +} + +extension ProgressListViewController: UICollectionViewDelegateFlowLayout { + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + let interItemSpacing: CGFloat = 10 + let padding: CGFloat = 10 + let width = (collectionView.bounds.width - interItemSpacing * 3 - padding * 2) + print("### \(width)") + let height = width / 3 + return CGSize(width: width, height: height) + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { + return 10 + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { + return 10 } } diff --git a/DiaryApp/Views/Cells/ProgressListCell.swift b/DiaryApp/Views/Cells/ProgressListCell.swift new file mode 100644 index 0000000..2a6cee0 --- /dev/null +++ b/DiaryApp/Views/Cells/ProgressListCell.swift @@ -0,0 +1,12 @@ +// +// ProgressListCell.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/31. +// + +import UIKit + +class ProgressListCell: UICollectionViewCell { + static let identifier = "ProgressListCell" +} From 59834cdc34236212bbc755f5375c7fadfa98ff12 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Thu, 31 Aug 2023 21:56:08 +0900 Subject: [PATCH 28/42] =?UTF-8?q?[FEAT]:=20ProgressTageCell=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=20&=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 16 +-- .../ProgressListViewController.swift | 8 +- DiaryApp/Views/Cells/DiaryProgressCell.swift | 3 +- DiaryApp/Views/Cells/ProgressListCell.swift | 107 ++++++++++++++++++ DiaryApp/Views/Cells/ProgressTagCell.swift | 39 +++++++ 5 files changed, 161 insertions(+), 12 deletions(-) create mode 100644 DiaryApp/Views/Cells/ProgressTagCell.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 3426ad1..4dc13df 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -13,11 +13,11 @@ 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; 4E6138C02A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138BD2A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift */; }; 4E6138C12A9F9E8B003A2B37 /* DiaryProgressCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138BE2A9F9E8B003A2B37 /* DiaryProgressCell.swift */; }; - 4E6138C22A9F9E8B003A2B37 /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138BF2A9F9E8B003A2B37 /* HomeFeedCell.swift */; }; 4E6138C42A9F9FBA003A2B37 /* CircleProgressBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138C32A9F9FBA003A2B37 /* CircleProgressBar.swift */; }; - 4E6138C62A9F9FDE003A2B37 /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6138C52A9F9FDE003A2B37 /* HomeFeedCell.swift */; }; 4E6138C92A9FA164003A2B37 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4E6138C82A9FA164003A2B37 /* LaunchScreen.storyboard */; }; 4E7A15042AA0A9C8005FCD9C /* ProgressListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15032AA0A9C8005FCD9C /* ProgressListCell.swift */; }; + 4E7A15062AA0BFA1005FCD9C /* ProgressTagCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15052AA0BFA1005FCD9C /* ProgressTagCell.swift */; }; + 4E7A150A2AA0C11E005FCD9C /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15092AA0C11E005FCD9C /* HomeFeedCell.swift */; }; 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; @@ -43,11 +43,11 @@ 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomLabel.swift; sourceTree = ""; }; 4E6138BD2A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DiaryListThumbnailCell.swift; sourceTree = ""; }; 4E6138BE2A9F9E8B003A2B37 /* DiaryProgressCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DiaryProgressCell.swift; sourceTree = ""; }; - 4E6138BF2A9F9E8B003A2B37 /* HomeFeedCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HomeFeedCell.swift; sourceTree = ""; }; 4E6138C32A9F9FBA003A2B37 /* CircleProgressBar.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CircleProgressBar.swift; sourceTree = ""; }; - 4E6138C52A9F9FDE003A2B37 /* HomeFeedCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HomeFeedCell.swift; sourceTree = ""; }; 4E6138C82A9FA164003A2B37 /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = ""; }; 4E7A15032AA0A9C8005FCD9C /* ProgressListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProgressListCell.swift; sourceTree = ""; }; + 4E7A15052AA0BFA1005FCD9C /* ProgressTagCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProgressTagCell.swift; sourceTree = ""; }; + 4E7A15092AA0C11E005FCD9C /* HomeFeedCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HomeFeedCell.swift; sourceTree = ""; }; 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = DiaryApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; @@ -86,10 +86,10 @@ children = ( 4E1550832A9E049100C8A500 /* DiaryListCell.swift */, 4E6138BD2A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift */, + 4E7A15052AA0BFA1005FCD9C /* ProgressTagCell.swift */, 4E6138BE2A9F9E8B003A2B37 /* DiaryProgressCell.swift */, - 4E6138C52A9F9FDE003A2B37 /* HomeFeedCell.swift */, - 4E6138BF2A9F9E8B003A2B37 /* HomeFeedCell.swift */, 4E7A15032AA0A9C8005FCD9C /* ProgressListCell.swift */, + 4E7A15092AA0C11E005FCD9C /* HomeFeedCell.swift */, ); path = Cells; sourceTree = ""; @@ -248,7 +248,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 4E6138C62A9F9FDE003A2B37 /* HomeFeedCell.swift in Sources */, + 4E7A150A2AA0C11E005FCD9C /* HomeFeedCell.swift in Sources */, 4E98A3BD2A9CB918003052D3 /* CustomCollectionView.swift in Sources */, 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */, 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */, @@ -259,8 +259,8 @@ 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */, 4E6138C02A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift in Sources */, 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, - 4E6138C22A9F9E8B003A2B37 /* HomeFeedCell.swift in Sources */, 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */, + 4E7A15062AA0BFA1005FCD9C /* ProgressTagCell.swift in Sources */, 4E7A15042AA0A9C8005FCD9C /* ProgressListCell.swift in Sources */, 4E6138C12A9F9E8B003A2B37 /* DiaryProgressCell.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, diff --git a/DiaryApp/Controllers/ProgressListViewController.swift b/DiaryApp/Controllers/ProgressListViewController.swift index f0e97c5..fbf6fb3 100644 --- a/DiaryApp/Controllers/ProgressListViewController.swift +++ b/DiaryApp/Controllers/ProgressListViewController.swift @@ -5,8 +5,8 @@ // Created by (^ㅗ^)7 iMac on 2023/08/28. // -import UIKit import SnapKit +import UIKit class ProgressListViewController: UIViewController { private let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) @@ -31,7 +31,7 @@ class ProgressListViewController: UIViewController { collectionView.register(ProgressListCell.self, forCellWithReuseIdentifier: ProgressListCell.identifier) collectionView.dataSource = self collectionView.delegate = self - + collectionView.isScrollEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = true @@ -62,6 +62,10 @@ extension ProgressListViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProgressListCell.identifier, for: indexPath) as? ProgressListCell else { return UICollectionViewCell() } + cell.imageView.image = UIImage(systemName: "bell") + cell.weatherImageView.image = UIImage(systemName: "sun.max") + cell.descriptionLabel.text = "오늘 하루 운동을 했는데 어쩌구 저쩌구 닭가슴살을 먹었는데 어쩌구 저쩌구 헬스장을 다녀왔는데 어쩌구 저꺼구" + cell.backgroundColor = .systemRed cell.layer.cornerRadius = 20 return cell diff --git a/DiaryApp/Views/Cells/DiaryProgressCell.swift b/DiaryApp/Views/Cells/DiaryProgressCell.swift index e0ac2fc..21f2699 100644 --- a/DiaryApp/Views/Cells/DiaryProgressCell.swift +++ b/DiaryApp/Views/Cells/DiaryProgressCell.swift @@ -23,14 +23,13 @@ final class DiaryProgressCell: UICollectionViewCell { circularProgressBarView.translatesAutoresizingMaskIntoConstraints = false circularProgressBarView.center = contentView.center -// circularProgressBarView.progressAnimation(duration: 30) percentLabel.text = "100%" contentView.addSubview(circularProgressBarView) circularProgressBarView.snp.makeConstraints { make in make.centerX.centerY.equalTo(contentView) } - + circularProgressBarView.addSubview(percentLabel) percentLabel.snp.makeConstraints { make in make.centerX.centerY.equalTo(circularProgressBarView) diff --git a/DiaryApp/Views/Cells/ProgressListCell.swift b/DiaryApp/Views/Cells/ProgressListCell.swift index 2a6cee0..e95c440 100644 --- a/DiaryApp/Views/Cells/ProgressListCell.swift +++ b/DiaryApp/Views/Cells/ProgressListCell.swift @@ -5,8 +5,115 @@ // Created by (^ㅗ^)7 iMac on 2023/08/31. // +import SnapKit import UIKit class ProgressListCell: UICollectionViewCell { static let identifier = "ProgressListCell" + + lazy var imageView = CustomImageView(frame: .zero) + lazy var weatherImageView = CustomImageView(frame: .zero) + lazy var descriptionLabel = CustomLabel(frame: .zero) + + private let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) + + private let collectionViewFlowLayout: UICollectionViewFlowLayout = { + let layout = UICollectionViewFlowLayout() + layout.scrollDirection = .horizontal + layout.itemSize = CGSize(width: 50, height: 20) + layout.minimumLineSpacing = 5 + layout.minimumInteritemSpacing = 2 + layout.estimatedItemSize = .zero + return layout + }() + + override init(frame: CGRect) { + super.init(frame: frame) + configureCell() + setupLayout() + configureCollectionView() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func configureCell() { + imageView.contentMode = .scaleAspectFit + imageView.layer.cornerRadius = 20 + imageView.backgroundColor = .systemBrown + + descriptionLabel.backgroundColor = .white + descriptionLabel.font = .systemFont(ofSize: 15, weight: .regular) + descriptionLabel.numberOfLines = 3 + descriptionLabel.textAlignment = .left + descriptionLabel.adjustsFontSizeToFitWidth = false + + weatherImageView.contentMode = .scaleAspectFit + weatherImageView.layer.cornerRadius = weatherImageView.bounds.size.width / 2 + weatherImageView.backgroundColor = .purple + } + + private func setupLayout() { + contentView.addSubview(imageView) + imageView.snp.makeConstraints { make in + make.top.leading.bottom.equalTo(contentView) + make.width.equalTo(imageView.snp.height) + } + + contentView.addSubview(weatherImageView) + weatherImageView.snp.makeConstraints { make in + make.leading.equalTo(imageView.snp.trailing).offset(10) + make.top.equalTo(contentView).inset(5) + make.width.height.equalTo(30) + } + + contentView.addSubview(descriptionLabel) + descriptionLabel.snp.makeConstraints { make in + make.leading.equalTo(imageView.snp.trailing).offset(10) + make.trailing.equalTo(contentView).inset(10) + make.top.equalTo(weatherImageView.snp.bottom).offset(5) + make.bottom.equalTo(contentView).inset(10) + } + + contentView.addSubview(collectionView) + collectionView.snp.makeConstraints { make in + make.top.equalTo(contentView).inset(5) + make.trailing.equalTo(contentView).inset(10) + make.bottom.equalTo(descriptionLabel.snp.top).offset(5) + make.leading.equalTo(weatherImageView.snp.trailing).offset(5) + } + } + + private func configureCollectionView() { + collectionView.register(ProgressTagCell.self, forCellWithReuseIdentifier: ProgressTagCell.identifier) + collectionView.dataSource = self + + collectionView.isScrollEnabled = false + collectionView.showsHorizontalScrollIndicator = false + collectionView.showsVerticalScrollIndicator = true + collectionView.backgroundColor = .clear + collectionView.clipsToBounds = true + collectionView.isPagingEnabled = false + collectionView.contentInsetAdjustmentBehavior = .never + collectionView.contentInset = UIEdgeInsets(top: 5, left: 5, bottom: 15, right: 5) + collectionView.decelerationRate = .fast + + collectionView.collectionViewLayout = collectionViewFlowLayout + } +} + +extension ProgressListCell: UICollectionViewDataSource { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return 3 + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProgressTagCell.identifier, for: indexPath) as? ProgressTagCell else { return UICollectionViewCell() } + cell.tagTitleLabel.text = "Hi" + cell.backgroundColor = .systemYellow + cell.layer.cornerRadius = 5 + return cell + } } diff --git a/DiaryApp/Views/Cells/ProgressTagCell.swift b/DiaryApp/Views/Cells/ProgressTagCell.swift new file mode 100644 index 0000000..c8893bc --- /dev/null +++ b/DiaryApp/Views/Cells/ProgressTagCell.swift @@ -0,0 +1,39 @@ +// +// ProgressTagCell.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/31. +// + +import SnapKit +import UIKit + +final class ProgressTagCell: UICollectionViewCell { + static let identifier = "ProgressTagCell" + + lazy var tagTitleLabel = CustomLabel(frame: .zero) + + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + setupLayout() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func setupUI() { + tagTitleLabel.numberOfLines = 1 + tagTitleLabel.font = .systemFont(ofSize: 15) + tagTitleLabel.textAlignment = .center + } + + func setupLayout() { + contentView.addSubview(tagTitleLabel) + tagTitleLabel.snp.makeConstraints { make in + make.top.bottom.leading.trailing.equalTo(contentView).inset(-10) + } + } +} From 4e1582cb6617ac4b52f09ffa4852370f732f98c9 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Thu, 31 Aug 2023 22:01:34 +0900 Subject: [PATCH 29/42] =?UTF-8?q?[FEAT]:=20DiaryProgressViewController=20-?= =?UTF-8?q?>=20ProgressListViewController=20=EB=84=A4=EB=B9=84=EA=B2=8C?= =?UTF-8?q?=EC=9D=B4=EC=85=98=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DiaryProgressViewController.swift | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/DiaryApp/Controllers/DiaryProgressViewController.swift b/DiaryApp/Controllers/DiaryProgressViewController.swift index 2f00330..35e523c 100644 --- a/DiaryApp/Controllers/DiaryProgressViewController.swift +++ b/DiaryApp/Controllers/DiaryProgressViewController.swift @@ -11,15 +11,6 @@ import UIKit class DiaryProgressViewController: UIViewController { private let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) -// private let collectionViewFlowLayout: UICollectionViewFlowLayout = { -// let layout = UICollectionViewFlowLayout() -// layout.scrollDirection = .vertical -// layout.itemSize = Const.itemSize -// layout.minimumLineSpacing = Const.itemSpacing -// layout.minimumInteritemSpacing = 0 -// return layout -// }() - override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground @@ -53,7 +44,6 @@ class DiaryProgressViewController: UIViewController { if let flowlayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowlayout.estimatedItemSize = .zero } -// collectionView.collectionViewLayout = collectionViewFlowLayout } } @@ -71,6 +61,13 @@ extension DiaryProgressViewController: UICollectionViewDataSource { } } +extension DiaryProgressViewController: UICollectionViewDelegate { + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + let vc = ProgressListViewController() + navigationController?.pushViewController(vc, animated: true) + } +} + extension DiaryProgressViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let interItemSpacing: CGFloat = 10 From e09690ad309dbbbc81abc1e8734416c23a2f3c45 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Wed, 30 Aug 2023 12:32:03 +0900 Subject: [PATCH 30/42] =?UTF-8?q?[FEAT]:=20Snapkit=20=ED=8C=A8=ED=82=A4?= =?UTF-8?q?=EC=A7=80=20=EC=B6=94=EA=B0=80=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 4 ++++ .../xcshareddata/swiftpm/Package.resolved | 14 -------------- 2 files changed, 4 insertions(+), 14 deletions(-) delete mode 100644 DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 4dc13df..71e028f 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ +<<<<<<< HEAD 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550832A9E049100C8A500 /* DiaryListCell.swift */; }; 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; @@ -18,6 +19,9 @@ 4E7A15042AA0A9C8005FCD9C /* ProgressListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15032AA0A9C8005FCD9C /* ProgressListCell.swift */; }; 4E7A15062AA0BFA1005FCD9C /* ProgressTagCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15052AA0BFA1005FCD9C /* ProgressTagCell.swift */; }; 4E7A150A2AA0C11E005FCD9C /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15092AA0C11E005FCD9C /* HomeFeedCell.swift */; }; +======= + 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; +>>>>>>> 5765151 ([FEAT]: Snapkit 패키지 추가가) 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; diff --git a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved deleted file mode 100644 index 009c162..0000000 --- a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ /dev/null @@ -1,14 +0,0 @@ -{ - "pins" : [ - { - "identity" : "snapkit", - "kind" : "remoteSourceControl", - "location" : "https://github.com/SnapKit/SnapKit.git", - "state" : { - "revision" : "f222cbdf325885926566172f6f5f06af95473158", - "version" : "5.6.0" - } - } - ], - "version" : 2 -} From 7666d255661d6a34f3688c8074dbafafc8afac9a Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Thu, 31 Aug 2023 22:24:24 +0900 Subject: [PATCH 31/42] =?UTF-8?q?[MERGE]:=20Develop=20=EB=B3=91=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 4 ---- 1 file changed, 4 deletions(-) diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 71e028f..4dc13df 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -7,7 +7,6 @@ objects = { /* Begin PBXBuildFile section */ -<<<<<<< HEAD 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550832A9E049100C8A500 /* DiaryListCell.swift */; }; 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; @@ -19,9 +18,6 @@ 4E7A15042AA0A9C8005FCD9C /* ProgressListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15032AA0A9C8005FCD9C /* ProgressListCell.swift */; }; 4E7A15062AA0BFA1005FCD9C /* ProgressTagCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15052AA0BFA1005FCD9C /* ProgressTagCell.swift */; }; 4E7A150A2AA0C11E005FCD9C /* HomeFeedCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E7A15092AA0C11E005FCD9C /* HomeFeedCell.swift */; }; -======= - 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 4E6138AF2A9EEF50003A2B37 /* SnapKit */; }; ->>>>>>> 5765151 ([FEAT]: Snapkit 패키지 추가가) 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A38E2A9CA57B003052D3 /* AppDelegate.swift */; }; 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3902A9CA57B003052D3 /* SceneDelegate.swift */; }; 4E98A3932A9CA57B003052D3 /* TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3922A9CA57B003052D3 /* TabBarController.swift */; }; From 2fce643865c32fa00e5755bc314a376035b1ea47 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Thu, 31 Aug 2023 22:27:53 +0900 Subject: [PATCH 32/42] =?UTF-8?q?[MERGE]:=20Develop=20=EB=B3=91=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xcshareddata/swiftpm/Package.resolved | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved diff --git a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..009c162 --- /dev/null +++ b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "snapkit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/SnapKit/SnapKit.git", + "state" : { + "revision" : "f222cbdf325885926566172f6f5f06af95473158", + "version" : "5.6.0" + } + } + ], + "version" : 2 +} From 63972b7a5049b99c7154fa81915408061c5d76d0 Mon Sep 17 00:00:00 2001 From: p2glet Date: Thu, 31 Aug 2023 22:42:59 +0900 Subject: [PATCH 33/42] =?UTF-8?q?[MERGE]=20feature/DiaryCalendar=20?= =?UTF-8?q?=EB=B3=91=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 8 +- .../DiaryCalendarViewController.swift | 488 ++++++++++++++++++ .../DiaryCalenderViewController.swift | 15 - 3 files changed, 492 insertions(+), 19 deletions(-) create mode 100644 DiaryApp/Controllers/DiaryCalendarViewController.swift delete mode 100644 DiaryApp/Controllers/DiaryCalenderViewController.swift diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 4dc13df..9e34023 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -29,12 +29,12 @@ 4E98A3AC2A9CA70B003052D3 /* DiaryListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3AB2A9CA70B003052D3 /* DiaryListViewController.swift */; }; 4E98A3AE2A9CA748003052D3 /* DetailDiaryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3AD2A9CA748003052D3 /* DetailDiaryViewController.swift */; }; 4E98A3B02A9CA762003052D3 /* DiaryProgressViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3AF2A9CA762003052D3 /* DiaryProgressViewController.swift */; }; - 4E98A3B22A9CA781003052D3 /* DiaryCalenderViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B12A9CA781003052D3 /* DiaryCalenderViewController.swift */; }; 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B52A9CAA16003052D3 /* ProfileViewController.swift */; }; 4E98A3B82A9CAD27003052D3 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B72A9CAD27003052D3 /* User.swift */; }; 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B92A9CAD60003052D3 /* Weather.swift */; }; 4E98A3BD2A9CB918003052D3 /* CustomCollectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */; }; 4E98A3C12A9CCFB8003052D3 /* CustomImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */; }; + FF0F824A2AA0D01C005CFB57 /* DiaryCalendarViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF0F82492AA0D01C005CFB57 /* DiaryCalendarViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -61,12 +61,12 @@ 4E98A3AB2A9CA70B003052D3 /* DiaryListViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListViewController.swift; sourceTree = ""; }; 4E98A3AD2A9CA748003052D3 /* DetailDiaryViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetailDiaryViewController.swift; sourceTree = ""; }; 4E98A3AF2A9CA762003052D3 /* DiaryProgressViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryProgressViewController.swift; sourceTree = ""; }; - 4E98A3B12A9CA781003052D3 /* DiaryCalenderViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryCalenderViewController.swift; sourceTree = ""; }; 4E98A3B52A9CAA16003052D3 /* ProfileViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileViewController.swift; sourceTree = ""; }; 4E98A3B72A9CAD27003052D3 /* User.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; 4E98A3B92A9CAD60003052D3 /* Weather.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Weather.swift; sourceTree = ""; }; 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomCollectionView.swift; sourceTree = ""; }; 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomImageView.swift; sourceTree = ""; }; + FF0F82492AA0D01C005CFB57 /* DiaryCalendarViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DiaryCalendarViewController.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -129,11 +129,11 @@ 4E98A3A22A9CA634003052D3 /* HomeViewController.swift */, 4E98A3A52A9CA6A6003052D3 /* NewDiaryViewController.swift */, 4E98A3A72A9CA6B6003052D3 /* EditDiaryViewController.swift */, + FF0F82492AA0D01C005CFB57 /* DiaryCalendarViewController.swift */, 4E98A3A92A9CA6F6003052D3 /* ProgressListViewController.swift */, 4E98A3AB2A9CA70B003052D3 /* DiaryListViewController.swift */, 4E98A3AD2A9CA748003052D3 /* DetailDiaryViewController.swift */, 4E98A3AF2A9CA762003052D3 /* DiaryProgressViewController.swift */, - 4E98A3B12A9CA781003052D3 /* DiaryCalenderViewController.swift */, 4E98A3B52A9CAA16003052D3 /* ProfileViewController.swift */, ); path = Controllers; @@ -254,7 +254,6 @@ 4E98A38F2A9CA57B003052D3 /* AppDelegate.swift in Sources */, 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */, 4E98A3A32A9CA634003052D3 /* HomeViewController.swift in Sources */, - 4E98A3B22A9CA781003052D3 /* DiaryCalenderViewController.swift in Sources */, 4E98A3A82A9CA6B6003052D3 /* EditDiaryViewController.swift in Sources */, 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */, 4E6138C02A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift in Sources */, @@ -272,6 +271,7 @@ 4E6138C42A9F9FBA003A2B37 /* CircleProgressBar.swift in Sources */, 4E98A3A62A9CA6A6003052D3 /* NewDiaryViewController.swift in Sources */, 4E98A3C12A9CCFB8003052D3 /* CustomImageView.swift in Sources */, + FF0F824A2AA0D01C005CFB57 /* DiaryCalendarViewController.swift in Sources */, 4E98A3AA2A9CA6F6003052D3 /* ProgressListViewController.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/DiaryApp/Controllers/DiaryCalendarViewController.swift b/DiaryApp/Controllers/DiaryCalendarViewController.swift new file mode 100644 index 0000000..581e77c --- /dev/null +++ b/DiaryApp/Controllers/DiaryCalendarViewController.swift @@ -0,0 +1,488 @@ +// +// BottomSheetViewController.swift +// DiaryApp +// +// Created by t2023-m0056 on 2023/08/31. +// + +import UIKit +import SnapKit + +@available(iOS 16.0, *) +class DiaryCalendarViewController: UIViewController { + + // MARK: - BottomSheet + // 바텀 시트 높이 + var bottomHeight: CGFloat = 620 + + // bottomSheet가 view의 상단에서 떨어진 거리 + private var bottomSheetViewTopConstraint: NSLayoutConstraint! + + // 기존 화면을 흐려지게 만들기 위한 뷰 + private let dimmedBackView: UIView = { + let view = UIView() + view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) + return view + }() + + // 바텀 시트 뷰 + private let bottomSheetView: UIView = { + let view = UIView() + view.backgroundColor = .white + + view.layer.cornerRadius = 27 + view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] + view.clipsToBounds = true + + return view + }() + + // MARK: - Callendar + + lazy var dateView: UICalendarView = { + var view = UICalendarView() + view.wantsDateDecorations = true + return view + }() + + var selectedDate: DateComponents? = nil + + // MARK: - Properties + + var purposeTextField: UITextField = { + var textField = UITextField() + let centeredParagraphStyle = NSMutableParagraphStyle() + centeredParagraphStyle.alignment = .center + textField.attributedPlaceholder = NSAttributedString(string: "목표", attributes:[NSAttributedString.Key.foregroundColor : UIColor.black, NSAttributedString.Key.paragraphStyle: centeredParagraphStyle]) + textField.layer.cornerRadius = 10 + textField.layer.borderWidth = 1 + return textField + }() + + var everyDayBtn = UIButton(), threeDaysBtn = UIButton(), fiveDaysBtn = UIButton(), everyWeekBtn = UIButton() + + var checkedEverDay = false, checkedThreeDays = false, checkedFiveDays = false, checkedEverWeek = false + + var sundayBtn = UIButton() ,mondayBtn = UIButton(), tuesdayBtn = UIButton(), wednesdayBtn = UIButton(), thursdayBtn = UIButton(), fridayBtn = UIButton(), saturdayBtn = UIButton() + + var checkedSunday = false, checkedMonday = false, checkedTuesday = false, checkedWednesday = false, checkedThursday = false, checkedFridaay = false, checkedSaturday = false + + var saveBtn: UIButton = { + var btn = UIButton() + btn.setTitle("저장", for: .normal) + btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) + btn.setTitleColor(.black, for: .normal) + btn.layer.cornerRadius = 10 + btn.layer.borderWidth = 1 + return btn + }() + + // dismiss Indicator View UI 구성 부분 + private let dismissIndicatorView: UIView = { + let view = UIView() + view.backgroundColor = .systemGray + view.layer.cornerRadius = 3 + return view + }() + + // MARK: - StackView + + var totalStackView = { + var view = UIStackView() + view.axis = .vertical + view.spacing = 10 + view.snp.makeConstraints{ + $0.height.equalTo(120) + } + return view + }() + + lazy var intervalStackView = { + var view = UIStackView(arrangedSubviews: [self.everyDayBtn, self.threeDaysBtn, self.fiveDaysBtn, self.everyWeekBtn]) + view.axis = .horizontal + view.distribution = .equalSpacing + view.snp.makeConstraints{ + $0.height.equalTo(50) + } + return view + }() + + lazy var dayStackView = { + let view = UIStackView(arrangedSubviews: [self.sundayBtn,self.mondayBtn,self.tuesdayBtn,self.wednesdayBtn,self.thursdayBtn,self.fridayBtn,self.saturdayBtn]) + view.axis = .horizontal + view.distribution = .equalSpacing + view.isHidden = true + view.snp.makeConstraints{ + $0.height.equalTo(40) + } + return view + }() + + // MARK: - View Life Cycle + override func viewDidLoad() { + super.viewDidLoad() + + dateView.delegate = self + let dateSelection = UICalendarSelectionSingleDate(delegate: self) + dateView.selectionBehavior = dateSelection + + configurationView() + setupGestureRecognizer() + } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + showBottomSheet() + } + + // MARK: - @Functions + func configurationView() { + setupUI() + setupLayout() + setDateView() + setPurposeTitle() + setTotalStackView() + + setEveryDayBtn() + setThreeDaysBtn() + setFiveDaysBtn() + setEveryWeekBtn() + + setSundayBtn() + setMondayBtn() + setTuesdayBtn() + setWednesdayBtn() + setThursdayBtn() + setFridayBtn() + setSaturdayBtn() + + setSaveBtn() + } + + // UI 세팅 작업 + private func setupUI() { + view.addSubview(dimmedBackView) + view.addSubview(bottomSheetView) + view.addSubview(dismissIndicatorView) + dimmedBackView.alpha = 0.0 + } + + // GestureRecognizer 세팅 작업 + private func setupGestureRecognizer() { + // 흐린 부분 탭할 때, 바텀시트를 내리는 TapGesture + let dimmedTap = UITapGestureRecognizer(target: self, action: #selector(dimmedViewTapped(_:))) + dimmedBackView.addGestureRecognizer(dimmedTap) + dimmedBackView.isUserInteractionEnabled = true + + // 스와이프 했을 때, 바텀시트를 내리는 swipeGesture + let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(panGesture)) + swipeGesture.direction = .down + view.addGestureRecognizer(swipeGesture) + } + + // 레이아웃 세팅 + private func setupLayout() { + dimmedBackView.snp.makeConstraints{ + $0.top.equalTo(view.safeAreaLayoutGuide.snp.top) + $0.leading.equalTo(view.safeAreaLayoutGuide.snp.leading) + $0.trailing.equalTo(view.safeAreaLayoutGuide.snp.trailing) + $0.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom) + } + + bottomSheetView.translatesAutoresizingMaskIntoConstraints = false + let topConstant = view.safeAreaInsets.bottom + view.safeAreaLayoutGuide.layoutFrame.height + bottomSheetViewTopConstraint = bottomSheetView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: topConstant) + bottomSheetView.snp.makeConstraints{ + $0.leading.equalTo(view.safeAreaLayoutGuide.snp.leading) + $0.trailing.equalTo(view.safeAreaLayoutGuide.snp.trailing) + $0.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom) + } + bottomSheetViewTopConstraint.isActive = true + + dismissIndicatorView.snp.makeConstraints{ + $0.width.equalTo(102) + $0.height.equalTo(7) + $0.top.equalTo(bottomSheetView.snp.top).inset(12) + $0.centerX.equalTo(bottomSheetView.snp.centerX) + } + } + + func setDateView() { + bottomSheetView.addSubview(dateView) + dateView.snp.makeConstraints{ + $0.top.equalToSuperview().inset(10) + $0.leading.equalToSuperview().inset(10) + $0.trailing.equalToSuperview().inset(10) + } + } + + func reloadDateView(date: Date?) { + if date == nil { return } + let calendar = Calendar.current + dateView.reloadDecorations(forDateComponents: [calendar.dateComponents([.day, .month, .year], from: date!)], animated: true) + } + + func setPurposeTitle() { + bottomSheetView.addSubview(purposeTextField) + purposeTextField.snp.makeConstraints { + $0.top.equalTo(dateView.snp.bottom).inset(-10) + $0.leading.equalToSuperview().inset(10) + $0.trailing.equalToSuperview().inset(10) + $0.height.equalTo(50) + } + } + + func setTotalStackView() { + bottomSheetView.addSubview(totalStackView) + totalStackView.addArrangedSubview(intervalStackView) + totalStackView.addArrangedSubview(dayStackView) + totalStackView.snp.makeConstraints { + $0.top.equalTo(purposeTextField.snp.bottom).inset(-10) + $0.leading.equalToSuperview().inset(10) + $0.trailing.equalToSuperview().inset(10) + } + } + + // MARK: - IntervalBtn + func setEveryDayBtn() { + self.setIntervalBtn("매일", everyDayBtn) + everyDayBtn.addTarget(self, action: #selector(clickedEveryDay), for: .touchUpInside) + } + + func setThreeDaysBtn() { + self.setIntervalBtn("3일", threeDaysBtn) + threeDaysBtn.addTarget(self, action: #selector(clickedThreeDays), for: .touchUpInside) + } + + func setFiveDaysBtn() { + self.setIntervalBtn("5일", fiveDaysBtn) + fiveDaysBtn.addTarget(self, action: #selector(clickedFiveDays), for: .touchUpInside) + } + + func setEveryWeekBtn() { + self.setIntervalBtn("매주", everyWeekBtn) + everyWeekBtn.addTarget(self, action: #selector(clickedEveryWeek), for: .touchUpInside) + } + + // MARK: - DaysBtn + func setSundayBtn() { + self.setDayBtn("일", self.sundayBtn) + sundayBtn.layer.borderColor = UIColor.red.cgColor + sundayBtn.setTitleColor(.red, for: .normal) + sundayBtn.addTarget(self, action: #selector(clickedSunday), for: .touchUpInside) + } + + func setMondayBtn() { + self.setDayBtn("월", self.mondayBtn) + mondayBtn.addTarget(self, action: #selector(clickedMonday), for: .touchUpInside) + } + + func setTuesdayBtn() { + self.setDayBtn("화", self.tuesdayBtn) + tuesdayBtn.addTarget(self, action: #selector(clickedTuesday), for: .touchUpInside) + } + + func setWednesdayBtn() { + self.setDayBtn("수", self.wednesdayBtn) + wednesdayBtn.addTarget(self, action: #selector(clickedWednesday), for: .touchUpInside) + } + + func setThursdayBtn() { + self.setDayBtn("목", self.thursdayBtn) + thursdayBtn.addTarget(self, action: #selector(clickedThursday), for: .touchUpInside) + } + + func setFridayBtn() { + self.setDayBtn("금", self.fridayBtn) + fridayBtn.addTarget(self, action: #selector(clickedFriday), for: .touchUpInside) + } + + func setSaturdayBtn() { + self.setDayBtn("토", self.saturdayBtn) + saturdayBtn.layer.borderColor = UIColor.blue.cgColor + saturdayBtn.setTitleColor(.blue, for: .normal) + saturdayBtn.addTarget(self, action: #selector(clickedSaturday), for: .touchUpInside) + } + + func setSaveBtn() { + bottomSheetView.addSubview(saveBtn) + saveBtn.snp.makeConstraints { + $0.top.equalTo(totalStackView.snp.bottom).inset(-10) + $0.leading.equalToSuperview().inset(10) + $0.trailing.equalToSuperview().inset(10) + $0.bottom.equalToSuperview() + $0.height.equalTo(50) + } + saveBtn.addTarget(self, action: #selector(clickedSaveBtn), for: .touchUpInside) + } + + func setIntervalBtn(_ title: String, _ btn: UIButton) { + btn.setTitle(title, for: .normal) + btn.setTitleColor(.black, for: .normal) + btn.layer.cornerRadius = 10 + btn.layer.borderWidth = 1 + btn.snp.makeConstraints{ + $0.width.equalTo(80) + } + } + + func setDayBtn(_ title: String, _ btn: UIButton) { + btn.setTitle(title, for: .normal) + btn.setTitleColor(.black, for: .normal) + btn.layer.cornerRadius = 10 + btn.layer.borderWidth = 1 + btn.snp.makeConstraints{ + $0.width.equalTo(40) + } + } + + // 바텀 시트 표출 애니메이션 + private func showBottomSheet() { + let safeAreaHeight: CGFloat = view.safeAreaLayoutGuide.layoutFrame.height + let bottomPadding: CGFloat = view.safeAreaInsets.bottom + + bottomSheetViewTopConstraint.constant = (safeAreaHeight + bottomPadding) - bottomHeight + + UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: { + self.dimmedBackView.alpha = 0.5 + self.view.layoutIfNeeded() + }, completion: nil) + } + + // 바텀 시트 사라지는 애니메이션 + private func hideBottomSheetAndGoBack() { + let safeAreaHeight = view.safeAreaLayoutGuide.layoutFrame.height + let bottomPadding = view.safeAreaInsets.bottom + bottomSheetViewTopConstraint.constant = safeAreaHeight + bottomPadding + UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: { + self.dimmedBackView.alpha = 0.0 + self.view.layoutIfNeeded() + }) { _ in + if self.presentingViewController != nil { + self.dismiss(animated: false, completion: nil) + } + } + } + + // MARK: - @objc + @objc func clickedEveryDay() { + everyDayBtn.backgroundColor = checkedEverDay ? .white : .black + everyDayBtn.setTitleColor(checkedEverDay ? .black : .white, for: .normal) + checkedEverDay = !checkedEverDay + } + + @objc func clickedThreeDays() { + threeDaysBtn.backgroundColor = checkedThreeDays ? .white : .black + threeDaysBtn.setTitleColor(checkedThreeDays ? .black : .white, for: .normal) + checkedThreeDays = !checkedThreeDays + } + + @objc func clickedFiveDays() { + fiveDaysBtn.backgroundColor = checkedFiveDays ? .white : .black + fiveDaysBtn.setTitleColor(checkedFiveDays ? .black : .white, for: .normal) + checkedFiveDays = !checkedFiveDays + } + + @objc func clickedEveryWeek() { + everyWeekBtn.backgroundColor = checkedEverWeek ? .white : .black + everyWeekBtn.setTitleColor(checkedEverWeek ? .black : .white, for: .normal) + checkedEverWeek = !checkedEverWeek + + dayStackView.isHidden = !dayStackView.isHidden + bottomHeight = (dayStackView.isHidden == false) ? 660 : 620 + showBottomSheet() + } + + @objc func clickedSunday() { + sundayBtn.backgroundColor = checkedSunday ? .white : .red + sundayBtn.setTitleColor(checkedSunday ? .red : .white, for: .normal) + checkedSunday = !checkedSunday + } + + @objc func clickedMonday() { + mondayBtn.backgroundColor = checkedMonday ? .white : .black + mondayBtn.setTitleColor(checkedMonday ? .black : .white, for: .normal) + checkedMonday = !checkedMonday + } + + @objc func clickedTuesday() { + tuesdayBtn.backgroundColor = checkedTuesday ? .white : .black + tuesdayBtn.setTitleColor(checkedTuesday ? .black : .white, for: .normal) + checkedTuesday = !checkedTuesday + } + + @objc func clickedWednesday() { + wednesdayBtn.backgroundColor = checkedWednesday ? .white : .black + wednesdayBtn.setTitleColor(checkedWednesday ? .black : .white, for: .normal) + checkedWednesday = !checkedWednesday + } + + @objc func clickedThursday() { + thursdayBtn.backgroundColor = checkedThursday ? .white : .black + thursdayBtn.setTitleColor(checkedThursday ? .black : .white, for: .normal) + checkedThursday = !checkedThursday + } + + @objc func clickedFriday() { + fridayBtn.backgroundColor = checkedFridaay ? .white : .black + fridayBtn.setTitleColor(checkedFridaay ? .black : .white, for: .normal) + checkedFridaay = !checkedFridaay + } + + @objc func clickedSaturday() { + saturdayBtn.backgroundColor = checkedSaturday ? .white : .blue + saturdayBtn.setTitleColor(checkedSaturday ? .blue : .white, for: .normal) + checkedSaturday = !checkedSaturday + } + + @objc func clickedSaveBtn() { + //save + } + + // UITapGestureRecognizer 연결 함수 부분 + @objc private func dimmedViewTapped(_ tapRecognizer: UITapGestureRecognizer) { + hideBottomSheetAndGoBack() + } + + // UISwipeGestureRecognizer 연결 함수 부분 + @objc func panGesture(_ recognizer: UISwipeGestureRecognizer) { + if recognizer.state == .ended { + switch recognizer.direction { + case .down: + hideBottomSheetAndGoBack() + default: + break + } + } + } +} + +@available(iOS 16.0, *) +extension DiaryCalendarViewController: UICalendarViewDelegate, UICalendarSelectionSingleDateDelegate { + // UICalendarView + func calendarView(_ calendarView: UICalendarView, decorationFor dateComponents: DateComponents) -> UICalendarView.Decoration? { + if let selectedDate = selectedDate, selectedDate == dateComponents { + return .customView { + let label = UILabel() +// label.text = "🐶" + label.textAlignment = .center + return label + } + } + return nil + } + + // 달력에서 날짜 선택했을 경우 + func dateSelection(_ selection: UICalendarSelectionSingleDate, didSelectDate dateComponents: DateComponents?) { + selection.setSelected(dateComponents, animated: true) + selectedDate = dateComponents + reloadDateView(date: Calendar.current.date(from: dateComponents!)) + } +} + +//// btn.addTarget(self, action: #selector(pushCallendar), for: .touchUpInside) +// @objc func pushCallendar() { +// let vc = DiaryCalendarViewController() +// vc.modalPresentationStyle = .overFullScreen +// self.present(vc, animated: false, completion: nil) +// } diff --git a/DiaryApp/Controllers/DiaryCalenderViewController.swift b/DiaryApp/Controllers/DiaryCalenderViewController.swift deleted file mode 100644 index 41e69b3..0000000 --- a/DiaryApp/Controllers/DiaryCalenderViewController.swift +++ /dev/null @@ -1,15 +0,0 @@ -// -// DiaryCalenderViewController.swift -// DiaryApp -// -// Created by (^ㅗ^)7 iMac on 2023/08/28. -// - -import UIKit - -class DiaryCalenderViewController: UIViewController { - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = .systemBackground - } -} From f60182777749ff646e176374a92e18ea347c4711 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Fri, 1 Sep 2023 15:53:39 +0900 Subject: [PATCH 34/42] =?UTF-8?q?[FEAT]:=20*.pbxproj=20Avoid=20Merge=20Con?= =?UTF-8?q?flict=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..36bbda7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.pbxproj binary merge=union + From 1da1b003b836933bc28079aadd43f39e753436c8 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Fri, 1 Sep 2023 16:30:24 +0900 Subject: [PATCH 35/42] =?UTF-8?q?[STYLE]:=20Nslayout=20=EC=BD=94=EB=93=9C?= =?UTF-8?q?=20->=20Snapkit=EC=9C=BC=EB=A1=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp/Controllers/HomeViewController.swift | 11 +++++----- DiaryApp/Views/Cells/HomeFeedCell.swift | 21 ++++++++----------- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index a54be2d..76ba51e 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -5,6 +5,7 @@ // Created by (^ㅗ^)7 iMac on 2023/08/28. // +import SnapKit import UIKit enum Const { @@ -62,12 +63,10 @@ class HomeViewController: UIViewController { private func configureLayout() { view.addSubview(collectionView) - NSLayoutConstraint.activate([ - collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), - collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), - collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), - collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20), - ]) + collectionView.snp.makeConstraints { make in + make.top.leading.trailing.equalTo(view.safeAreaLayoutGuide) + make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-20) + } } private func addSearchBar() { diff --git a/DiaryApp/Views/Cells/HomeFeedCell.swift b/DiaryApp/Views/Cells/HomeFeedCell.swift index 0b2bdc4..248bd37 100644 --- a/DiaryApp/Views/Cells/HomeFeedCell.swift +++ b/DiaryApp/Views/Cells/HomeFeedCell.swift @@ -5,6 +5,7 @@ // Created by (^ㅗ^)7 iMac on 2023/08/28. // +import SnapKit import UIKit final class HomeFeedCell: UICollectionViewCell { @@ -29,17 +30,13 @@ final class HomeFeedCell: UICollectionViewCell { self.weatherImage.layer.cornerRadius = CGFloat(self.sizeWidth / 2) self.myView.addSubview(self.weatherImage) - - NSLayoutConstraint.activate([ - self.myView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor), - self.myView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor), - self.myView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), - self.myView.topAnchor.constraint(equalTo: self.contentView.topAnchor), - - self.weatherImage.trailingAnchor.constraint(equalTo: self.myView.trailingAnchor, constant: -30), - self.weatherImage.bottomAnchor.constraint(equalTo: self.myView.bottomAnchor, constant: -30), - self.weatherImage.heightAnchor.constraint(equalToConstant: self.sizeWidth), - self.weatherImage.widthAnchor.constraint(equalToConstant: self.sizeWidth), - ]) + self.myView.snp.makeConstraints { make in + make.top.bottom.leading.trailing.equalTo(contentView) + } + + self.weatherImage.snp.makeConstraints { make in + make.trailing.bottom.equalTo(self.myView).offset(-30) + make.height.width.equalTo(self.sizeWidth) + } } } From a873dd0f2a20d1896491e288042be21573f5b4cb Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Fri, 1 Sep 2023 17:11:41 +0900 Subject: [PATCH 36/42] =?UTF-8?q?[FEAT]:=20=ED=8C=8C=EC=9D=B4=EC=96=B4?= =?UTF-8?q?=EB=B2=A0=EC=9D=B4=EC=8A=A4=20=EC=9E=84=ED=8F=AC=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 41 +++++++ .../xcshareddata/swiftpm/Package.resolved | 108 ++++++++++++++++++ DiaryApp/Resources/AppDelegate.swift | 1 + 3 files changed, 150 insertions(+) diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 9e34023..2df2414 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -34,6 +34,10 @@ 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3B92A9CAD60003052D3 /* Weather.swift */; }; 4E98A3BD2A9CB918003052D3 /* CustomCollectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */; }; 4E98A3C12A9CCFB8003052D3 /* CustomImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */; }; + 4EA8081E2AA1D41100A4D465 /* FirebaseAuth in Frameworks */ = {isa = PBXBuildFile; productRef = 4EA8081D2AA1D41100A4D465 /* FirebaseAuth */; }; + 4EA808202AA1D41100A4D465 /* FirebaseDatabase in Frameworks */ = {isa = PBXBuildFile; productRef = 4EA8081F2AA1D41100A4D465 /* FirebaseDatabase */; }; + 4EA808222AA1D41100A4D465 /* FirebaseFirestore in Frameworks */ = {isa = PBXBuildFile; productRef = 4EA808212AA1D41100A4D465 /* FirebaseFirestore */; }; + 4EA808242AA1D41100A4D465 /* FirebaseStorage in Frameworks */ = {isa = PBXBuildFile; productRef = 4EA808232AA1D41100A4D465 /* FirebaseStorage */; }; FF0F824A2AA0D01C005CFB57 /* DiaryCalendarViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF0F82492AA0D01C005CFB57 /* DiaryCalendarViewController.swift */; }; /* End PBXBuildFile section */ @@ -74,7 +78,11 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 4EA808202AA1D41100A4D465 /* FirebaseDatabase in Frameworks */, + 4EA808222AA1D41100A4D465 /* FirebaseFirestore in Frameworks */, 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */, + 4EA808242AA1D41100A4D465 /* FirebaseStorage in Frameworks */, + 4EA8081E2AA1D41100A4D465 /* FirebaseAuth in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -190,6 +198,10 @@ name = DiaryApp; packageProductDependencies = ( 4E6138AF2A9EEF50003A2B37 /* SnapKit */, + 4EA8081D2AA1D41100A4D465 /* FirebaseAuth */, + 4EA8081F2AA1D41100A4D465 /* FirebaseDatabase */, + 4EA808212AA1D41100A4D465 /* FirebaseFirestore */, + 4EA808232AA1D41100A4D465 /* FirebaseStorage */, ); productName = DiaryApp; productReference = 4E98A38B2A9CA57B003052D3 /* DiaryApp.app */; @@ -221,6 +233,7 @@ mainGroup = 4E98A3822A9CA57B003052D3; packageReferences = ( 4E6138AE2A9EEF50003A2B37 /* XCRemoteSwiftPackageReference "SnapKit" */, + 4EA8081C2AA1D41100A4D465 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */, ); productRefGroup = 4E98A38C2A9CA57B003052D3 /* Products */; projectDirPath = ""; @@ -481,6 +494,14 @@ minimumVersion = 5.0.0; }; }; + 4EA8081C2AA1D41100A4D465 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/firebase/firebase-ios-sdk.git"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 10.0.0; + }; + }; /* End XCRemoteSwiftPackageReference section */ /* Begin XCSwiftPackageProductDependency section */ @@ -489,6 +510,26 @@ package = 4E6138AE2A9EEF50003A2B37 /* XCRemoteSwiftPackageReference "SnapKit" */; productName = SnapKit; }; + 4EA8081D2AA1D41100A4D465 /* FirebaseAuth */ = { + isa = XCSwiftPackageProductDependency; + package = 4EA8081C2AA1D41100A4D465 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseAuth; + }; + 4EA8081F2AA1D41100A4D465 /* FirebaseDatabase */ = { + isa = XCSwiftPackageProductDependency; + package = 4EA8081C2AA1D41100A4D465 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseDatabase; + }; + 4EA808212AA1D41100A4D465 /* FirebaseFirestore */ = { + isa = XCSwiftPackageProductDependency; + package = 4EA8081C2AA1D41100A4D465 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseFirestore; + }; + 4EA808232AA1D41100A4D465 /* FirebaseStorage */ = { + isa = XCSwiftPackageProductDependency; + package = 4EA8081C2AA1D41100A4D465 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseStorage; + }; /* End XCSwiftPackageProductDependency section */ }; rootObject = 4E98A3832A9CA57B003052D3 /* Project object */; diff --git a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 009c162..49740e1 100644 --- a/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/DiaryApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,104 @@ { "pins" : [ + { + "identity" : "abseil-cpp-binary", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/abseil-cpp-binary.git", + "state" : { + "revision" : "bfc0b6f81adc06ce5121eb23f628473638d67c5c", + "version" : "1.2022062300.0" + } + }, + { + "identity" : "firebase-ios-sdk", + "kind" : "remoteSourceControl", + "location" : "https://github.com/firebase/firebase-ios-sdk.git", + "state" : { + "revision" : "2bfe6abe1014aafe5cf28401708f7d39f9926a76", + "version" : "10.14.0" + } + }, + { + "identity" : "googleappmeasurement", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/GoogleAppMeasurement.git", + "state" : { + "revision" : "03b9beee1a61f62d32c521e172e192a1663a5e8b", + "version" : "10.13.0" + } + }, + { + "identity" : "googledatatransport", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/GoogleDataTransport.git", + "state" : { + "revision" : "aae45a320fd0d11811820335b1eabc8753902a40", + "version" : "9.2.5" + } + }, + { + "identity" : "googleutilities", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/GoogleUtilities.git", + "state" : { + "revision" : "c38ce365d77b04a9a300c31061c5227589e5597b", + "version" : "7.11.5" + } + }, + { + "identity" : "grpc-binary", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/grpc-binary.git", + "state" : { + "revision" : "f1b366129d1125be7db83247e003fc333104b569", + "version" : "1.50.2" + } + }, + { + "identity" : "gtm-session-fetcher", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/gtm-session-fetcher.git", + "state" : { + "revision" : "d415594121c9e8a4f9d79cecee0965cf35e74dbd", + "version" : "3.1.1" + } + }, + { + "identity" : "interop-ios-for-google-sdks", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/interop-ios-for-google-sdks.git", + "state" : { + "revision" : "2d12673670417654f08f5f90fdd62926dc3a2648", + "version" : "100.0.0" + } + }, + { + "identity" : "leveldb", + "kind" : "remoteSourceControl", + "location" : "https://github.com/firebase/leveldb.git", + "state" : { + "revision" : "0706abcc6b0bd9cedfbb015ba840e4a780b5159b", + "version" : "1.22.2" + } + }, + { + "identity" : "nanopb", + "kind" : "remoteSourceControl", + "location" : "https://github.com/firebase/nanopb.git", + "state" : { + "revision" : "819d0a2173aff699fb8c364b6fb906f7cdb1a692", + "version" : "2.30909.0" + } + }, + { + "identity" : "promises", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/promises.git", + "state" : { + "revision" : "e70e889c0196c76d22759eb50d6a0270ca9f1d9e", + "version" : "2.3.1" + } + }, { "identity" : "snapkit", "kind" : "remoteSourceControl", @@ -8,6 +107,15 @@ "revision" : "f222cbdf325885926566172f6f5f06af95473158", "version" : "5.6.0" } + }, + { + "identity" : "swift-protobuf", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-protobuf.git", + "state" : { + "revision" : "cf62cdaea48b77f1a631e5cb3aeda6047c2cba1d", + "version" : "1.23.0" + } } ], "version" : 2 diff --git a/DiaryApp/Resources/AppDelegate.swift b/DiaryApp/Resources/AppDelegate.swift index 580f229..4ebf13a 100644 --- a/DiaryApp/Resources/AppDelegate.swift +++ b/DiaryApp/Resources/AppDelegate.swift @@ -7,6 +7,7 @@ import UIKit + @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { From 116ea1b736372ac20c58332d502f39e7a034b346 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Fri, 1 Sep 2023 17:16:47 +0900 Subject: [PATCH 37/42] =?UTF-8?q?[FEAT]:=20=ED=8C=8C=EC=9D=B4=EC=96=B4?= =?UTF-8?q?=EB=B2=A0=EC=9D=B4=EC=8A=A4=20=EC=97=B0=EB=8F=99=20=ED=99=95?= =?UTF-8?q?=EC=9D=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 4 ++++ DiaryApp/GoogleService-Info.plist | 34 ++++++++++++++++++++++++++++ DiaryApp/Resources/AppDelegate.swift | 3 ++- 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 DiaryApp/GoogleService-Info.plist diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index 2df2414..bfae310 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -38,6 +38,7 @@ 4EA808202AA1D41100A4D465 /* FirebaseDatabase in Frameworks */ = {isa = PBXBuildFile; productRef = 4EA8081F2AA1D41100A4D465 /* FirebaseDatabase */; }; 4EA808222AA1D41100A4D465 /* FirebaseFirestore in Frameworks */ = {isa = PBXBuildFile; productRef = 4EA808212AA1D41100A4D465 /* FirebaseFirestore */; }; 4EA808242AA1D41100A4D465 /* FirebaseStorage in Frameworks */ = {isa = PBXBuildFile; productRef = 4EA808232AA1D41100A4D465 /* FirebaseStorage */; }; + 4EA808262AA1D46800A4D465 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 4EA808252AA1D46800A4D465 /* GoogleService-Info.plist */; }; FF0F824A2AA0D01C005CFB57 /* DiaryCalendarViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF0F82492AA0D01C005CFB57 /* DiaryCalendarViewController.swift */; }; /* End PBXBuildFile section */ @@ -70,6 +71,7 @@ 4E98A3B92A9CAD60003052D3 /* Weather.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Weather.swift; sourceTree = ""; }; 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomCollectionView.swift; sourceTree = ""; }; 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomImageView.swift; sourceTree = ""; }; + 4EA808252AA1D46800A4D465 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; FF0F82492AA0D01C005CFB57 /* DiaryCalendarViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DiaryCalendarViewController.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -126,6 +128,7 @@ 4E98A3B42A9CA7AD003052D3 /* Views */, 4E98A3A42A9CA638003052D3 /* Controllers */, 4E98A39C2A9CA57E003052D3 /* Info.plist */, + 4EA808252AA1D46800A4D465 /* GoogleService-Info.plist */, ); path = DiaryApp; sourceTree = ""; @@ -251,6 +254,7 @@ files = ( 4E98A3982A9CA57E003052D3 /* Assets.xcassets in Resources */, 4E6138C92A9FA164003A2B37 /* LaunchScreen.storyboard in Resources */, + 4EA808262AA1D46800A4D465 /* GoogleService-Info.plist in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/DiaryApp/GoogleService-Info.plist b/DiaryApp/GoogleService-Info.plist new file mode 100644 index 0000000..128a083 --- /dev/null +++ b/DiaryApp/GoogleService-Info.plist @@ -0,0 +1,34 @@ + + + + + CLIENT_ID + 362176913792-tda207b6l1e87ifhcll7sm23qt1f1v7c.apps.googleusercontent.com + REVERSED_CLIENT_ID + com.googleusercontent.apps.362176913792-tda207b6l1e87ifhcll7sm23qt1f1v7c + API_KEY + AIzaSyBCu5uLGUJ_eru0wsQOJNulDzFskaFLHOM + GCM_SENDER_ID + 362176913792 + PLIST_VERSION + 1 + BUNDLE_ID + com.Junwoo.Momo8282.DiaryApp + PROJECT_ID + diaryapp-90713 + STORAGE_BUCKET + diaryapp-90713.appspot.com + IS_ADS_ENABLED + + IS_ANALYTICS_ENABLED + + IS_APPINVITE_ENABLED + + IS_GCM_ENABLED + + IS_SIGNIN_ENABLED + + GOOGLE_APP_ID + 1:362176913792:ios:523d7a190b449e2d006165 + + \ No newline at end of file diff --git a/DiaryApp/Resources/AppDelegate.swift b/DiaryApp/Resources/AppDelegate.swift index 4ebf13a..f86fe25 100644 --- a/DiaryApp/Resources/AppDelegate.swift +++ b/DiaryApp/Resources/AppDelegate.swift @@ -5,12 +5,13 @@ // Created by (^ㅗ^)7 iMac on 2023/08/28. // +import FirebaseCore import UIKit - @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + FirebaseApp.configure() return true } From 99fc0d17ccf15e5d4030755ac284e386555ed0c5 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Fri, 1 Sep 2023 17:38:43 +0900 Subject: [PATCH 38/42] =?UTF-8?q?[MERGE]:=20Feature/NewDiaryVC=20=EB=B3=91?= =?UTF-8?q?=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DiaryCalenderViewController.swift | 15 ++ .../DiaryProgressViewController.swift | 1 + DiaryApp/Controllers/HomeViewController.swift | 20 +- .../Controllers/NewDiaryViewController.swift | 175 +++++++++++++++++- DiaryApp/Resources/SceneDelegate.swift | 21 ++- 5 files changed, 212 insertions(+), 20 deletions(-) create mode 100644 DiaryApp/Controllers/DiaryCalenderViewController.swift diff --git a/DiaryApp/Controllers/DiaryCalenderViewController.swift b/DiaryApp/Controllers/DiaryCalenderViewController.swift new file mode 100644 index 0000000..41e69b3 --- /dev/null +++ b/DiaryApp/Controllers/DiaryCalenderViewController.swift @@ -0,0 +1,15 @@ +// +// DiaryCalenderViewController.swift +// DiaryApp +// +// Created by (^ㅗ^)7 iMac on 2023/08/28. +// + +import UIKit + +class DiaryCalenderViewController: UIViewController { + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .systemBackground + } +} diff --git a/DiaryApp/Controllers/DiaryProgressViewController.swift b/DiaryApp/Controllers/DiaryProgressViewController.swift index 35e523c..502d4e9 100644 --- a/DiaryApp/Controllers/DiaryProgressViewController.swift +++ b/DiaryApp/Controllers/DiaryProgressViewController.swift @@ -84,5 +84,6 @@ extension DiaryProgressViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 10 + } } diff --git a/DiaryApp/Controllers/HomeViewController.swift b/DiaryApp/Controllers/HomeViewController.swift index 76ba51e..1d1bd2f 100644 --- a/DiaryApp/Controllers/HomeViewController.swift +++ b/DiaryApp/Controllers/HomeViewController.swift @@ -11,11 +11,11 @@ import UIKit enum Const { static let itemSize = CGSize(width: 300, height: 550) static let itemSpacing = 46.0 - + static var insetX: CGFloat { (UIScreen.main.bounds.width - Self.itemSize.width) / 2.0 } - + static var collectionViewContentInset: UIEdgeInsets { UIEdgeInsets(top: 0, left: Self.insetX, bottom: 0, right: Self.insetX) } @@ -23,7 +23,7 @@ enum Const { class HomeViewController: UIViewController { private let collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) - + override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground @@ -31,7 +31,7 @@ class HomeViewController: UIViewController { configureLayout() addSearchBar() } - + private let collectionViewFlowLayout: UICollectionViewFlowLayout = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal @@ -40,12 +40,12 @@ class HomeViewController: UIViewController { layout.minimumInteritemSpacing = 0 return layout }() - + private func configureCollectionView() { collectionView.register(HomeFeedCell.self, forCellWithReuseIdentifier: HomeFeedCell.identifier) collectionView.delegate = self collectionView.dataSource = self - + collectionView.isScrollEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = true @@ -56,10 +56,10 @@ class HomeViewController: UIViewController { collectionView.contentInsetAdjustmentBehavior = .never collectionView.contentInset = Const.collectionViewContentInset collectionView.decelerationRate = .fast - + collectionView.collectionViewLayout = collectionViewFlowLayout } - + private func configureLayout() { view.addSubview(collectionView) @@ -68,7 +68,7 @@ class HomeViewController: UIViewController { make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-20) } } - + private func addSearchBar() { let searchController = UISearchController(searchResultsController: nil) searchController.hidesNavigationBarDuringPresentation = false @@ -82,7 +82,7 @@ extension HomeViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3 } - + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeFeedCell.identifier, for: indexPath) as? HomeFeedCell else { return UICollectionViewCell() } cell.backgroundColor = .systemOrange diff --git a/DiaryApp/Controllers/NewDiaryViewController.swift b/DiaryApp/Controllers/NewDiaryViewController.swift index d0092ba..b20b82f 100644 --- a/DiaryApp/Controllers/NewDiaryViewController.swift +++ b/DiaryApp/Controllers/NewDiaryViewController.swift @@ -5,11 +5,184 @@ // Created by (^ㅗ^)7 iMac on 2023/08/28. // +import SnapKit import UIKit class NewDiaryViewController: UIViewController { + let options = ["운동", "식단", "헬스", "크로스핏", "양배추", "닭가슴살", "닭안심살"] + var selectedButton: UIButton? + lazy var pickerView: UIPickerView = { + let pickerView = UIPickerView() + pickerView.delegate = self + pickerView.dataSource = self + return pickerView + }() + + lazy var pickImageButton: UIButton = { + let button = UIButton(type: .system) + button.setImage(UIImage(systemName: "camera"), for: .normal) + button.addTarget(self, action: #selector(pickImage), for: .touchUpInside) + return button + }() + + lazy var textView: UITextView = { + let textView = UITextView() + textView.text = "입력하시요" + textView.layer.borderWidth = 1.0 + textView.layer.borderColor = UIColor.lightGray.cgColor + textView.layer.cornerRadius = 5.0 + return textView + }() + + lazy var button1: UIButton = { + let button = UIButton(type: .system) + button.setTitle("Button 1", for: .normal) + button.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside) + return button + }() + + lazy var button2: UIButton = { + let button = UIButton(type: .system) + button.setTitle("운동", for: .normal) + button.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside) + return button + }() + + lazy var button3: UIButton = { + let button = UIButton(type: .system) + button.setTitle("건강", for: .normal) + button.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside) + return button + }() + + lazy var button4: UIButton = { + let button = UIButton(type: .system) + button.setTitle("식단", for: .normal) + button.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside) + return button + }() + override func viewDidLoad() { super.viewDidLoad() - view.backgroundColor = .systemBackground + view.backgroundColor = .white + view.addSubview(pickImageButton) + view.addSubview(textView) + view.addSubview(button1) + view.addSubview(button2) + view.addSubview(button3) + view.addSubview(button4) + pickImageButton.snp.makeConstraints { make in + make.centerX.equalToSuperview() + // make.centerY.equalToSuperview() + } + textView.snp.makeConstraints { make in + make.top.equalTo(pickImageButton.snp.bottom).offset(100) + make.leading.trailing.equalToSuperview().inset(20) + make.bottom.equalTo(view.safeAreaLayoutGuide).inset(200) + make.height.equalTo(button1).offset(100) + } + button1.snp.makeConstraints { make in + make.bottom.equalTo(textView.snp.bottom).offset(20) + make.trailing.equalTo(textView).inset(20) + make.top.equalTo(textView).offset(150) + } + button2.snp.makeConstraints { make in + make.top.equalTo(button1.snp.bottom).offset(20) + make.leading.equalTo(button1) + } + button3.snp.makeConstraints { make in + make.top.equalTo(button1.snp.bottom).offset(20) + make.leading.equalTo(button2.snp.leading).offset(-100) + } + button4.snp.makeConstraints { make in + make.top.equalTo(button1.snp.bottom).offset(20) + make.leading.equalTo(button2.snp.leading).offset(-200) + } + } + + @objc func button1Tapped() { + presentAlertWithPicker(for: button1) + } + + @objc func button2Tapped() { + presentAlertWithPicker(for: button2) + } + + @objc func button3Tapped() { + presentAlertWithPicker(for: button3) + } + + @objc func button4Tapped() { + presentAlertWithPicker(for: button4) + } + + func presentAlertWithPicker(for button: UIButton) { + selectedButton = button + let alertController = UIAlertController(title: "Select", message: nil, preferredStyle: .alert) + alertController.addTextField { textField in + textField.inputView = self.pickerView + } + let confirmAction = UIAlertAction(title: "수정", style: .default) { [weak self] _ in + guard let self = self else { return } + let textField = alertController.textFields?.first + if textField?.inputView == self.pickerView { + let selectedRow = self.pickerView.selectedRow(inComponent: 0) + let selectedOption = self.options[selectedRow] + button.setTitle(selectedOption, for: .normal) + } else { + // Handle custom input from text field + if let customInput = textField?.text, !customInput.isEmpty { + button.setTitle(customInput, for: .normal) + } + } + self.selectedButton = nil + } + let cancelAction = UIAlertAction(title: "취소", style: .cancel) { _ in + self.selectedButton = nil + } + alertController.addAction(confirmAction) + alertController.addAction(cancelAction) + present(alertController, animated: true, completion: nil) + } +} + +extension NewDiaryViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { + @objc func pickImage() { + showImagePicker() + } + + func showImagePicker() { + let imagePicker = UIImagePickerController() + imagePicker.delegate = self + imagePicker.sourceType = .photoLibrary + present(imagePicker, animated: true, completion: nil) + } + + func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { + picker.dismiss(animated: true, completion: nil) + if let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { + let imageView = UIImageView(image: selectedImage) + imageView.contentMode = .scaleAspectFit + view.addSubview(imageView) + imageView.snp.makeConstraints { make in + make.centerX.equalTo(pickImageButton) + make.centerY.equalTo(pickImageButton) + make.width.height.equalTo(300) + } + } + } +} + +extension NewDiaryViewController: UIPickerViewDelegate, UIPickerViewDataSource { + func numberOfComponents(in pickerView: UIPickerView) -> Int { + return 1 + } + + func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + return options.count + } + + func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { + return options[row] } } diff --git a/DiaryApp/Resources/SceneDelegate.swift b/DiaryApp/Resources/SceneDelegate.swift index 298ead0..e86883f 100644 --- a/DiaryApp/Resources/SceneDelegate.swift +++ b/DiaryApp/Resources/SceneDelegate.swift @@ -9,41 +9,44 @@ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? - + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow(windowScene: windowScene) window?.makeKeyAndVisible() - + let tabBarController = TabBarController() - + let tabs: [(root: UIViewController, icon: String)] = [ (HomeViewController(), "house"), (DiaryListViewController(), "list.bullet"), (NewDiaryViewController(), "plus.square"), (DiaryProgressViewController(), "tag"), (ProfileViewController(), "person"), + (DiaryProgressViewController(), "tag"), + (ProfileViewController(), "person"), ] + tabBarController.setViewControllers(tabs.map { root, icon in let navigationController = UINavigationController(rootViewController: root) let tabBarItem = UITabBarItem(title: nil, image: .init(systemName: icon), selectedImage: .init(systemName: "\(icon).fill")) navigationController.tabBarItem = tabBarItem return navigationController }, animated: false) - + tabBarController.tabBar.tintColor = .label tabBarController.tabBar.backgroundColor = .systemBackground window?.rootViewController = tabBarController } - + func sceneDidDisconnect(_ scene: UIScene) {} - + func sceneDidBecomeActive(_ scene: UIScene) {} - + func sceneWillResignActive(_ scene: UIScene) {} - + func sceneWillEnterForeground(_ scene: UIScene) {} - + func sceneDidEnterBackground(_ scene: UIScene) {} } From 616ba0c69417580203d54c9470b96569a16bb260 Mon Sep 17 00:00:00 2001 From: jakkujakku Date: Fri, 1 Sep 2023 17:41:06 +0900 Subject: [PATCH 39/42] =?UTF-8?q?[REMOVE]:=20DirayCalenderViewController?= =?UTF-8?q?=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/DiaryCalenderViewController.swift | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 DiaryApp/Controllers/DiaryCalenderViewController.swift diff --git a/DiaryApp/Controllers/DiaryCalenderViewController.swift b/DiaryApp/Controllers/DiaryCalenderViewController.swift deleted file mode 100644 index 41e69b3..0000000 --- a/DiaryApp/Controllers/DiaryCalenderViewController.swift +++ /dev/null @@ -1,15 +0,0 @@ -// -// DiaryCalenderViewController.swift -// DiaryApp -// -// Created by (^ㅗ^)7 iMac on 2023/08/28. -// - -import UIKit - -class DiaryCalenderViewController: UIViewController { - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = .systemBackground - } -} From 5ca72895c245b3761db905e9d458ca1c404eb50a Mon Sep 17 00:00:00 2001 From: p2glet Date: Fri, 1 Sep 2023 21:52:23 +0900 Subject: [PATCH 40/42] [FEAT] : created FirestoreManager --- DiaryApp/Models/Post.swift | 28 ++++++++++ DiaryApp/Network/FirestoreManager.swift | 71 +++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 DiaryApp/Models/Post.swift create mode 100644 DiaryApp/Network/FirestoreManager.swift diff --git a/DiaryApp/Models/Post.swift b/DiaryApp/Models/Post.swift new file mode 100644 index 0000000..4d9720c --- /dev/null +++ b/DiaryApp/Models/Post.swift @@ -0,0 +1,28 @@ +// +// Post.swift +// DiaryApp +// +// Created by t2023-m0056 on 2023/09/01. +// + +import Foundation + +struct Post: Codable { + var content: String? + var goal: String? + var image: String? + var tag: Array + var temperature: String + var weather: String + var weatherIcon: String + + enum CodingKeys: String, CodingKey { + case content + case goal + case image + case tag + case temperature + case weather + case weatherIcon + } +} diff --git a/DiaryApp/Network/FirestoreManager.swift b/DiaryApp/Network/FirestoreManager.swift new file mode 100644 index 0000000..5e6060e --- /dev/null +++ b/DiaryApp/Network/FirestoreManager.swift @@ -0,0 +1,71 @@ +// +// FirestoreManager.swift +// DiaryApp +// +// Created by t2023-m0056 on 2023/09/01. +// + +import Foundation +import FirebaseFirestore + +final class FirestoreService { + let db = Firestore.firestore() + + func getPostData(completion: @escaping ([Post]?) -> Void) { + var names: [[String:Any]] = [[:]] + var post: [Post]? + + db.collection("Post").getDocuments { (querySnapshot, error) in + if let error = error { + print("Error getting documents: \(error)") + completion(post) // 호출하는 쪽에 빈 배열 전달 + return + } + for document in querySnapshot!.documents { + names.append(document.data()) + } + names.remove(at: 0) + post = self.dictionaryToObject(objectType: Post.self, dictionary: names) + completion(post) // 성공 시 이름 배열 전달 + } + } + + func addPostDocument(content: String, goal: String, image: String, tag: Array, temperature: String, weather: String, weatherIcon: String, completion: @escaping (String) -> Void) { + // Add a new document with a generated ID + db.collection("Info").document(goal).setData([ + "content": content, + "goal": goal, + "image": image, + "tag": tag, + "temperature": temperature, + "weather": weather, + "weatherIcon": weatherIcon, + ]) { err in + if let err = err { + print("Error adding document: \(err)") + } else { + completion("Post Document added") + } + } + } +} + +extension FirestoreService { + func dictionaryToObject(objectType:T.Type,dictionary:[[String:Any]]) -> [T]? { + + guard let dictionaries = try? JSONSerialization.data(withJSONObject: dictionary) else { return nil } + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + guard let objects = try? decoder.decode([T].self, from: dictionaries) else { return nil } + return objects + } + + func dicToObject(objectType:T.Type,dictionary:[String:Any]) -> T? { + + guard let dictionaries = try? JSONSerialization.data(withJSONObject: dictionary) else { return nil } + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + guard let objects = try? decoder.decode(T.self, from: dictionaries) else { return nil } + return objects + } +} From 33f5e0277a7ed811172865ed56227dbec9065375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=B5=E1=86=B7=E1=84=80=E1=85=B5=E1=84=92?= =?UTF-8?q?=E1=85=A7=E1=86=AB?= Date: Sun, 3 Sep 2023 18:47:42 +0900 Subject: [PATCH 41/42] =?UTF-8?q?=EB=82=A0=EC=94=A8=20ui=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DiaryApp.xcodeproj/project.pbxproj | 90 + DiaryApp.xcworkspace/contents.xcworkspacedata | 10 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/swiftpm/Package.resolved | 122 + .../Controllers/NewDiaryViewController.swift | 98 +- .../Controllers/Weather/WeatherManager.swift | 61 + .../Controllers/Weather/WeatherResponse.swift | 24 + DiaryApp/Controllers/weatherAPI.plist | 8 + Podfile | 11 + Podfile.lock | 20 + Pods/Alamofire/LICENSE | 19 + Pods/Alamofire/README.md | 227 ++ Pods/Alamofire/Source/AFError.swift | 874 +++++++ Pods/Alamofire/Source/Alamofire.swift | 40 + Pods/Alamofire/Source/AlamofireExtended.swift | 61 + .../Source/AuthenticationInterceptor.swift | 403 ++++ .../Source/CachedResponseHandler.swift | 107 + Pods/Alamofire/Source/Combine.swift | 655 ++++++ Pods/Alamofire/Source/Concurrency.swift | 832 +++++++ .../Source/DispatchQueue+Alamofire.swift | 37 + Pods/Alamofire/Source/EventMonitor.swift | 907 ++++++++ Pods/Alamofire/Source/HTTPHeaders.swift | 452 ++++ Pods/Alamofire/Source/HTTPMethod.swift | 56 + Pods/Alamofire/Source/MultipartFormData.swift | 601 +++++ Pods/Alamofire/Source/MultipartUpload.swift | 89 + .../Source/NetworkReachabilityManager.swift | 301 +++ Pods/Alamofire/Source/Notifications.swift | 115 + .../Source/OperationQueue+Alamofire.swift | 49 + Pods/Alamofire/Source/ParameterEncoder.swift | 213 ++ Pods/Alamofire/Source/ParameterEncoding.swift | 346 +++ Pods/Alamofire/Source/Protected.swift | 161 ++ Pods/Alamofire/Source/RedirectHandler.swift | 111 + Pods/Alamofire/Source/Request.swift | 2070 +++++++++++++++++ .../Alamofire/Source/RequestCompression.swift | 153 ++ .../Alamofire/Source/RequestInterceptor.swift | 351 +++ Pods/Alamofire/Source/RequestTaskMap.swift | 149 ++ Pods/Alamofire/Source/Response.swift | 453 ++++ .../Source/ResponseSerialization.swift | 1270 ++++++++++ Pods/Alamofire/Source/Result+Alamofire.swift | 120 + Pods/Alamofire/Source/RetryPolicy.swift | 430 ++++ .../Source/ServerTrustEvaluation.swift | 772 ++++++ Pods/Alamofire/Source/Session.swift | 1264 ++++++++++ Pods/Alamofire/Source/SessionDelegate.swift | 355 +++ .../Source/StringEncoding+Alamofire.swift | 55 + ...URLConvertible+URLRequestConvertible.swift | 105 + .../Source/URLEncodedFormEncoder.swift | 1083 +++++++++ .../Source/URLRequest+Alamofire.swift | 39 + .../URLSessionConfiguration+Alamofire.swift | 46 + Pods/Alamofire/Source/Validation.swift | 302 +++ Pods/Manifest.lock | 20 + Pods/Pods.xcodeproj/project.pbxproj | 939 ++++++++ Pods/SwiftyJSON/LICENSE | 21 + Pods/SwiftyJSON/README.md | 560 +++++ .../Source/SwiftyJSON/SwiftyJSON.swift | 1401 +++++++++++ .../Alamofire/Alamofire-Info.plist | 26 + .../Alamofire/Alamofire-dummy.m | 5 + .../Alamofire/Alamofire-prefix.pch | 12 + .../Alamofire/Alamofire-umbrella.h | 16 + .../Alamofire/Alamofire.debug.xcconfig | 15 + .../Alamofire/Alamofire.modulemap | 6 + .../Alamofire/Alamofire.release.xcconfig | 15 + .../Pods-DiaryApp/Pods-DiaryApp-Info.plist | 26 + .../Pods-DiaryApp-acknowledgements.markdown | 51 + .../Pods-DiaryApp-acknowledgements.plist | 89 + .../Pods-DiaryApp/Pods-DiaryApp-dummy.m | 5 + ...pp-frameworks-Debug-input-files.xcfilelist | 3 + ...p-frameworks-Debug-output-files.xcfilelist | 2 + ...-frameworks-Release-input-files.xcfilelist | 3 + ...frameworks-Release-output-files.xcfilelist | 2 + .../Pods-DiaryApp/Pods-DiaryApp-frameworks.sh | 188 ++ .../Pods-DiaryApp/Pods-DiaryApp-umbrella.h | 16 + .../Pods-DiaryApp.debug.xcconfig | 15 + .../Pods-DiaryApp/Pods-DiaryApp.modulemap | 6 + .../Pods-DiaryApp.release.xcconfig | 15 + .../SwiftyJSON/SwiftyJSON-Info.plist | 26 + .../SwiftyJSON/SwiftyJSON-dummy.m | 5 + .../SwiftyJSON/SwiftyJSON-prefix.pch | 12 + .../SwiftyJSON/SwiftyJSON-umbrella.h | 16 + .../SwiftyJSON/SwiftyJSON.debug.xcconfig | 14 + .../SwiftyJSON/SwiftyJSON.modulemap | 6 + .../SwiftyJSON/SwiftyJSON.release.xcconfig | 14 + 81 files changed, 19664 insertions(+), 11 deletions(-) create mode 100644 DiaryApp.xcworkspace/contents.xcworkspacedata create mode 100644 DiaryApp.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 DiaryApp.xcworkspace/xcshareddata/swiftpm/Package.resolved create mode 100644 DiaryApp/Controllers/Weather/WeatherManager.swift create mode 100644 DiaryApp/Controllers/Weather/WeatherResponse.swift create mode 100644 DiaryApp/Controllers/weatherAPI.plist create mode 100644 Podfile create mode 100644 Podfile.lock create mode 100644 Pods/Alamofire/LICENSE create mode 100644 Pods/Alamofire/README.md create mode 100644 Pods/Alamofire/Source/AFError.swift create mode 100644 Pods/Alamofire/Source/Alamofire.swift create mode 100644 Pods/Alamofire/Source/AlamofireExtended.swift create mode 100644 Pods/Alamofire/Source/AuthenticationInterceptor.swift create mode 100644 Pods/Alamofire/Source/CachedResponseHandler.swift create mode 100644 Pods/Alamofire/Source/Combine.swift create mode 100644 Pods/Alamofire/Source/Concurrency.swift create mode 100644 Pods/Alamofire/Source/DispatchQueue+Alamofire.swift create mode 100644 Pods/Alamofire/Source/EventMonitor.swift create mode 100644 Pods/Alamofire/Source/HTTPHeaders.swift create mode 100644 Pods/Alamofire/Source/HTTPMethod.swift create mode 100644 Pods/Alamofire/Source/MultipartFormData.swift create mode 100644 Pods/Alamofire/Source/MultipartUpload.swift create mode 100644 Pods/Alamofire/Source/NetworkReachabilityManager.swift create mode 100644 Pods/Alamofire/Source/Notifications.swift create mode 100644 Pods/Alamofire/Source/OperationQueue+Alamofire.swift create mode 100644 Pods/Alamofire/Source/ParameterEncoder.swift create mode 100644 Pods/Alamofire/Source/ParameterEncoding.swift create mode 100644 Pods/Alamofire/Source/Protected.swift create mode 100644 Pods/Alamofire/Source/RedirectHandler.swift create mode 100644 Pods/Alamofire/Source/Request.swift create mode 100644 Pods/Alamofire/Source/RequestCompression.swift create mode 100644 Pods/Alamofire/Source/RequestInterceptor.swift create mode 100644 Pods/Alamofire/Source/RequestTaskMap.swift create mode 100644 Pods/Alamofire/Source/Response.swift create mode 100644 Pods/Alamofire/Source/ResponseSerialization.swift create mode 100644 Pods/Alamofire/Source/Result+Alamofire.swift create mode 100644 Pods/Alamofire/Source/RetryPolicy.swift create mode 100644 Pods/Alamofire/Source/ServerTrustEvaluation.swift create mode 100644 Pods/Alamofire/Source/Session.swift create mode 100644 Pods/Alamofire/Source/SessionDelegate.swift create mode 100644 Pods/Alamofire/Source/StringEncoding+Alamofire.swift create mode 100644 Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift create mode 100644 Pods/Alamofire/Source/URLEncodedFormEncoder.swift create mode 100644 Pods/Alamofire/Source/URLRequest+Alamofire.swift create mode 100644 Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift create mode 100644 Pods/Alamofire/Source/Validation.swift create mode 100644 Pods/Manifest.lock create mode 100644 Pods/Pods.xcodeproj/project.pbxproj create mode 100644 Pods/SwiftyJSON/LICENSE create mode 100644 Pods/SwiftyJSON/README.md create mode 100644 Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-Info.plist create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-dummy.m create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-prefix.pch create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-umbrella.h create mode 100644 Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig create mode 100644 Pods/Target Support Files/Alamofire/Alamofire.modulemap create mode 100644 Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.markdown create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.plist create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-dummy.m create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-input-files.xcfilelist create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-output-files.xcfilelist create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-input-files.xcfilelist create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-output-files.xcfilelist create mode 100755 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-umbrella.h create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.debug.xcconfig create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap create mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.release.xcconfig create mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist create mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m create mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch create mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h create mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig create mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap create mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig diff --git a/DiaryApp.xcodeproj/project.pbxproj b/DiaryApp.xcodeproj/project.pbxproj index bfae310..1087db6 100644 --- a/DiaryApp.xcodeproj/project.pbxproj +++ b/DiaryApp.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + 416BCE5008D8A336C839F81F /* Pods_DiaryApp.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6ECBBCC35FC9003BDB3F2719 /* Pods_DiaryApp.framework */; }; + 4E1112492AA45E7A00D4E550 /* weatherAPI.plist in Resources */ = {isa = PBXBuildFile; fileRef = 4E1112482AA45E7A00D4E550 /* weatherAPI.plist */; }; 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550832A9E049100C8A500 /* DiaryListCell.swift */; }; 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */; }; 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */; }; @@ -39,10 +41,14 @@ 4EA808222AA1D41100A4D465 /* FirebaseFirestore in Frameworks */ = {isa = PBXBuildFile; productRef = 4EA808212AA1D41100A4D465 /* FirebaseFirestore */; }; 4EA808242AA1D41100A4D465 /* FirebaseStorage in Frameworks */ = {isa = PBXBuildFile; productRef = 4EA808232AA1D41100A4D465 /* FirebaseStorage */; }; 4EA808262AA1D46800A4D465 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 4EA808252AA1D46800A4D465 /* GoogleService-Info.plist */; }; + 4ED3122E2AA46BA700677EE0 /* WeatherManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED3122D2AA46BA700677EE0 /* WeatherManager.swift */; }; + 4ED312302AA48BFB00677EE0 /* WeatherResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED3122F2AA48BFB00677EE0 /* WeatherResponse.swift */; }; FF0F824A2AA0D01C005CFB57 /* DiaryCalendarViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF0F82492AA0D01C005CFB57 /* DiaryCalendarViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 29E4E142F65D379C5B088A3D /* Pods-DiaryApp.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-DiaryApp.release.xcconfig"; path = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp.release.xcconfig"; sourceTree = ""; }; + 4E1112482AA45E7A00D4E550 /* weatherAPI.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = weatherAPI.plist; sourceTree = ""; }; 4E1550832A9E049100C8A500 /* DiaryListCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiaryListCell.swift; sourceTree = ""; }; 4E1550882A9E0C6500C8A500 /* CustomStackView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomStackView.swift; sourceTree = ""; }; 4E15508A2A9E0DF500C8A500 /* CustomLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomLabel.swift; sourceTree = ""; }; @@ -72,6 +78,10 @@ 4E98A3BC2A9CB918003052D3 /* CustomCollectionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomCollectionView.swift; sourceTree = ""; }; 4E98A3C02A9CCFB8003052D3 /* CustomImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomImageView.swift; sourceTree = ""; }; 4EA808252AA1D46800A4D465 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; + 4ED3122D2AA46BA700677EE0 /* WeatherManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherManager.swift; sourceTree = ""; }; + 4ED3122F2AA48BFB00677EE0 /* WeatherResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherResponse.swift; sourceTree = ""; }; + 6ECBBCC35FC9003BDB3F2719 /* Pods_DiaryApp.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_DiaryApp.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F45C74DA7EACBE351DEA5098 /* Pods-DiaryApp.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-DiaryApp.debug.xcconfig"; path = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp.debug.xcconfig"; sourceTree = ""; }; FF0F82492AA0D01C005CFB57 /* DiaryCalendarViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DiaryCalendarViewController.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -85,6 +95,7 @@ 4E6138B02A9EEF50003A2B37 /* SnapKit in Frameworks */, 4EA808242AA1D41100A4D465 /* FirebaseStorage in Frameworks */, 4EA8081E2AA1D41100A4D465 /* FirebaseAuth in Frameworks */, + 416BCE5008D8A336C839F81F /* Pods_DiaryApp.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -109,6 +120,8 @@ children = ( 4E98A38D2A9CA57B003052D3 /* DiaryApp */, 4E98A38C2A9CA57B003052D3 /* Products */, + 645148A477D85E4A768623AC /* Pods */, + C495D0DD606D22FB491EDCDE /* Frameworks */, ); sourceTree = ""; }; @@ -144,8 +157,10 @@ 4E98A3A92A9CA6F6003052D3 /* ProgressListViewController.swift */, 4E98A3AB2A9CA70B003052D3 /* DiaryListViewController.swift */, 4E98A3AD2A9CA748003052D3 /* DetailDiaryViewController.swift */, + 4ED312312AA48CFA00677EE0 /* Weather */, 4E98A3AF2A9CA762003052D3 /* DiaryProgressViewController.swift */, 4E98A3B52A9CAA16003052D3 /* ProfileViewController.swift */, + 4E1112482AA45E7A00D4E550 /* weatherAPI.plist */, ); path = Controllers; sourceTree = ""; @@ -183,6 +198,32 @@ path = Resources; sourceTree = ""; }; + 4ED312312AA48CFA00677EE0 /* Weather */ = { + isa = PBXGroup; + children = ( + 4ED3122D2AA46BA700677EE0 /* WeatherManager.swift */, + 4ED3122F2AA48BFB00677EE0 /* WeatherResponse.swift */, + ); + path = Weather; + sourceTree = ""; + }; + 645148A477D85E4A768623AC /* Pods */ = { + isa = PBXGroup; + children = ( + F45C74DA7EACBE351DEA5098 /* Pods-DiaryApp.debug.xcconfig */, + 29E4E142F65D379C5B088A3D /* Pods-DiaryApp.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + C495D0DD606D22FB491EDCDE /* Frameworks */ = { + isa = PBXGroup; + children = ( + 6ECBBCC35FC9003BDB3F2719 /* Pods_DiaryApp.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -190,9 +231,11 @@ isa = PBXNativeTarget; buildConfigurationList = 4E98A39F2A9CA57E003052D3 /* Build configuration list for PBXNativeTarget "DiaryApp" */; buildPhases = ( + 8DFF7EF8445834A3CB02DCFD /* [CP] Check Pods Manifest.lock */, 4E98A3872A9CA57B003052D3 /* Sources */, 4E98A3882A9CA57B003052D3 /* Frameworks */, 4E98A3892A9CA57B003052D3 /* Resources */, + FA407FDDD7445C4F63B1AD88 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -252,6 +295,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 4E1112492AA45E7A00D4E550 /* weatherAPI.plist in Resources */, 4E98A3982A9CA57E003052D3 /* Assets.xcassets in Resources */, 4E6138C92A9FA164003A2B37 /* LaunchScreen.storyboard in Resources */, 4EA808262AA1D46800A4D465 /* GoogleService-Info.plist in Resources */, @@ -260,6 +304,48 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 8DFF7EF8445834A3CB02DCFD /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-DiaryApp-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + FA407FDDD7445C4F63B1AD88 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 4E98A3872A9CA57B003052D3 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -272,6 +358,7 @@ 4E98A3912A9CA57B003052D3 /* SceneDelegate.swift in Sources */, 4E98A3A32A9CA634003052D3 /* HomeViewController.swift in Sources */, 4E98A3A82A9CA6B6003052D3 /* EditDiaryViewController.swift in Sources */, + 4ED312302AA48BFB00677EE0 /* WeatherResponse.swift in Sources */, 4E1550842A9E049100C8A500 /* DiaryListCell.swift in Sources */, 4E6138C02A9F9E8B003A2B37 /* DiaryListThumbnailCell.swift in Sources */, 4E98A3BA2A9CAD60003052D3 /* Weather.swift in Sources */, @@ -279,6 +366,7 @@ 4E7A15062AA0BFA1005FCD9C /* ProgressTagCell.swift in Sources */, 4E7A15042AA0A9C8005FCD9C /* ProgressListCell.swift in Sources */, 4E6138C12A9F9E8B003A2B37 /* DiaryProgressCell.swift in Sources */, + 4ED3122E2AA46BA700677EE0 /* WeatherManager.swift in Sources */, 4E98A3B62A9CAA16003052D3 /* ProfileViewController.swift in Sources */, 4E15508B2A9E0DF500C8A500 /* CustomLabel.swift in Sources */, 4E1550892A9E0C6500C8A500 /* CustomStackView.swift in Sources */, @@ -412,6 +500,7 @@ }; 4E98A3A02A9CA57E003052D3 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = F45C74DA7EACBE351DEA5098 /* Pods-DiaryApp.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -440,6 +529,7 @@ }; 4E98A3A12A9CA57E003052D3 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 29E4E142F65D379C5B088A3D /* Pods-DiaryApp.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; diff --git a/DiaryApp.xcworkspace/contents.xcworkspacedata b/DiaryApp.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..fe90328 --- /dev/null +++ b/DiaryApp.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/DiaryApp.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/DiaryApp.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/DiaryApp.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/DiaryApp.xcworkspace/xcshareddata/swiftpm/Package.resolved b/DiaryApp.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..49740e1 --- /dev/null +++ b/DiaryApp.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,122 @@ +{ + "pins" : [ + { + "identity" : "abseil-cpp-binary", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/abseil-cpp-binary.git", + "state" : { + "revision" : "bfc0b6f81adc06ce5121eb23f628473638d67c5c", + "version" : "1.2022062300.0" + } + }, + { + "identity" : "firebase-ios-sdk", + "kind" : "remoteSourceControl", + "location" : "https://github.com/firebase/firebase-ios-sdk.git", + "state" : { + "revision" : "2bfe6abe1014aafe5cf28401708f7d39f9926a76", + "version" : "10.14.0" + } + }, + { + "identity" : "googleappmeasurement", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/GoogleAppMeasurement.git", + "state" : { + "revision" : "03b9beee1a61f62d32c521e172e192a1663a5e8b", + "version" : "10.13.0" + } + }, + { + "identity" : "googledatatransport", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/GoogleDataTransport.git", + "state" : { + "revision" : "aae45a320fd0d11811820335b1eabc8753902a40", + "version" : "9.2.5" + } + }, + { + "identity" : "googleutilities", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/GoogleUtilities.git", + "state" : { + "revision" : "c38ce365d77b04a9a300c31061c5227589e5597b", + "version" : "7.11.5" + } + }, + { + "identity" : "grpc-binary", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/grpc-binary.git", + "state" : { + "revision" : "f1b366129d1125be7db83247e003fc333104b569", + "version" : "1.50.2" + } + }, + { + "identity" : "gtm-session-fetcher", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/gtm-session-fetcher.git", + "state" : { + "revision" : "d415594121c9e8a4f9d79cecee0965cf35e74dbd", + "version" : "3.1.1" + } + }, + { + "identity" : "interop-ios-for-google-sdks", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/interop-ios-for-google-sdks.git", + "state" : { + "revision" : "2d12673670417654f08f5f90fdd62926dc3a2648", + "version" : "100.0.0" + } + }, + { + "identity" : "leveldb", + "kind" : "remoteSourceControl", + "location" : "https://github.com/firebase/leveldb.git", + "state" : { + "revision" : "0706abcc6b0bd9cedfbb015ba840e4a780b5159b", + "version" : "1.22.2" + } + }, + { + "identity" : "nanopb", + "kind" : "remoteSourceControl", + "location" : "https://github.com/firebase/nanopb.git", + "state" : { + "revision" : "819d0a2173aff699fb8c364b6fb906f7cdb1a692", + "version" : "2.30909.0" + } + }, + { + "identity" : "promises", + "kind" : "remoteSourceControl", + "location" : "https://github.com/google/promises.git", + "state" : { + "revision" : "e70e889c0196c76d22759eb50d6a0270ca9f1d9e", + "version" : "2.3.1" + } + }, + { + "identity" : "snapkit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/SnapKit/SnapKit.git", + "state" : { + "revision" : "f222cbdf325885926566172f6f5f06af95473158", + "version" : "5.6.0" + } + }, + { + "identity" : "swift-protobuf", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-protobuf.git", + "state" : { + "revision" : "cf62cdaea48b77f1a631e5cb3aeda6047c2cba1d", + "version" : "1.23.0" + } + } + ], + "version" : 2 +} diff --git a/DiaryApp/Controllers/NewDiaryViewController.swift b/DiaryApp/Controllers/NewDiaryViewController.swift index b20b82f..d5371d3 100644 --- a/DiaryApp/Controllers/NewDiaryViewController.swift +++ b/DiaryApp/Controllers/NewDiaryViewController.swift @@ -7,6 +7,7 @@ import SnapKit import UIKit +import Alamofire class NewDiaryViewController: UIViewController { let options = ["운동", "식단", "헬스", "크로스핏", "양배추", "닭가슴살", "닭안심살"] @@ -17,14 +18,14 @@ class NewDiaryViewController: UIViewController { pickerView.dataSource = self return pickerView }() - + lazy var pickImageButton: UIButton = { let button = UIButton(type: .system) button.setImage(UIImage(systemName: "camera"), for: .normal) button.addTarget(self, action: #selector(pickImage), for: .touchUpInside) return button }() - + lazy var textView: UITextView = { let textView = UITextView() textView.text = "입력하시요" @@ -33,37 +34,55 @@ class NewDiaryViewController: UIViewController { textView.layer.cornerRadius = 5.0 return textView }() - + lazy var button1: UIButton = { let button = UIButton(type: .system) button.setTitle("Button 1", for: .normal) button.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside) return button }() - + lazy var button2: UIButton = { let button = UIButton(type: .system) button.setTitle("운동", for: .normal) button.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside) return button }() - + lazy var button3: UIButton = { let button = UIButton(type: .system) button.setTitle("건강", for: .normal) button.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside) return button }() - + lazy var button4: UIButton = { let button = UIButton(type: .system) button.setTitle("식단", for: .normal) button.addTarget(self, action: #selector(button1Tapped), for: .touchUpInside) return button }() + + let weatherIconImageView: UIImageView = { + let imageView = UIImageView() + return imageView + }() + + let weatherDescriptionLabel: UILabel = { + let label = UILabel() + return label + }() + + let temperatureLabel: UILabel = { + let label = UILabel() + return label + }() + + override func viewDidLoad() { super.viewDidLoad() + view.backgroundColor = .white view.addSubview(pickImageButton) view.addSubview(textView) @@ -71,6 +90,13 @@ class NewDiaryViewController: UIViewController { view.addSubview(button2) view.addSubview(button3) view.addSubview(button4) + view.addSubview(weatherIconImageView) + view.addSubview(weatherDescriptionLabel) + view.addSubview(temperatureLabel) + + fetchAndDisplayWeather() + + pickImageButton.snp.makeConstraints { make in make.centerX.equalToSuperview() // make.centerY.equalToSuperview() @@ -98,24 +124,42 @@ class NewDiaryViewController: UIViewController { make.top.equalTo(button1.snp.bottom).offset(20) make.leading.equalTo(button2.snp.leading).offset(-200) } + weatherIconImageView.snp.makeConstraints { make in +// make.centerX.equalToSuperview() + make.top.equalTo(button4.snp.bottom).offset(20) + make.leading.equalTo(button1) + make.width.height.equalTo(50) + + } + + weatherDescriptionLabel.snp.makeConstraints { make in + make.centerX.equalToSuperview() + make.top.equalTo(button4.snp.bottom).offset(10) + } + + temperatureLabel.snp.makeConstraints { make in + make.centerX.equalToSuperview() + make.top.equalTo(weatherDescriptionLabel.snp.bottom).offset(5) + } } - + @objc func button1Tapped() { presentAlertWithPicker(for: button1) } - + @objc func button2Tapped() { presentAlertWithPicker(for: button2) } - + @objc func button3Tapped() { presentAlertWithPicker(for: button3) } - + @objc func button4Tapped() { presentAlertWithPicker(for: button4) } - + + func presentAlertWithPicker(for button: UIButton) { selectedButton = button let alertController = UIAlertController(title: "Select", message: nil, preferredStyle: .alert) @@ -144,6 +188,38 @@ class NewDiaryViewController: UIViewController { alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } + func fetchAndDisplayWeather() { + let city = "Busan" + WeatherManager.shared.fetchWeather(for: city) { result in + switch result { + case .success(let weatherData): + // 날씨 정보를 받아와 UI에 표시 + DispatchQueue.main.async { + self.weatherDescriptionLabel.text = weatherData.description + self.temperatureLabel.text = "\(weatherData.temperature) °C" + + // 아이콘 이미지를 표시 + if let iconUrl = URL(string: weatherData.iconUrl) { + DispatchQueue.global().async { + + if let imageData = try? Data(contentsOf: iconUrl), + let iconImage = UIImage(data: imageData) { + DispatchQueue.main.async { + print("###이미지 다운로드 완ㄹ") + + self.weatherIconImageView.image = iconImage + } + } else { + print("이미지 다운로드 변환 실패 ###") + } + } + } + } + case .failure(let error): + print("###날씨 정보 가져오기 실패: \(error)") + } + } + } } extension NewDiaryViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { diff --git a/DiaryApp/Controllers/Weather/WeatherManager.swift b/DiaryApp/Controllers/Weather/WeatherManager.swift new file mode 100644 index 0000000..71e05e4 --- /dev/null +++ b/DiaryApp/Controllers/Weather/WeatherManager.swift @@ -0,0 +1,61 @@ +// +// WeatherManager.swift +// DiaryApp +// +// Created by 김기현 on 2023/09/03. +// + +import Foundation +import Alamofire + +class WeatherManager { + static let shared = WeatherManager() + + private init() {} + + private let apiKey = "e8aeafe9abc4ec56d53a28782b1991f8" + private let baseUrl = "https://api.openweathermap.org/data/2.5/weather" // HTTPS 사용 + + func fetchWeather(for city: String, completion: @escaping (Result) -> Void) { + let parameters: [String: Any] = [ + "q": city, + "APPID": apiKey + ] + + // Alamofire를 사용하여 GET 요청을 보냅니다. + AF.request(baseUrl, method: .get, parameters: parameters) + .validate() + .responseJSON { response in + switch response.result { + case .success(let value): + if let weatherResponse = WeatherResponse(json: value) { + // 이미지 데이터 가져오기 + self.fetchWeatherIcon(for: weatherResponse.iconUrl) { imageData in + var weatherResponseWithIcon = weatherResponse + weatherResponseWithIcon.iconImageData = imageData + completion(.success(weatherResponseWithIcon)) + } + } else { + print("###날씨 데이터 파싱 실패ㅜㅜ") + } + case .failure(let error): + completion(.failure(error)) + } + } + } + + private func fetchWeatherIcon(for iconUrl: String, completion: @escaping (Data?) -> Void) { + if let url = URL(string: iconUrl) { + AF.request(url).responseData { response in + switch response.result { + case .success(let data): + completion(data) + case .failure(_): + completion(nil) + } + } + } else { + completion(nil) + } + } +} diff --git a/DiaryApp/Controllers/Weather/WeatherResponse.swift b/DiaryApp/Controllers/Weather/WeatherResponse.swift new file mode 100644 index 0000000..fc62465 --- /dev/null +++ b/DiaryApp/Controllers/Weather/WeatherResponse.swift @@ -0,0 +1,24 @@ +import Foundation + +struct WeatherResponse { + let description: String + let temperature: Double + let iconUrl: String + var iconImageData: Data? // 이미지 데이터 추가 + + init?(json: Any) { + guard let jsonDict = json as? [String: Any], + let weatherArray = jsonDict["weather"] as? [[String: Any]], + let mainDict = jsonDict["main"] as? [String: Any], + let description = weatherArray.first?["description"] as? String, + let icon = weatherArray.first?["icon"] as? String, + let temperature = mainDict["temp"] as? Double + else { + return nil + } + + self.description = description + self.temperature = temperature + self.iconUrl = "https://openweathermap.org/img/wn/\(icon)@2x.png" + } +} diff --git a/DiaryApp/Controllers/weatherAPI.plist b/DiaryApp/Controllers/weatherAPI.plist new file mode 100644 index 0000000..7ae8c99 --- /dev/null +++ b/DiaryApp/Controllers/weatherAPI.plist @@ -0,0 +1,8 @@ + + + + + OpenWeather + e8aeafe9abc4ec56d53a28782b1991f8 + + diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..bbf389f --- /dev/null +++ b/Podfile @@ -0,0 +1,11 @@ +# Uncomment the next line to define a global platform for your project +platform :ios, '13.0' + +target 'DiaryApp' do + use_frameworks! + + # Pods for DiaryApp +pod 'Alamofire', '~> 5.2' +pod 'SwiftyJSON', '~> 5.0' + +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..eea3d86 --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,20 @@ +PODS: + - Alamofire (5.8.0) + - SwiftyJSON (5.0.1) + +DEPENDENCIES: + - Alamofire (~> 5.2) + - SwiftyJSON (~> 5.0) + +SPEC REPOS: + trunk: + - Alamofire + - SwiftyJSON + +SPEC CHECKSUMS: + Alamofire: 0e92e751b3e9e66d7982db43919d01f313b8eb91 + SwiftyJSON: 2f33a42c6fbc52764d96f13368585094bfd8aa5e + +PODFILE CHECKSUM: 5e61afd8812c9454d63f39ebb91e91b56a2d87b4 + +COCOAPODS: 1.12.1 diff --git a/Pods/Alamofire/LICENSE b/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..cae030a --- /dev/null +++ b/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/Alamofire/README.md b/Pods/Alamofire/README.md new file mode 100644 index 0000000..b0ba4d5 --- /dev/null +++ b/Pods/Alamofire/README.md @@ -0,0 +1,227 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/AlamofireLogo.png) + +[![Swift](https://img.shields.io/badge/Swift-5.5_5.6_5.7_5.8-orange?style=flat-square)](https://img.shields.io/badge/Swift-5.5_5.6_5.7_5.8-Orange?style=flat-square) +[![Platforms](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-yellowgreen?style=flat-square)](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-Green?style=flat-square) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg?style=flat-square)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat-square)](https://github.com/Carthage/Carthage) +[![Swift Package Manager](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square)](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat-square)](https://twitter.com/AlamofireSF) +[![Swift Forums](https://img.shields.io/badge/Swift_Forums-Alamofire-orange?style=flat-square)](https://forums.swift.org/c/related-projects/alamofire/37) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Contributing](#contributing) +- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire) + - [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) + - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) + - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) +- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) + - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#sessiondelegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) + - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests-with-requestinterceptor) + - **Model Objects -** [Custom Response Handlers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#customizing-response-handlers) + - **Advanced Concurrency -** [Swift Concurrency](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-swift-concurrency) and [Combine](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-combine) + - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] Swift Concurrency Support Back to iOS 13, macOS 10.15, tvOS 13, and watchOS 6. +- [x] Combine Support +- [x] URL / JSON Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with `URLCredential` +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](https://alamofire.github.io/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache, and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +| Platform | Minimum Swift Version | Installation | Status | +| --- | --- | --- | --- | +| iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ | 5.5 | [CocoaPods](#cocoapods), [Carthage](#carthage), [Swift Package Manager](#swift-package-manager), [Manual](#manually) | Fully Tested | +| Linux | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | +| Windows | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | + +#### Known Issues on Linux and Windows + +Alamofire builds on Linux and Windows but there are missing features and many issues in the underlying `swift-corelibs-foundation` that prevent full functionality and may cause crashes. These include: +- `ServerTrustManager` and associated certificate functionality is unavailable, so there is no certificate pinning and no client certificate support. +- Various methods of HTTP authentication may crash, including HTTP Basic and HTTP Digest. Crashes may occur if responses contain server challenges. +- Cache control through `CachedResponseHandler` and associated APIs is unavailable, as the underlying delegate methods aren't called. +- `URLSessionTaskMetrics` are never gathered. + +Due to these issues, Alamofire is unsupported on Linux and Windows. Please report any crashes to the [Swift bug reporter](https://bugs.swift.org). + +## Migration Guides + +- [Alamofire 5.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md) +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication +- If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. +- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. +- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better! + +## Installation + +### CocoaPods + +[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +pod 'Alamofire' +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" +``` + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.6.4")) +] +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for macOS. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS`, or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +## Contributing + +Before contributing to Alamofire, please read the instructions detailed in our [contribution guide](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md). + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in the test case +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` + +## Resolved Radars + +The following radars have been resolved over time after being filed against the Alamofire project. + +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage. + - (Resolved): 9/1/17 in Xcode 9 beta 6. +- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ + - (Resolved): Just add `CFNetwork` to your linked frameworks. +- `FB7624529` - `urlSession(_:task:didFinishCollecting:)` never called on watchOS + - (Resolved): Metrics now collected on watchOS 7+. + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Sponsorship + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. +Registering will allow Foundation members to gain some legal protections and also allow us to put donations to use, tax-free. +Sponsoring the ASF will enable us to: + +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. +We are greatly humbled by your enthusiasm around the projects and want to continue to do everything we can to move the needle forward. +With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. +If you use any of our libraries for work, see if your employers would be interested in donating. +Any amount you can donate, whether once or monthly, to help us reach our goal would be greatly appreciated. + +[Sponsor Alamofire](https://github.com/sponsors/Alamofire) + +## Supporters + +[MacStadium](https://macstadium.com) provides Alamofire with a free, hosted Mac mini. + +![Powered by MacStadium](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/MacStadiumLogo.png) + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/Pods/Alamofire/Source/AFError.swift b/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000..82a75b5 --- /dev/null +++ b/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,874 @@ +// +// AFError.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if canImport(Security) +import Security +#endif + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +public enum AFError: Error { + /// The underlying reason the `.multipartEncodingFailed` error occurred. + public enum MultipartEncodingFailureReason { + /// The `fileURL` provided for reading an encodable body part isn't a file `URL`. + case bodyPartURLInvalid(url: URL) + /// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension. + case bodyPartFilenameInvalid(in: URL) + /// The file at the `fileURL` provided was not reachable. + case bodyPartFileNotReachable(at: URL) + /// Attempting to check the reachability of the `fileURL` provided threw an error. + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + /// The file at the `fileURL` provided is actually a directory. + case bodyPartFileIsDirectory(at: URL) + /// The size of the file at the `fileURL` provided was not returned by the system. + case bodyPartFileSizeNotAvailable(at: URL) + /// The attempt to find the size of the file at the `fileURL` provided threw an error. + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + /// An `InputStream` could not be created for the provided `fileURL`. + case bodyPartInputStreamCreationFailed(for: URL) + /// An `OutputStream` could not be created when attempting to write the encoded data to disk. + case outputStreamCreationFailed(for: URL) + /// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`. + case outputStreamFileAlreadyExists(at: URL) + /// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`. + case outputStreamURLInvalid(url: URL) + /// The attempt to write the encoded body data to disk failed with an underlying error. + case outputStreamWriteFailed(error: Error) + /// The attempt to read an encoded body part `InputStream` failed with underlying system error. + case inputStreamReadFailed(error: Error) + } + + /// Represents unexpected input stream length that occur when encoding the `MultipartFormData`. Instances will be + /// embedded within an `AFError.multipartEncodingFailed` `.inputStreamReadFailed` case. + public struct UnexpectedInputStreamLength: Error { + /// The expected byte count to read. + public var bytesExpected: UInt64 + /// The actual byte count read. + public var bytesRead: UInt64 + } + + /// The underlying reason the `.parameterEncodingFailed` error occurred. + public enum ParameterEncodingFailureReason { + /// The `URLRequest` did not have a `URL` to encode. + case missingURL + /// JSON serialization failed with an underlying system error during the encoding process. + case jsonEncodingFailed(error: Error) + /// Custom parameter encoding failed due to the associated `Error`. + case customEncodingFailed(error: Error) + } + + /// The underlying reason the `.parameterEncoderFailed` error occurred. + public enum ParameterEncoderFailureReason { + /// Possible missing components. + public enum RequiredComponent { + /// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding. + case url + /// The `HTTPMethod` could not be extracted from the passed `URLRequest`. + case httpMethod(rawValue: String) + } + + /// A `RequiredComponent` was missing during encoding. + case missingRequiredComponent(RequiredComponent) + /// The underlying encoder failed with the associated error. + case encoderFailed(error: Error) + } + + /// The underlying reason the `.responseValidationFailed` error occurred. + public enum ResponseValidationFailureReason { + /// The data file containing the server response did not exist. + case dataFileNil + /// The data file containing the server response at the associated `URL` could not be read. + case dataFileReadFailed(at: URL) + /// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a + /// wildcard type. + case missingContentType(acceptableContentTypes: [String]) + /// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`. + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + /// The response status code was not acceptable. + case unacceptableStatusCode(code: Int) + /// Custom response validation failed due to the associated `Error`. + case customValidationFailed(error: Error) + } + + /// The underlying reason the response serialization error occurred. + public enum ResponseSerializationFailureReason { + /// The server response contained no data or the data was zero length. + case inputDataNilOrZeroLength + /// The file containing the server response did not exist. + case inputFileNil + /// The file containing the server response could not be read from the associated `URL`. + case inputFileReadFailed(at: URL) + /// String serialization failed using the provided `String.Encoding`. + case stringSerializationFailed(encoding: String.Encoding) + /// JSON serialization failed with an underlying system error. + case jsonSerializationFailed(error: Error) + /// A `DataDecoder` failed to decode the response due to the associated `Error`. + case decodingFailed(error: Error) + /// A custom response serializer failed due to the associated `Error`. + case customSerializationFailed(error: Error) + /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type. + case invalidEmptyResponse(type: String) + } + + #if canImport(Security) + /// Underlying reason a server trust evaluation error occurred. + public enum ServerTrustFailureReason { + /// The output of a server trust evaluation. + public struct Output { + /// The host for which the evaluation was performed. + public let host: String + /// The `SecTrust` value which was evaluated. + public let trust: SecTrust + /// The `OSStatus` of evaluation operation. + public let status: OSStatus + /// The result of the evaluation operation. + public let result: SecTrustResultType + + /// Creates an `Output` value from the provided values. + init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) { + self.host = host + self.trust = trust + self.status = status + self.result = result + } + } + + /// No `ServerTrustEvaluator` was found for the associated host. + case noRequiredEvaluator(host: String) + /// No certificates were found with which to perform the trust evaluation. + case noCertificatesFound + /// No public keys were found with which to perform the trust evaluation. + case noPublicKeysFound + /// During evaluation, application of the associated `SecPolicy` failed. + case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus) + /// During evaluation, setting the associated anchor certificates failed. + case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate]) + /// During evaluation, creation of the revocation policy failed. + case revocationPolicyCreationFailed + /// `SecTrust` evaluation failed with the associated `Error`, if one was produced. + case trustEvaluationFailed(error: Error?) + /// Default evaluation failed with the associated `Output`. + case defaultEvaluationFailed(output: Output) + /// Host validation failed with the associated `Output`. + case hostValidationFailed(output: Output) + /// Revocation check failed with the associated `Output` and options. + case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options) + /// Certificate pinning failed. + case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate]) + /// Public key pinning failed. + case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey]) + /// Custom server trust evaluation failed due to the associated `Error`. + case customEvaluationFailed(error: Error) + } + #endif + + /// The underlying reason the `.urlRequestValidationFailed` + public enum URLRequestValidationFailureReason { + /// URLRequest with GET method had body data. + case bodyDataInGETRequest(Data) + } + + /// `UploadableConvertible` threw an error in `createUploadable()`. + case createUploadableFailed(error: Error) + /// `URLRequestConvertible` threw an error in `asURLRequest()`. + case createURLRequestFailed(error: Error) + /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL. + case downloadedFileMoveFailed(error: Error, source: URL, destination: URL) + /// `Request` was explicitly cancelled. + case explicitlyCancelled + /// `URLConvertible` type failed to create a valid `URL`. + case invalidURL(url: URLConvertible) + /// Multipart form encoding failed. + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + /// `ParameterEncoding` threw an error during the encoding process. + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + /// `ParameterEncoder` threw an error while running the encoder. + case parameterEncoderFailed(reason: ParameterEncoderFailureReason) + /// `RequestAdapter` threw an error during adaptation. + case requestAdaptationFailed(error: Error) + /// `RequestRetrier` threw an error during the request retry process. + case requestRetryFailed(retryError: Error, originalError: Error) + /// Response validation failed. + case responseValidationFailed(reason: ResponseValidationFailureReason) + /// Response serialization failed. + case responseSerializationFailed(reason: ResponseSerializationFailureReason) + #if canImport(Security) + /// `ServerTrustEvaluating` instance threw an error during trust evaluation. + case serverTrustEvaluationFailed(reason: ServerTrustFailureReason) + #endif + /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope. + case sessionDeinitialized + /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`. + case sessionInvalidated(error: Error?) + /// `URLSessionTask` completed with error. + case sessionTaskFailed(error: Error) + /// `URLRequest` failed validation. + case urlRequestValidationFailed(reason: URLRequestValidationFailureReason) +} + +extension Error { + /// Returns the instance cast as an `AFError`. + public var asAFError: AFError? { + self as? AFError + } + + /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown. + public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError { + guard let afError = self as? AFError else { + fatalError(message(), file: file, line: line) + } + return afError + } + + /// Casts the instance as `AFError` or returns `defaultAFError` + func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError { + self as? AFError ?? defaultAFError() + } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the instance is `.sessionDeinitialized`. + public var isSessionDeinitializedError: Bool { + if case .sessionDeinitialized = self { return true } + return false + } + + /// Returns whether the instance is `.sessionInvalidated`. + public var isSessionInvalidatedError: Bool { + if case .sessionInvalidated = self { return true } + return false + } + + /// Returns whether the instance is `.explicitlyCancelled`. + public var isExplicitlyCancelledError: Bool { + if case .explicitlyCancelled = self { return true } + return false + } + + /// Returns whether the instance is `.invalidURL`. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncoderError: Bool { + if case .parameterEncoderFailed = self { return true } + return false + } + + /// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError` + /// properties will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestAdaptationError: Bool { + if case .requestAdaptationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } + + #if canImport(Security) + /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isServerTrustEvaluationError: Bool { + if case .serverTrustEvaluationFailed = self { return true } + return false + } + #endif + + /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestRetryError: Bool { + if case .requestRetryFailed = self { return true } + return false + } + + /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateUploadableError: Bool { + if case .createUploadableFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateURLRequestError: Bool { + if case .createURLRequestFailed = self { return true } + return false + } + + /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will + /// contain the associated values. + public var isDownloadedFileMoveError: Bool { + if case .downloadedFileMoveFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isSessionTaskError: Bool { + if case .sessionTaskFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + guard case let .invalidURL(url) = self else { return nil } + return url + } + + /// The `URL` associated with the error. + public var url: URL? { + guard case let .multipartEncodingFailed(reason) = self else { return nil } + return reason.url + } + + /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`, + /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`, + /// `.responseSerializationFailed`, `.requestRetryFailed` errors. + public var underlyingError: Error? { + switch self { + case let .multipartEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncoderFailed(reason): + return reason.underlyingError + case let .requestAdaptationFailed(error): + return error + case let .requestRetryFailed(retryError, _): + return retryError + case let .responseValidationFailed(reason): + return reason.underlyingError + case let .responseSerializationFailed(reason): + return reason.underlyingError + #if canImport(Security) + case let .serverTrustEvaluationFailed(reason): + return reason.underlyingError + #endif + case let .sessionInvalidated(error): + return error + case let .createUploadableFailed(error): + return error + case let .createURLRequestFailed(error): + return error + case let .downloadedFileMoveFailed(error, _, _): + return error + case let .sessionTaskFailed(error): + return error + case .explicitlyCancelled, + .invalidURL, + .sessionDeinitialized, + .urlRequestValidationFailed: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.acceptableContentTypes + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseContentType + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseCode + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + guard case let .responseSerializationFailed(reason) = self else { return nil } + return reason.failedStringEncoding + } + + /// The `source` URL of a `.downloadedFileMoveFailed` error. + public var sourceURL: URL? { + guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil } + return source + } + + /// The `destination` URL of a `.downloadedFileMoveFailed` error. + public var destinationURL: URL? { + guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil } + return destination + } + + #if canImport(Security) + /// The download resume data of any underlying network error. Only produced by `DownloadRequest`s. + public var downloadResumeData: Data? { + (underlyingError as? URLError)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data + } + #endif +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case let .jsonEncodingFailed(error), + let .customEncodingFailed(error): + return error + case .missingURL: + return nil + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var underlyingError: Error? { + switch self { + case let .encoderFailed(error): + return error + case .missingRequiredComponent: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case let .bodyPartURLInvalid(url), + let .bodyPartFilenameInvalid(url), + let .bodyPartFileNotReachable(url), + let .bodyPartFileIsDirectory(url), + let .bodyPartFileSizeNotAvailable(url), + let .bodyPartInputStreamCreationFailed(url), + let .outputStreamCreationFailed(url), + let .outputStreamFileAlreadyExists(url), + let .outputStreamURLInvalid(url), + let .bodyPartFileNotReachableWithError(url, _), + let .bodyPartFileSizeQueryFailedWithError(url, _): + return url + case .outputStreamWriteFailed, + .inputStreamReadFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .bodyPartFileNotReachableWithError(_, error), + let .bodyPartFileSizeQueryFailedWithError(_, error), + let .outputStreamWriteFailed(error), + let .inputStreamReadFailed(error): + return error + case .bodyPartURLInvalid, + .bodyPartFilenameInvalid, + .bodyPartFileNotReachable, + .bodyPartFileIsDirectory, + .bodyPartFileSizeNotAvailable, + .bodyPartInputStreamCreationFailed, + .outputStreamCreationFailed, + .outputStreamFileAlreadyExists, + .outputStreamURLInvalid: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case let .missingContentType(types), + let .unacceptableContentType(types, _): + return types + case .dataFileNil, + .dataFileReadFailed, + .unacceptableStatusCode, + .customValidationFailed: + return nil + } + } + + var responseContentType: String? { + switch self { + case let .unacceptableContentType(_, responseType): + return responseType + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableStatusCode, + .customValidationFailed: + return nil + } + } + + var responseCode: Int? { + switch self { + case let .unacceptableStatusCode(code): + return code + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .customValidationFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .customValidationFailed(error): + return error + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .unacceptableStatusCode: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case let .stringSerializationFailed(encoding): + return encoding + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed(_), + .jsonSerializationFailed(_), + .decodingFailed(_), + .customSerializationFailed(_), + .invalidEmptyResponse: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .jsonSerializationFailed(error), + let .decodingFailed(error), + let .customSerializationFailed(error): + return error + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed, + .stringSerializationFailed, + .invalidEmptyResponse: + return nil + } + } +} + +#if canImport(Security) +extension AFError.ServerTrustFailureReason { + var output: AFError.ServerTrustFailureReason.Output? { + switch self { + case let .defaultEvaluationFailed(output), + let .hostValidationFailed(output), + let .revocationCheckFailed(output, _): + return output + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .trustEvaluationFailed, + .certificatePinningFailed, + .publicKeyPinningFailed, + .customEvaluationFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .customEvaluationFailed(error): + return error + case let .trustEvaluationFailed(error): + return error + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .defaultEvaluationFailed, + .hostValidationFailed, + .revocationCheckFailed, + .certificatePinningFailed, + .publicKeyPinningFailed: + return nil + } + } +} +#endif + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .explicitlyCancelled: + return "Request explicitly cancelled." + case let .invalidURL(url): + return "URL is not valid: \(url)" + case let .parameterEncodingFailed(reason): + return reason.localizedDescription + case let .parameterEncoderFailed(reason): + return reason.localizedDescription + case let .multipartEncodingFailed(reason): + return reason.localizedDescription + case let .requestAdaptationFailed(error): + return "Request adaption failed with error: \(error.localizedDescription)" + case let .responseValidationFailed(reason): + return reason.localizedDescription + case let .responseSerializationFailed(reason): + return reason.localizedDescription + case let .requestRetryFailed(retryError, originalError): + return """ + Request retry failed with retry error: \(retryError.localizedDescription), \ + original error: \(originalError.localizedDescription) + """ + case .sessionDeinitialized: + return """ + Session was invalidated without error, so it was likely deinitialized unexpectedly. \ + Be sure to retain a reference to your Session for the duration of your requests. + """ + case let .sessionInvalidated(error): + return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")" + #if canImport(Security) + case let .serverTrustEvaluationFailed(reason): + return "Server trust evaluation failed due to reason: \(reason.localizedDescription)" + #endif + case let .urlRequestValidationFailed(reason): + return "URLRequest validation failed due to reason: \(reason.localizedDescription)" + case let .createUploadableFailed(error): + return "Uploadable creation failed with error: \(error.localizedDescription)" + case let .createURLRequestFailed(error): + return "URLRequest creation failed with error: \(error.localizedDescription)" + case let .downloadedFileMoveFailed(error, source, destination): + return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)" + case let .sessionTaskFailed(error): + return "URLSessionTask failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case let .jsonEncodingFailed(error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case let .customEncodingFailed(error): + return "Custom parameter encoder failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var localizedDescription: String { + switch self { + case let .missingRequiredComponent(component): + return "Encoding failed due to a missing request component: \(component)" + case let .encoderFailed(error): + return "The underlying encoder failed with the error: \(error)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case let .bodyPartURLInvalid(url): + return "The URL provided is not a file URL: \(url)" + case let .bodyPartFilenameInvalid(url): + return "The URL provided does not have a valid filename: \(url)" + case let .bodyPartFileNotReachable(url): + return "The URL provided is not reachable: \(url)" + case let .bodyPartFileNotReachableWithError(url, error): + return """ + The system returned an error while checking the provided URL for reachability. + URL: \(url) + Error: \(error) + """ + case let .bodyPartFileIsDirectory(url): + return "The URL provided is a directory: \(url)" + case let .bodyPartFileSizeNotAvailable(url): + return "Could not fetch the file size from the provided URL: \(url)" + case let .bodyPartFileSizeQueryFailedWithError(url, error): + return """ + The system returned an error while attempting to fetch the file size from the provided URL. + URL: \(url) + Error: \(error) + """ + case let .bodyPartInputStreamCreationFailed(url): + return "Failed to create an InputStream for the provided URL: \(url)" + case let .outputStreamCreationFailed(url): + return "Failed to create an OutputStream for URL: \(url)" + case let .outputStreamFileAlreadyExists(url): + return "A file already exists at the provided URL: \(url)" + case let .outputStreamURLInvalid(url): + return "The provided OutputStream URL is invalid: \(url)" + case let .outputStreamWriteFailed(error): + return "OutputStream write failed with error: \(error)" + case let .inputStreamReadFailed(error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case let .inputFileReadFailed(url): + return "Response could not be serialized, input file could not be read: \(url)." + case let .stringSerializationFailed(encoding): + return "String could not be serialized with encoding: \(encoding)." + case let .jsonSerializationFailed(error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case let .invalidEmptyResponse(type): + return """ + Empty response could not be serialized to type: \(type). \ + Use Empty as the expected type for such responses. + """ + case let .decodingFailed(error): + return "Response could not be decoded because of error:\n\(error.localizedDescription)" + case let .customSerializationFailed(error): + return "Custom response serializer failed with error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case let .dataFileReadFailed(url): + return "Response could not be validated, data file could not be read: \(url)." + case let .missingContentType(types): + return """ + Response Content-Type was missing and acceptable content types \ + (\(types.joined(separator: ","))) do not match "*/*". + """ + case let .unacceptableContentType(acceptableTypes, responseType): + return """ + Response Content-Type "\(responseType)" does not match any acceptable types: \ + \(acceptableTypes.joined(separator: ",")). + """ + case let .unacceptableStatusCode(code): + return "Response status code was unacceptable: \(code)." + case let .customValidationFailed(error): + return "Custom response validation failed with error: \(error.localizedDescription)" + } + } +} + +#if canImport(Security) +extension AFError.ServerTrustFailureReason { + var localizedDescription: String { + switch self { + case let .noRequiredEvaluator(host): + return "A ServerTrustEvaluating value is required for host \(host) but none was found." + case .noCertificatesFound: + return "No certificates were found or provided for evaluation." + case .noPublicKeysFound: + return "No public keys were found or provided for evaluation." + case .policyApplicationFailed: + return "Attempting to set a SecPolicy failed." + case .settingAnchorCertificatesFailed: + return "Attempting to set the provided certificates as anchor certificates failed." + case .revocationPolicyCreationFailed: + return "Attempting to create a revocation policy failed." + case let .trustEvaluationFailed(error): + return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")" + case let .defaultEvaluationFailed(output): + return "Default evaluation failed for host \(output.host)." + case let .hostValidationFailed(output): + return "Host validation failed for host \(output.host)." + case let .revocationCheckFailed(output, _): + return "Revocation check failed for host \(output.host)." + case let .certificatePinningFailed(host, _, _, _): + return "Certificate pinning failed for host \(host)." + case let .publicKeyPinningFailed(host, _, _, _): + return "Public key pinning failed for host \(host)." + case let .customEvaluationFailed(error): + return "Custom trust evaluation failed with error: \(error.localizedDescription)" + } + } +} +#endif + +extension AFError.URLRequestValidationFailureReason { + var localizedDescription: String { + switch self { + case let .bodyDataInGETRequest(data): + return """ + Invalid URLRequest: Requests with GET method cannot have body data: + \(String(decoding: data, as: UTF8.self)) + """ + } + } +} diff --git a/Pods/Alamofire/Source/Alamofire.swift b/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..c99fe49 --- /dev/null +++ b/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,40 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2021 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation +#if canImport(FoundationNetworking) +@_exported import FoundationNetworking +#endif + +// Enforce minimum Swift version for all platforms and build systems. +#if swift(<5.5) +#error("Alamofire doesn't support Swift versions below 5.5.") +#endif + +/// Reference to `Session.default` for quick bootstrapping and examples. +public let AF = Session.default + +/// Current Alamofire version. Necessary since SPM doesn't use dynamic libraries. Plus this will be more accurate. +let version = "5.8.0" diff --git a/Pods/Alamofire/Source/AlamofireExtended.swift b/Pods/Alamofire/Source/AlamofireExtended.swift new file mode 100644 index 0000000..280c6de --- /dev/null +++ b/Pods/Alamofire/Source/AlamofireExtended.swift @@ -0,0 +1,61 @@ +// +// AlamofireExtended.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +/// Type that acts as a generic extension point for all `AlamofireExtended` types. +public struct AlamofireExtension { + /// Stores the type or meta-type of any extended type. + public private(set) var type: ExtendedType + + /// Create an instance from the provided value. + /// + /// - Parameter type: Instance being extended. + public init(_ type: ExtendedType) { + self.type = type + } +} + +/// Protocol describing the `af` extension points for Alamofire extended types. +public protocol AlamofireExtended { + /// Type being extended. + associatedtype ExtendedType + + /// Static Alamofire extension point. + static var af: AlamofireExtension.Type { get set } + /// Instance Alamofire extension point. + var af: AlamofireExtension { get set } +} + +extension AlamofireExtended { + /// Static Alamofire extension point. + public static var af: AlamofireExtension.Type { + get { AlamofireExtension.self } + set {} + } + + /// Instance Alamofire extension point. + public var af: AlamofireExtension { + get { AlamofireExtension(self) } + set {} + } +} diff --git a/Pods/Alamofire/Source/AuthenticationInterceptor.swift b/Pods/Alamofire/Source/AuthenticationInterceptor.swift new file mode 100644 index 0000000..c3a3f31 --- /dev/null +++ b/Pods/Alamofire/Source/AuthenticationInterceptor.swift @@ -0,0 +1,403 @@ +// +// AuthenticationInterceptor.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `AuthenticationCredential` protocol can be used to authenticate `URLRequest`s. +/// +/// One common example of an `AuthenticationCredential` is an OAuth2 credential containing an access token used to +/// authenticate all requests on behalf of a user. The access token generally has an expiration window of 60 minutes +/// which will then require a refresh of the credential using the refresh token to generate a new access token. +public protocol AuthenticationCredential { + /// Whether the credential requires a refresh. This property should always return `true` when the credential is + /// expired. It is also wise to consider returning `true` when the credential will expire in several seconds or + /// minutes depending on the expiration window of the credential. + /// + /// For example, if the credential is valid for 60 minutes, then it would be wise to return `true` when the + /// credential is only valid for 5 minutes or less. That ensures the credential will not expire as it is passed + /// around backend services. + var requiresRefresh: Bool { get } +} + +// MARK: - + +/// Types adopting the `Authenticator` protocol can be used to authenticate `URLRequest`s with an +/// `AuthenticationCredential` as well as refresh the `AuthenticationCredential` when required. +public protocol Authenticator: AnyObject { + /// The type of credential associated with the `Authenticator` instance. + associatedtype Credential: AuthenticationCredential + + /// Applies the `Credential` to the `URLRequest`. + /// + /// In the case of OAuth2, the access token of the `Credential` would be added to the `URLRequest` as a Bearer + /// token to the `Authorization` header. + /// + /// - Parameters: + /// - credential: The `Credential`. + /// - urlRequest: The `URLRequest`. + func apply(_ credential: Credential, to urlRequest: inout URLRequest) + + /// Refreshes the `Credential` and executes the `completion` closure with the `Result` once complete. + /// + /// Refresh can be called in one of two ways. It can be called before the `Request` is actually executed due to + /// a `requiresRefresh` returning `true` during the adapt portion of the `Request` creation process. It can also + /// be triggered by a failed `Request` where the authentication server denied access due to an expired or + /// invalidated access token. + /// + /// In the case of OAuth2, this method would use the refresh token of the `Credential` to generate a new + /// `Credential` using the authentication service. Once complete, the `completion` closure should be called with + /// the new `Credential`, or the error that occurred. + /// + /// In general, if the refresh call fails with certain status codes from the authentication server (commonly a 401), + /// the refresh token in the `Credential` can no longer be used to generate a valid `Credential`. In these cases, + /// you will need to reauthenticate the user with their username / password. + /// + /// Please note, these are just general examples of common use cases. They are not meant to solve your specific + /// authentication server challenges. Please work with your authentication server team to ensure your + /// `Authenticator` logic matches their expectations. + /// + /// - Parameters: + /// - credential: The `Credential` to refresh. + /// - session: The `Session` requiring the refresh. + /// - completion: The closure to be executed once the refresh is complete. + func refresh(_ credential: Credential, for session: Session, completion: @escaping (Result) -> Void) + + /// Determines whether the `URLRequest` failed due to an authentication error based on the `HTTPURLResponse`. + /// + /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `false` + /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then you + /// will need to work with your authentication server team to understand how to identify when this occurs. + /// + /// In the case of OAuth2, where an authentication server can invalidate credentials, you will need to inspect the + /// `HTTPURLResponse` or possibly the `Error` for when this occurs. This is commonly handled by the authentication + /// server returning a 401 status code and some additional header to indicate an OAuth2 failure occurred. + /// + /// It is very important to understand how your authentication server works to be able to implement this correctly. + /// For example, if your authentication server returns a 401 when an OAuth2 error occurs, and your downstream + /// service also returns a 401 when you are not authorized to perform that operation, how do you know which layer + /// of the backend returned you a 401? You do not want to trigger a refresh unless you know your authentication + /// server is actually the layer rejecting the request. Again, work with your authentication server team to understand + /// how to identify an OAuth2 401 error vs. a downstream 401 error to avoid endless refresh loops. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest`. + /// - response: The `HTTPURLResponse`. + /// - error: The `Error`. + /// + /// - Returns: `true` if the `URLRequest` failed due to an authentication error, `false` otherwise. + func didRequest(_ urlRequest: URLRequest, with response: HTTPURLResponse, failDueToAuthenticationError error: Error) -> Bool + + /// Determines whether the `URLRequest` is authenticated with the `Credential`. + /// + /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `true` + /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then + /// read on. + /// + /// When an authentication server can invalidate credentials, it means that you may have a non-expired credential + /// that appears to be valid, but will be rejected by the authentication server when used. Generally when this + /// happens, a number of requests are all sent when the application is foregrounded, and all of them will be + /// rejected by the authentication server in the order they are received. The first failed request will trigger a + /// refresh internally, which will update the credential, and then retry all the queued requests with the new + /// credential. However, it is possible that some of the original requests will not return from the authentication + /// server until the refresh has completed. This is where this method comes in. + /// + /// When the authentication server rejects a credential, we need to check to make sure we haven't refreshed the + /// credential while the request was in flight. If it has already refreshed, then we don't need to trigger an + /// additional refresh. If it hasn't refreshed, then we need to refresh. + /// + /// Now that it is understood how the result of this method is used in the refresh lifecyle, let's walk through how + /// to implement it. You should return `true` in this method if the `URLRequest` is authenticated in a way that + /// matches the values in the `Credential`. In the case of OAuth2, this would mean that the Bearer token in the + /// `Authorization` header of the `URLRequest` matches the access token in the `Credential`. If it matches, then we + /// know the `Credential` was used to authenticate the `URLRequest` and should return `true`. If the Bearer token + /// did not match the access token, then you should return `false`. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest`. + /// - credential: The `Credential`. + /// + /// - Returns: `true` if the `URLRequest` is authenticated with the `Credential`, `false` otherwise. + func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: Credential) -> Bool +} + +// MARK: - + +/// Represents various authentication failures that occur when using the `AuthenticationInterceptor`. All errors are +/// still vended from Alamofire as `AFError` types. The `AuthenticationError` instances will be embedded within +/// `AFError` `.requestAdaptationFailed` or `.requestRetryFailed` cases. +public enum AuthenticationError: Error { + /// The credential was missing so the request could not be authenticated. + case missingCredential + /// The credential was refreshed too many times within the `RefreshWindow`. + case excessiveRefresh +} + +// MARK: - + +/// The `AuthenticationInterceptor` class manages the queuing and threading complexity of authenticating requests. +/// It relies on an `Authenticator` type to handle the actual `URLRequest` authentication and `Credential` refresh. +public class AuthenticationInterceptor: RequestInterceptor where AuthenticatorType: Authenticator { + // MARK: Typealiases + + /// Type of credential used to authenticate requests. + public typealias Credential = AuthenticatorType.Credential + + // MARK: Helper Types + + /// Type that defines a time window used to identify excessive refresh calls. When enabled, prior to executing a + /// refresh, the `AuthenticationInterceptor` compares the timestamp history of previous refresh calls against the + /// `RefreshWindow`. If more refreshes have occurred within the refresh window than allowed, the refresh is + /// cancelled and an `AuthorizationError.excessiveRefresh` error is thrown. + public struct RefreshWindow { + /// `TimeInterval` defining the duration of the time window before the current time in which the number of + /// refresh attempts is compared against `maximumAttempts`. For example, if `interval` is 30 seconds, then the + /// `RefreshWindow` represents the past 30 seconds. If more attempts occurred in the past 30 seconds than + /// `maximumAttempts`, an `.excessiveRefresh` error will be thrown. + public let interval: TimeInterval + + /// Total refresh attempts allowed within `interval` before throwing an `.excessiveRefresh` error. + public let maximumAttempts: Int + + /// Creates a `RefreshWindow` instance from the specified `interval` and `maximumAttempts`. + /// + /// - Parameters: + /// - interval: `TimeInterval` defining the duration of the time window before the current time. + /// - maximumAttempts: The maximum attempts allowed within the `TimeInterval`. + public init(interval: TimeInterval = 30.0, maximumAttempts: Int = 5) { + self.interval = interval + self.maximumAttempts = maximumAttempts + } + } + + private struct AdaptOperation { + let urlRequest: URLRequest + let session: Session + let completion: (Result) -> Void + } + + private enum AdaptResult { + case adapt(Credential) + case doNotAdapt(AuthenticationError) + case adaptDeferred + } + + private struct MutableState { + var credential: Credential? + + var isRefreshing = false + var refreshTimestamps: [TimeInterval] = [] + var refreshWindow: RefreshWindow? + + var adaptOperations: [AdaptOperation] = [] + var requestsToRetry: [(RetryResult) -> Void] = [] + } + + // MARK: Properties + + /// The `Credential` used to authenticate requests. + public var credential: Credential? { + get { $mutableState.credential } + set { $mutableState.credential = newValue } + } + + let authenticator: AuthenticatorType + let queue = DispatchQueue(label: "org.alamofire.authentication.inspector") + + @Protected + private var mutableState: MutableState + + // MARK: Initialization + + /// Creates an `AuthenticationInterceptor` instance from the specified parameters. + /// + /// A `nil` `RefreshWindow` will result in the `AuthenticationInterceptor` not checking for excessive refresh calls. + /// It is recommended to always use a `RefreshWindow` to avoid endless refresh cycles. + /// + /// - Parameters: + /// - authenticator: The `Authenticator` type. + /// - credential: The `Credential` if it exists. `nil` by default. + /// - refreshWindow: The `RefreshWindow` used to identify excessive refresh calls. `RefreshWindow()` by default. + public init(authenticator: AuthenticatorType, + credential: Credential? = nil, + refreshWindow: RefreshWindow? = RefreshWindow()) { + self.authenticator = authenticator + mutableState = MutableState(credential: credential, refreshWindow: refreshWindow) + } + + // MARK: Adapt + + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + let adaptResult: AdaptResult = $mutableState.write { mutableState in + // Queue the adapt operation if a refresh is already in place. + guard !mutableState.isRefreshing else { + let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) + mutableState.adaptOperations.append(operation) + return .adaptDeferred + } + + // Throw missing credential error is the credential is missing. + guard let credential = mutableState.credential else { + let error = AuthenticationError.missingCredential + return .doNotAdapt(error) + } + + // Queue the adapt operation and trigger refresh operation if credential requires refresh. + guard !credential.requiresRefresh else { + let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) + mutableState.adaptOperations.append(operation) + refresh(credential, for: session, insideLock: &mutableState) + return .adaptDeferred + } + + return .adapt(credential) + } + + switch adaptResult { + case let .adapt(credential): + var authenticatedRequest = urlRequest + authenticator.apply(credential, to: &authenticatedRequest) + completion(.success(authenticatedRequest)) + + case let .doNotAdapt(adaptError): + completion(.failure(adaptError)) + + case .adaptDeferred: + // No-op: adapt operation captured during refresh. + break + } + } + + // MARK: Retry + + public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { + // Do not attempt retry if there was not an original request and response from the server. + guard let urlRequest = request.request, let response = request.response else { + completion(.doNotRetry) + return + } + + // Do not attempt retry unless the `Authenticator` verifies failure was due to authentication error (i.e. 401 status code). + guard authenticator.didRequest(urlRequest, with: response, failDueToAuthenticationError: error) else { + completion(.doNotRetry) + return + } + + // Do not attempt retry if there is no credential. + guard let credential = credential else { + let error = AuthenticationError.missingCredential + completion(.doNotRetryWithError(error)) + return + } + + // Retry the request if the `Authenticator` verifies it was authenticated with a previous credential. + guard authenticator.isRequest(urlRequest, authenticatedWith: credential) else { + completion(.retry) + return + } + + $mutableState.write { mutableState in + mutableState.requestsToRetry.append(completion) + + guard !mutableState.isRefreshing else { return } + + refresh(credential, for: session, insideLock: &mutableState) + } + } + + // MARK: Refresh + + private func refresh(_ credential: Credential, for session: Session, insideLock mutableState: inout MutableState) { + guard !isRefreshExcessive(insideLock: &mutableState) else { + let error = AuthenticationError.excessiveRefresh + handleRefreshFailure(error, insideLock: &mutableState) + return + } + + mutableState.refreshTimestamps.append(ProcessInfo.processInfo.systemUptime) + mutableState.isRefreshing = true + + // Dispatch to queue to hop out of the lock in case authenticator.refresh is implemented synchronously. + queue.async { + self.authenticator.refresh(credential, for: session) { result in + self.$mutableState.write { mutableState in + switch result { + case let .success(credential): + self.handleRefreshSuccess(credential, insideLock: &mutableState) + case let .failure(error): + self.handleRefreshFailure(error, insideLock: &mutableState) + } + } + } + } + } + + private func isRefreshExcessive(insideLock mutableState: inout MutableState) -> Bool { + guard let refreshWindow = mutableState.refreshWindow else { return false } + + let refreshWindowMin = ProcessInfo.processInfo.systemUptime - refreshWindow.interval + + let refreshAttemptsWithinWindow = mutableState.refreshTimestamps.reduce(into: 0) { attempts, refreshTimestamp in + guard refreshWindowMin <= refreshTimestamp else { return } + attempts += 1 + } + + let isRefreshExcessive = refreshAttemptsWithinWindow >= refreshWindow.maximumAttempts + + return isRefreshExcessive + } + + private func handleRefreshSuccess(_ credential: Credential, insideLock mutableState: inout MutableState) { + mutableState.credential = credential + + let adaptOperations = mutableState.adaptOperations + let requestsToRetry = mutableState.requestsToRetry + + mutableState.adaptOperations.removeAll() + mutableState.requestsToRetry.removeAll() + + mutableState.isRefreshing = false + + // Dispatch to queue to hop out of the mutable state lock + queue.async { + adaptOperations.forEach { self.adapt($0.urlRequest, for: $0.session, completion: $0.completion) } + requestsToRetry.forEach { $0(.retry) } + } + } + + private func handleRefreshFailure(_ error: Error, insideLock mutableState: inout MutableState) { + let adaptOperations = mutableState.adaptOperations + let requestsToRetry = mutableState.requestsToRetry + + mutableState.adaptOperations.removeAll() + mutableState.requestsToRetry.removeAll() + + mutableState.isRefreshing = false + + // Dispatch to queue to hop out of the mutable state lock + queue.async { + adaptOperations.forEach { $0.completion(.failure(error)) } + requestsToRetry.forEach { $0(.doNotRetryWithError(error)) } + } + } +} diff --git a/Pods/Alamofire/Source/CachedResponseHandler.swift b/Pods/Alamofire/Source/CachedResponseHandler.swift new file mode 100644 index 0000000..1371b6e --- /dev/null +++ b/Pods/Alamofire/Source/CachedResponseHandler.swift @@ -0,0 +1,107 @@ +// +// CachedResponseHandler.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that handles whether the data task should store the HTTP response in the cache. +public protocol CachedResponseHandler { + /// Determines whether the HTTP response should be stored in the cache. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The cached response provided by the server (this is the most common use case). + /// 2. A modified version of the cached response (you may want to modify it in some way before caching). + /// 3. A `nil` value to prevent the cached response from being stored in the cache. + /// + /// - Parameters: + /// - task: The data task whose request resulted in the cached response. + /// - response: The cached response to potentially store in the cache. + /// - completion: The closure to execute containing cached response, a modified response, or `nil`. + func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) +} + +// MARK: - + +/// `ResponseCacher` is a convenience `CachedResponseHandler` making it easy to cache, not cache, or modify a cached +/// response. +public struct ResponseCacher { + /// Defines the behavior of the `ResponseCacher` type. + public enum Behavior { + /// Stores the cached response in the cache. + case cache + /// Prevents the cached response from being stored in the cache. + case doNotCache + /// Modifies the cached response before storing it in the cache. + case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?) + } + + /// Returns a `ResponseCacher` with a `.cache` `Behavior`. + public static let cache = ResponseCacher(behavior: .cache) + /// Returns a `ResponseCacher` with a `.doNotCache` `Behavior`. + public static let doNotCache = ResponseCacher(behavior: .doNotCache) + + /// The `Behavior` of the `ResponseCacher`. + public let behavior: Behavior + + /// Creates a `ResponseCacher` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +extension ResponseCacher: CachedResponseHandler { + public func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) { + switch behavior { + case .cache: + completion(response) + case .doNotCache: + completion(nil) + case let .modify(closure): + let response = closure(task, response) + completion(response) + } + } +} + +extension CachedResponseHandler where Self == ResponseCacher { + /// Provides a `ResponseCacher` which caches the response, if allowed. Equivalent to `ResponseCacher.cache`. + public static var cache: ResponseCacher { .cache } + + /// Provides a `ResponseCacher` which does not cache the response. Equivalent to `ResponseCacher.doNotCache`. + public static var doNotCache: ResponseCacher { .doNotCache } + + /// Creates a `ResponseCacher` which modifies the proposed `CachedURLResponse` using the provided closure. + /// + /// - Parameter closure: Closure used to modify the `CachedURLResponse`. + /// - Returns: The `ResponseCacher`. + public static func modify(using closure: @escaping ((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)) -> ResponseCacher { + ResponseCacher(behavior: .modify(closure)) + } +} diff --git a/Pods/Alamofire/Source/Combine.swift b/Pods/Alamofire/Source/Combine.swift new file mode 100644 index 0000000..416610e --- /dev/null +++ b/Pods/Alamofire/Source/Combine.swift @@ -0,0 +1,655 @@ +// +// Combine.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !((os(iOS) && (arch(i386) || arch(arm))) || os(Windows) || os(Linux) || os(Android)) + +import Combine +import Dispatch +import Foundation + +// MARK: - DataRequest / UploadRequest + +/// A Combine `Publisher` that publishes the `DataResponse` of the provided `DataRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DataResponsePublisher: Publisher { + public typealias Output = DataResponse + public typealias Failure = Never + + private typealias Handler = (@escaping (_ response: DataResponse) -> Void) -> DataRequest + + private let request: DataRequest + private let responseHandler: Handler + + /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. + /// + /// - Parameters: + /// - request: `DataRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `ResponseSerializer` used to produce the published `DataResponse`. + public init(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Creates an instance which will serialize responses using the provided `DataResponseSerializerProtocol`. + /// + /// - Parameters: + /// - request: `DataRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `DataResponseSerializerProtocol` used to produce the published `DataResponse`. + public init(_ request: DataRequest, + queue: DispatchQueue, + serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Publishes only the `Result` of the `DataResponse` value. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + map(\.result).eraseToAnyPublisher() + } + + /// Publishes the `Result` of the `DataResponse` as a single `Value` or fail with the `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber, DataResponsePublisher.Failure == S.Failure, DataResponsePublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + responseHandler: responseHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + @Protected + private var downstream: Downstream? + private let request: DataRequest + private let responseHandler: Handler + + init(request: DataRequest, responseHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.responseHandler = responseHandler + self.downstream = downstream + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream else { return } + + self.downstream = nil + responseHandler { response in + _ = downstream.receive(response) + downstream.receive(completion: .finished) + }.resume() + } + + func cancel() { + request.cancel() + downstream = nil + } + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +extension DataResponsePublisher where Value == Data? { + /// Creates an instance which publishes a `DataResponse` value without serialization. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DataRequest, queue: DispatchQueue) { + self.request = request + responseHandler = { request.response(queue: queue, completionHandler: $0) } + } +} + +extension DataRequest { + /// Creates a `DataResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` used to serialize response `Data`. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataResponsePublisher + where Serializer.SerializedObject == T { + DataResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding + /// will be determined by the server response, falling back to the default HTTP character + /// set, `ISO-8859-1`. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + @_disfavoredOverload + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by + /// default. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance which does not serialize the response before publishing. + /// + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishUnserialized(queue: DispatchQueue = .main) -> DataResponsePublisher { + DataResponsePublisher(self, queue: queue) + } +} + +// A Combine `Publisher` that publishes a sequence of `Stream` values received by the provided `DataStreamRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DataStreamPublisher: Publisher { + public typealias Output = DataStreamRequest.Stream + public typealias Failure = Never + + private typealias Handler = (@escaping DataStreamRequest.Handler) -> DataStreamRequest + + private let request: DataStreamRequest + private let streamHandler: Handler + + /// Creates an instance which will serialize responses using the provided `DataStreamSerializer`. + /// + /// - Parameters: + /// - request: `DataStreamRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `Stream` values will be published. `.main` by + /// default. + /// - serializer: `DataStreamSerializer` used to produce the published `Stream` values. + public init(_ request: DataStreamRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + streamHandler = { request.responseStream(using: serializer, on: queue, stream: $0) } + } + + /// Publishes only the `Result` of the `DataStreamRequest.Stream`'s `Event`s. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + compactMap { stream in + switch stream.event { + case let .stream(result): + return result + // If the stream has completed with an error, send the error value downstream as a `.failure`. + case let .complete(completion): + return completion.error.map(Result.failure) + } + } + .eraseToAnyPublisher() + } + + /// Publishes the streamed values of the `DataStreamRequest.Stream` as a sequence of `Value` or fail with the + /// `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + result().setFailureType(to: AFError.self).flatMap(\.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber, DataStreamPublisher.Failure == S.Failure, DataStreamPublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + streamHandler: streamHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + @Protected + private var downstream: Downstream? + private let request: DataStreamRequest + private let streamHandler: Handler + + init(request: DataStreamRequest, streamHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.streamHandler = streamHandler + self.downstream = downstream + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream else { return } + + self.downstream = nil + streamHandler { stream in + _ = downstream.receive(stream) + if case .complete = stream.event { + downstream.receive(completion: .finished) + } + }.resume() + } + + func cancel() { + request.cancel() + downstream = nil + } + } +} + +extension DataStreamRequest { + /// Creates a `DataStreamPublisher` for this instance using the given `DataStreamSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` used to serialize the streamed `Data`. + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishStream(using serializer: Serializer, + on queue: DispatchQueue = .main) -> DataStreamPublisher { + DataStreamPublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `PassthroughStreamSerializer` to stream `Data` + /// unserialized. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher { + publishStream(using: PassthroughStreamSerializer(), on: queue) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `StringStreamSerializer` to serialize stream + /// `Data` values into `String` values. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher { + publishStream(using: StringStreamSerializer(), on: queue) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `DecodableStreamSerializer` with the provided + /// parameters to serialize stream `Data` values into the provided type. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode stream `Data`. Inferred from the context by default. + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - decoder: `DataDecoder` instance used to decode stream `Data`. `JSONDecoder()` by default. + /// - preprocessor: `DataPreprocessor` which filters incoming stream `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + decoder: DataDecoder = JSONDecoder(), + preprocessor: DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher { + publishStream(using: DecodableStreamSerializer(decoder: decoder, + dataPreprocessor: preprocessor), + on: queue) + } +} + +/// A Combine `Publisher` that publishes the `DownloadResponse` of the provided `DownloadRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DownloadResponsePublisher: Publisher { + public typealias Output = DownloadResponse + public typealias Failure = Never + + private typealias Handler = (@escaping (_ response: DownloadResponse) -> Void) -> DownloadRequest + + private let request: DownloadRequest + private let responseHandler: Handler + + /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. + /// + /// - Parameters: + /// - request: `DownloadRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DownloadResponse` value will be published. `.main` by default. + /// - serializer: `ResponseSerializer` used to produce the published `DownloadResponse`. + public init(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Creates an instance which will serialize responses using the provided `DownloadResponseSerializerProtocol` value. + /// + /// - Parameters: + /// - request: `DownloadRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `DownloadResponseSerializerProtocol` used to produce the published `DownloadResponse`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DownloadRequest, + queue: DispatchQueue, + serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Publishes only the `Result` of the `DownloadResponse` value. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + map(\.result).eraseToAnyPublisher() + } + + /// Publishes the `Result` of the `DownloadResponse` as a single `Value` or fail with the `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber, DownloadResponsePublisher.Failure == S.Failure, DownloadResponsePublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + responseHandler: responseHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + @Protected + private var downstream: Downstream? + private let request: DownloadRequest + private let responseHandler: Handler + + init(request: DownloadRequest, responseHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.responseHandler = responseHandler + self.downstream = downstream + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream else { return } + + self.downstream = nil + responseHandler { response in + _ = downstream.receive(response) + downstream.receive(completion: .finished) + }.resume() + } + + func cancel() { + request.cancel() + downstream = nil + } + } +} + +extension DownloadRequest { + /// Creates a `DownloadResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` used to serialize the response `Data` from disk. + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher + where Serializer.SerializedObject == T { + DownloadResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DownloadResponsePublisher` for this instance using the given `DownloadResponseSerializerProtocol` and + /// `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `DownloadResponseSerializer` used to serialize the response `Data` from disk. + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher + where Serializer.SerializedObject == T { + DownloadResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `URLResponseSerializer` to serialize the + /// response. + /// + /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishURL(queue: DispatchQueue = .main) -> DownloadResponsePublisher { + publishResponse(using: URLResponseSerializer(), on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding + /// will be determined by the server response, falling back to the default HTTP character + /// set, `ISO-8859-1`. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + @_disfavoredOverload + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize + /// the response. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless + /// of status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +extension DownloadResponsePublisher where Value == URL? { + /// Creates an instance which publishes a `DownloadResponse` value without serialization. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DownloadRequest, queue: DispatchQueue) { + self.request = request + responseHandler = { request.response(queue: queue, completionHandler: $0) } + } +} + +extension DownloadRequest { + /// Creates a `DownloadResponsePublisher` for this instance which does not serialize the response before publishing. + /// + /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishUnserialized(on queue: DispatchQueue = .main) -> DownloadResponsePublisher { + DownloadResponsePublisher(self, queue: queue) + } +} + +#endif diff --git a/Pods/Alamofire/Source/Concurrency.swift b/Pods/Alamofire/Source/Concurrency.swift new file mode 100644 index 0000000..21e7e1e --- /dev/null +++ b/Pods/Alamofire/Source/Concurrency.swift @@ -0,0 +1,832 @@ +// +// Concurrency.swift +// +// Copyright (c) 2021 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if compiler(>=5.6.0) && canImport(_Concurrency) + +import Foundation + +// MARK: - Request Event Streams + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension Request { + /// Creates a `StreamOf` for the instance's upload progress. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func uploadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + uploadProgress(queue: underlyingQueue) { progress in + continuation.yield(progress) + } + } + } + + /// Creates a `StreamOf` for the instance's download progress. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func downloadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + downloadProgress(queue: underlyingQueue) { progress in + continuation.yield(progress) + } + } + } + + /// Creates a `StreamOf` for the `URLRequest`s produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func urlRequests(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onURLRequestCreation(on: underlyingQueue) { request in + continuation.yield(request) + } + } + } + + /// Creates a `StreamOf` for the `URLSessionTask`s produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func urlSessionTasks(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onURLSessionTaskCreation(on: underlyingQueue) { task in + continuation.yield(task) + } + } + } + + /// Creates a `StreamOf` for the cURL descriptions produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func cURLDescriptions(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + cURLDescription(on: underlyingQueue) { description in + continuation.yield(description) + } + } + } + + fileprivate func stream(of type: T.Type = T.self, + bufferingPolicy: StreamOf.BufferingPolicy = .unbounded, + yielder: @escaping (StreamOf.Continuation) -> Void) -> StreamOf { + StreamOf(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + yielder(continuation) + // Must come after serializers run in order to catch retry progress. + onFinish { + continuation.finish() + } + } + } +} + +// MARK: - DataTask + +/// Value used to `await` a `DataResponse` and associated values. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DataTask { + /// `DataResponse` produced by the `DataRequest` and its response handler. + public var response: DataResponse { + get async { + if shouldAutomaticallyCancel { + return await withTaskCancellationHandler { + await task.value + } onCancel: { + cancel() + } + } else { + return await task.value + } + } + } + + /// `Result` of any response serialization performed for the `response`. + public var result: Result { + get async { await response.result } + } + + /// `Value` returned by the `response`. + public var value: Value { + get async throws { + try await result.get() + } + } + + private let request: DataRequest + private let task: Task, Never> + private let shouldAutomaticallyCancel: Bool + + fileprivate init(request: DataRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { + self.request = request + self.task = task + self.shouldAutomaticallyCancel = shouldAutomaticallyCancel + } + + /// Cancel the underlying `DataRequest` and `Task`. + public func cancel() { + task.cancel() + } + + /// Resume the underlying `DataRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DataRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DataRequest { + /// Creates a `StreamOf` for the instance's responses. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func httpResponses(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onHTTPResponse(on: underlyingQueue) { response in + continuation.yield(response) + } + } + } + + #if swift(>=5.7) + /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataRequest` produces an + /// `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a + /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as + /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread, + /// so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse( + perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> ResponseDisposition + ) -> Self { + onHTTPResponse(on: underlyingQueue) { response, completionHandler in + Task { + let disposition = await handler(response) + completionHandler(disposition) + } + } + + return self + } + + /// Sets an async closure called whenever the `DataRequest` produces an `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an + /// arbitrary thread, so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> Void) -> Self { + onHTTPResponse { response in + await handler(response) + return .allow + } + + return self + } + #endif + + /// Creates a `DataTask` to `await` a `Data` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. + /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization of a `Decodable` value. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingDecodable(_ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization of a `String` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case + /// the encoding will be determined from the server response, falling back to the + /// default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization using the provided `ResponseSerializer` instance. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DataTask`. + public func serializingResponse(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DataTask { + dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + /// Creates a `DataTask` to `await` serialization using the provided `DataResponseSerializerProtocol` instance. + /// + /// - Parameters: + /// - serializer: `DataResponseSerializerProtocol` responsible for serializing the request, + /// response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DataTask`. + public func serializingResponse(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DataTask { + dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + private func dataTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, + forResponse onResponse: @escaping (@escaping (DataResponse) -> Void) -> Void) + -> DataTask { + let task = Task { + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + onResponse { + continuation.resume(returning: $0) + } + } + } onCancel: { + self.cancel() + } + } + + return DataTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) + } +} + +// MARK: - DownloadTask + +/// Value used to `await` a `DownloadResponse` and associated values. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DownloadTask { + /// `DownloadResponse` produced by the `DownloadRequest` and its response handler. + public var response: DownloadResponse { + get async { + if shouldAutomaticallyCancel { + return await withTaskCancellationHandler { + await task.value + } onCancel: { + cancel() + } + } else { + return await task.value + } + } + } + + /// `Result` of any response serialization performed for the `response`. + public var result: Result { + get async { await response.result } + } + + /// `Value` returned by the `response`. + public var value: Value { + get async throws { + try await result.get() + } + } + + private let task: Task, Never> + private let request: DownloadRequest + private let shouldAutomaticallyCancel: Bool + + fileprivate init(request: DownloadRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { + self.request = request + self.task = task + self.shouldAutomaticallyCancel = shouldAutomaticallyCancel + } + + /// Cancel the underlying `DownloadRequest` and `Task`. + public func cancel() { + task.cancel() + } + + /// Resume the underlying `DownloadRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DownloadRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DownloadRequest { + /// Creates a `DownloadTask` to `await` a `Data` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. + /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of a `Decodable` value. + /// + /// - Note: This serializer reads the entire response into memory before parsing. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDecodable(_ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of the downloaded file's `URL` on disk. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownloadedFileURL(automaticallyCancelling shouldAutomaticallyCancel: Bool = true) -> DownloadTask { + serializingDownload(using: URLResponseSerializer(), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of a `String` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// serializer. `PassthroughPreprocessor()` by default. + /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case + /// the encoding will be determined from the server response, falling back to the + /// default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization using the provided `ResponseSerializer` instance. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownload(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DownloadTask { + downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + /// Creates a `DownloadTask` to `await` serialization using the provided `DownloadResponseSerializerProtocol` + /// instance. + /// + /// - Parameters: + /// - serializer: `DownloadResponseSerializerProtocol` responsible for serializing the request, + /// response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownload(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DownloadTask { + downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + private func downloadTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, + forResponse onResponse: @escaping (@escaping (DownloadResponse) -> Void) -> Void) + -> DownloadTask { + let task = Task { + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + onResponse { + continuation.resume(returning: $0) + } + } + } onCancel: { + self.cancel() + } + } + + return DownloadTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) + } +} + +// MARK: - DataStreamTask + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DataStreamTask { + // Type of created streams. + public typealias Stream = StreamOf> + + private let request: DataStreamRequest + + fileprivate init(request: DataStreamRequest) { + self.request = request + } + + /// Creates a `Stream` of `Data` values from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStream(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) + } + } + + /// Creates a `Stream` of `UTF-8` `String`s from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// - Returns: + public func streamingStrings(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStreamString(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) + } + } + + /// Creates a `Stream` of `Decodable` values from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - type: `Decodable` type to be serialized from stream payloads. + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingDecodables(_ type: T.Type = T.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded) + -> Stream where T: Decodable { + streamingResponses(serializedUsing: DecodableStreamSerializer(), + automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy) + } + + /// Creates a `Stream` of values using the provided `DataStreamSerializer` from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` to use to serialize incoming `Data`. + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingResponses(serializedUsing serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded) + -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStream(using: serializer, + on: .streamCompletionQueue(forRequestID: request.id), + stream: onStream) + } + } + + private func createStream(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded, + forResponse onResponse: @escaping (@escaping (DataStreamRequest.Stream) -> Void) -> Void) + -> Stream { + StreamOf(bufferingPolicy: bufferingPolicy) { + guard shouldAutomaticallyCancel, + request.isInitialized || request.isResumed || request.isSuspended else { return } + + cancel() + } builder: { continuation in + onResponse { stream in + continuation.yield(stream) + if case .complete = stream.event { + continuation.finish() + } + } + } + } + + /// Cancel the underlying `DataStreamRequest`. + public func cancel() { + request.cancel() + } + + /// Resume the underlying `DataStreamRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DataStreamRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DataStreamRequest { + /// Creates a `StreamOf` for the instance's responses. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func httpResponses(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onHTTPResponse(on: underlyingQueue) { response in + continuation.yield(response) + } + } + } + + #if swift(>=5.7) + /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataStreamRequest` + /// produces an `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a + /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as + /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread, + /// so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> ResponseDisposition) -> Self { + onHTTPResponse(on: underlyingQueue) { response, completionHandler in + Task { + let disposition = await handler(response) + completionHandler(disposition) + } + } + + return self + } + + /// Sets an async closure called whenever the `DataStreamRequest` produces an `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an + /// arbitrary thread, so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> Void) -> Self { + onHTTPResponse { response in + await handler(response) + return .allow + } + + return self + } + #endif + + /// Creates a `DataStreamTask` used to `await` streams of serialized values. + /// + /// - Returns: The `DataStreamTask`. + public func streamTask() -> DataStreamTask { + DataStreamTask(request: self) + } +} + +extension DispatchQueue { + fileprivate static let singleEventQueue = DispatchQueue(label: "org.alamofire.concurrencySingleEventQueue", + attributes: .concurrent) + + fileprivate static func streamCompletionQueue(forRequestID id: UUID) -> DispatchQueue { + DispatchQueue(label: "org.alamofire.concurrencyStreamCompletionQueue-\(id)", target: .singleEventQueue) + } +} + +/// An asynchronous sequence generated from an underlying `AsyncStream`. Only produced by Alamofire. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct StreamOf: AsyncSequence { + public typealias AsyncIterator = Iterator + public typealias BufferingPolicy = AsyncStream.Continuation.BufferingPolicy + fileprivate typealias Continuation = AsyncStream.Continuation + + private let bufferingPolicy: BufferingPolicy + private let onTermination: (() -> Void)? + private let builder: (Continuation) -> Void + + fileprivate init(bufferingPolicy: BufferingPolicy = .unbounded, + onTermination: (() -> Void)? = nil, + builder: @escaping (Continuation) -> Void) { + self.bufferingPolicy = bufferingPolicy + self.onTermination = onTermination + self.builder = builder + } + + public func makeAsyncIterator() -> Iterator { + var continuation: AsyncStream.Continuation? + let stream = AsyncStream(bufferingPolicy: bufferingPolicy) { innerContinuation in + continuation = innerContinuation + builder(innerContinuation) + } + + return Iterator(iterator: stream.makeAsyncIterator()) { + continuation?.finish() + onTermination?() + } + } + + public struct Iterator: AsyncIteratorProtocol { + private final class Token { + private let onDeinit: () -> Void + + init(onDeinit: @escaping () -> Void) { + self.onDeinit = onDeinit + } + + deinit { + onDeinit() + } + } + + private var iterator: AsyncStream.AsyncIterator + private let token: Token + + init(iterator: AsyncStream.AsyncIterator, onCancellation: @escaping () -> Void) { + self.iterator = iterator + token = Token(onDeinit: onCancellation) + } + + public mutating func next() async -> Element? { + await iterator.next() + } + } +} + +#endif diff --git a/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..10cd273 --- /dev/null +++ b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation + +extension DispatchQueue { + /// Execute the provided closure after a `TimeInterval`. + /// + /// - Parameters: + /// - delay: `TimeInterval` to delay execution. + /// - closure: Closure to execute. + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/Pods/Alamofire/Source/EventMonitor.swift b/Pods/Alamofire/Source/EventMonitor.swift new file mode 100644 index 0000000..75b60f2 --- /dev/null +++ b/Pods/Alamofire/Source/EventMonitor.swift @@ -0,0 +1,907 @@ +// +// EventMonitor.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various +/// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses. +public protocol EventMonitor { + /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default. + var queue: DispatchQueue { get } + + // MARK: - URLSession Events + + // MARK: URLSessionDelegate Events + + /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method. + func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) + + // MARK: URLSessionTaskDelegate Events + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method. + func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method. + func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) + + // MARK: URLSessionDataDelegate Events + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:completionHandler:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) + + // MARK: URLSessionDownloadDelegate Events + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method. + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) + + // MARK: - Request Events + + /// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the + /// `URLRequest` will be adapted before being issued. + func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) + + /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails. + func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) + + /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`. + func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) + + /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`. + func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) + + /// Event called when a final `URLRequest` is created for a `Request`. + func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) + + /// Event called when a `URLSessionTask` subclass instance is created for a `Request`. + func request(_ request: Request, didCreateTask task: URLSessionTask) + + /// Event called when a `Request` receives a `URLSessionTaskMetrics` value. + func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) + + /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails. + func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) + + /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event + /// multiple times if it is retried. + func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) + + /// Event called when a `Request` is about to be retried. + func requestIsRetrying(_ request: Request) + + /// Event called when a `Request` finishes and response serializers are being called. + func requestDidFinish(_ request: Request) + + /// Event called when a `Request` receives a `resume` call. + func requestDidResume(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is resumed. + func request(_ request: Request, didResumeTask task: URLSessionTask) + + /// Event called when a `Request` receives a `suspend` call. + func requestDidSuspend(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is suspended. + func request(_ request: Request, didSuspendTask task: URLSessionTask) + + /// Event called when a `Request` receives a `cancel` call. + func requestDidCancel(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is cancelled. + func request(_ request: Request, didCancelTask task: URLSessionTask) + + // MARK: DataRequest Events + + /// Event called when a `DataRequest` calls a `Validation`. + func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) + + /// Event called when a `DataRequest` creates a `DataResponse` value without calling a `ResponseSerializer`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + // MARK: DataStreamRequest Events + + /// Event called when a `DataStreamRequest` calls a `Validation` closure. + /// + /// - Parameters: + /// - request: `DataStreamRequest` which is calling the `Validation`. + /// - urlRequest: `URLRequest` of the request being validated. + /// - response: `HTTPURLResponse` of the request being validated. + /// - result: Produced `ValidationResult`. + func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) + + /// Event called when a `DataStreamSerializer` produces a value from streamed `Data`. + /// + /// - Parameters: + /// - request: `DataStreamRequest` for which the value was serialized. + /// - result: `Result` of the serialization attempt. + func request(_ request: DataStreamRequest, didParseStream result: Result) + + // MARK: UploadRequest Events + + /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents. + func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) + + /// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error. + func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) + + /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if + /// the `InputStream` does not wrap a `Data` value or file `URL`. + func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) + + // MARK: DownloadRequest Events + + /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved. + func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) + + /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the + /// downloaded file will be moved to. + func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) + + /// Event called when a `DownloadRequest` calls a `Validation`. + func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) + + /// Event called when a `DownloadRequest` creates a `DownloadResponse` without calling a `ResponseSerializer`. + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) + + /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse` + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) +} + +extension EventMonitor { + /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default. + public var queue: DispatchQueue { .main } + + // MARK: Default Implementations + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) {} + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didFinishCollecting metrics: URLSessionTaskMetrics) {} + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {} + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {} + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) {} + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {} + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) {} + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {} + public func request(_ request: Request, + didAdaptInitialRequest initialRequest: URLRequest, + to adaptedRequest: URLRequest) {} + public func request(_ request: Request, + didFailToAdaptURLRequest initialRequest: URLRequest, + withError error: AFError) {} + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didCreateTask task: URLSessionTask) {} + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {} + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {} + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {} + public func requestIsRetrying(_ request: Request) {} + public func requestDidFinish(_ request: Request) {} + public func requestDidResume(_ request: Request) {} + public func request(_ request: Request, didResumeTask task: URLSessionTask) {} + public func requestDidSuspend(_ request: Request) {} + public func request(_ request: Request, didSuspendTask task: URLSessionTask) {} + public func requestDidCancel(_ request: Request) {} + public func request(_ request: Request, didCancelTask task: URLSessionTask) {} + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) {} + public func request(_ request: DataStreamRequest, didParseStream result: Result) {} + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {} + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {} + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {} + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {} + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {} + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} +} + +/// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues. +public final class CompositeEventMonitor: EventMonitor { + public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor", qos: .utility) + + let monitors: [EventMonitor] + + init(monitors: [EventMonitor]) { + self.monitors = monitors + } + + func performEvent(_ event: @escaping (EventMonitor) -> Void) { + queue.async { + for monitor in self.monitors { + monitor.queue.async { event(monitor) } + } + } + } + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) { + performEvent { $0.urlSession(session, task: task, didReceive: challenge) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + performEvent { + $0.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + } + + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + performEvent { + $0.urlSession(session, taskNeedsNewBodyStream: task) + } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + performEvent { + $0.urlSession(session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request) + } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) } + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) } + } + + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) { + performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: response) } + } + + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) } + } + + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) { + performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) { + performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } + } + + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) } + } + + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) } + } + + public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) } + } + + public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) } + } + + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateURLRequest: urlRequest) } + } + + public func request(_ request: Request, didCreateTask task: URLSessionTask) { + performEvent { $0.request(request, didCreateTask: task) } + } + + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + performEvent { $0.request(request, didGatherMetrics: metrics) } + } + + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + performEvent { $0.request(request, didFailTask: task, earlyWithError: error) } + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + performEvent { $0.request(request, didCompleteTask: task, with: error) } + } + + public func requestIsRetrying(_ request: Request) { + performEvent { $0.requestIsRetrying(request) } + } + + public func requestDidFinish(_ request: Request) { + performEvent { $0.requestDidFinish(request) } + } + + public func requestDidResume(_ request: Request) { + performEvent { $0.requestDidResume(request) } + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + performEvent { $0.request(request, didResumeTask: task) } + } + + public func requestDidSuspend(_ request: Request) { + performEvent { $0.requestDidSuspend(request) } + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + performEvent { $0.request(request, didSuspendTask: task) } + } + + public func requestDidCancel(_ request: Request) { + performEvent { $0.requestDidCancel(request) } + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + performEvent { $0.request(request, didCancelTask: task) } + } + + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + data: data, + withResult: result) + } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + withResult: result) + } + } + + public func request(_ request: DataStreamRequest, didParseStream result: Result) { + performEvent { $0.request(request, didParseStream: result) } + } + + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + performEvent { $0.request(request, didCreateUploadable: uploadable) } + } + + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateUploadableWithError: error) } + } + + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + performEvent { $0.request(request, didProvideInputStream: stream) } + } + + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) } + } + + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + performEvent { $0.request(request, didCreateDestinationURL: url) } + } + + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + fileURL: fileURL, + withResult: result) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } +} + +/// `EventMonitor` that allows optional closures to be set to receive events. +open class ClosureEventMonitor: EventMonitor { + /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)? + + /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)? + + /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)? + + /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event. + open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event. + open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)? + + /// Closure called on the `urlSession(_:dataTask:didReceive:completionHandler:)` event. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> Void)? + + /// Closure that receives the `urlSession(_:dataTask:didReceive:)` event. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` + /// event. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: - Request Events + + /// Closure called on the `request(_:didCreateInitialURLRequest:)` event. + open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event. + open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)? + + /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event. + open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event. + open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didCreateURLRequest:)` event. + open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didCreateTask:)` event. + open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didGatherMetrics:)` event. + open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `request(_:didFailTask:earlyWithError:)` event. + open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)? + + /// Closure called on the `request(_:didCompleteTask:with:)` event. + open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)? + + /// Closure called on the `requestIsRetrying(_:)` event. + open var requestIsRetrying: ((Request) -> Void)? + + /// Closure called on the `requestDidFinish(_:)` event. + open var requestDidFinish: ((Request) -> Void)? + + /// Closure called on the `requestDidResume(_:)` event. + open var requestDidResume: ((Request) -> Void)? + + /// Closure called on the `request(_:didResumeTask:)` event. + open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidSuspend(_:)` event. + open var requestDidSuspend: ((Request) -> Void)? + + /// Closure called on the `request(_:didSuspendTask:)` event. + open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidCancel(_:)` event. + open var requestDidCancel: ((Request) -> Void)? + + /// Closure called on the `request(_:didCancelTask:)` event. + open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event. + open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseResponse: ((DataRequest, DataResponse) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:withResult:)` event. + open var requestDidValidateRequestResponseWithResult: ((DataStreamRequest, URLRequest?, HTTPURLResponse, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didCreateUploadable:)` event. + open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)? + + /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event. + open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didProvideInputStream:)` event. + open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)? + + /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event. + open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result) -> Void)? + + /// Closure called on the `request(_:didCreateDestinationURL:)` event. + open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event. + open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse) -> Void)? + + public let queue: DispatchQueue + + /// Creates an instance using the provided queue. + /// + /// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default. + public init(queue: DispatchQueue = .main) { + self.queue = queue + } + + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) { + taskDidReceiveChallenge?(session, task, challenge) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + taskNeedNewBodyStream?(session, task) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + taskWillPerformHTTPRedirection?(session, task, response, request) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + taskDidFinishCollectingMetrics?(session, task, metrics) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + taskDidComplete?(session, task, error) + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + taskIsWaitingForConnectivity?(session, task) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) { + dataTaskDidReceiveResponse?(session, dataTask, response) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + dataTaskDidReceiveData?(session, dataTask, data) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) { + dataTaskWillCacheResponse?(session, dataTask, proposedResponse) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location) + } + + // MARK: Request Events + + open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + requestDidCreateInitialURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + requestDidFailToCreateURLRequestWithError?(request, error) + } + + open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest) + } + + open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error) + } + + open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + requestDidCreateURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didCreateTask task: URLSessionTask) { + requestDidCreateTask?(request, task) + } + + open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + requestDidGatherMetrics?(request, metrics) + } + + open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + requestDidFailTaskEarlyWithError?(request, task, error) + } + + open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + requestDidCompleteTaskWithError?(request, task, error) + } + + open func requestIsRetrying(_ request: Request) { + requestIsRetrying?(request) + } + + open func requestDidFinish(_ request: Request) { + requestDidFinish?(request) + } + + open func requestDidResume(_ request: Request) { + requestDidResume?(request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + requestDidResumeTask?(request, task) + } + + open func requestDidSuspend(_ request: Request) { + requestDidSuspend?(request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + requestDidSuspendTask?(request, task) + } + + open func requestDidCancel(_ request: Request) { + requestDidCancel?(request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + requestDidCancelTask?(request, task) + } + + open func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result) + } + + open func request(_ request: DataRequest, didParseResponse response: DataResponse) { + requestDidParseResponse?(request, response) + } + + public func request(_ request: DataStreamRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseWithResult?(request, urlRequest, response, result) + } + + open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + requestDidCreateUploadable?(request, uploadable) + } + + open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + requestDidFailToCreateUploadableWithError?(request, error) + } + + open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + requestDidProvideInputStream?(request, stream) + } + + open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + requestDidFinishDownloadingUsingTaskWithResult?(request, task, result) + } + + open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + requestDidCreateDestinationURL?(request, url) + } + + open func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseFileURLWithResult?(request, + urlRequest, + response, + fileURL, + result) + } + + open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + requestDidParseDownloadResponse?(request, response) + } +} diff --git a/Pods/Alamofire/Source/HTTPHeaders.swift b/Pods/Alamofire/Source/HTTPHeaders.swift new file mode 100644 index 0000000..08d4799 --- /dev/null +++ b/Pods/Alamofire/Source/HTTPHeaders.swift @@ -0,0 +1,452 @@ +// +// HTTPHeaders.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// An order-preserving and case-insensitive representation of HTTP headers. +public struct HTTPHeaders { + private var headers: [HTTPHeader] = [] + + /// Creates an empty instance. + public init() {} + + /// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last + /// name and value encountered. + public init(_ headers: [HTTPHeader]) { + headers.forEach { update($0) } + } + + /// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name + /// and value encountered. + public init(_ dictionary: [String: String]) { + dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) } + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader value. + public mutating func add(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func add(_ header: HTTPHeader) { + update(header) + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader value. + public mutating func update(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func update(_ header: HTTPHeader) { + guard let index = headers.index(of: header.name) else { + headers.append(header) + return + } + + headers.replaceSubrange(index...index, with: [header]) + } + + /// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance. + /// + /// - Parameter name: The name of the `HTTPHeader` to remove. + public mutating func remove(name: String) { + guard let index = headers.index(of: name) else { return } + + headers.remove(at: index) + } + + /// Sort the current instance by header name, case insensitively. + public mutating func sort() { + headers.sort { $0.name.lowercased() < $1.name.lowercased() } + } + + /// Returns an instance sorted by header name. + /// + /// - Returns: A copy of the current instance sorted by name. + public func sorted() -> HTTPHeaders { + var headers = self + headers.sort() + + return headers + } + + /// Case-insensitively find a header's value by name. + /// + /// - Parameter name: The name of the header to search for, case-insensitively. + /// + /// - Returns: The value of header, if it exists. + public func value(for name: String) -> String? { + guard let index = headers.index(of: name) else { return nil } + + return headers[index].value + } + + /// Case-insensitively access the header with the given name. + /// + /// - Parameter name: The name of the header. + public subscript(_ name: String) -> String? { + get { value(for: name) } + set { + if let value = newValue { + update(name: name, value: value) + } else { + remove(name: name) + } + } + } + + /// The dictionary representation of all headers. + /// + /// This representation does not preserve the current order of the instance. + public var dictionary: [String: String] { + let namesAndValues = headers.map { ($0.name, $0.value) } + + return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last }) + } +} + +extension HTTPHeaders: ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, String)...) { + elements.forEach { update(name: $0.0, value: $0.1) } + } +} + +extension HTTPHeaders: ExpressibleByArrayLiteral { + public init(arrayLiteral elements: HTTPHeader...) { + self.init(elements) + } +} + +extension HTTPHeaders: Sequence { + public func makeIterator() -> IndexingIterator<[HTTPHeader]> { + headers.makeIterator() + } +} + +extension HTTPHeaders: Collection { + public var startIndex: Int { + headers.startIndex + } + + public var endIndex: Int { + headers.endIndex + } + + public subscript(position: Int) -> HTTPHeader { + headers[position] + } + + public func index(after i: Int) -> Int { + headers.index(after: i) + } +} + +extension HTTPHeaders: CustomStringConvertible { + public var description: String { + headers.map(\.description) + .joined(separator: "\n") + } +} + +// MARK: - HTTPHeader + +/// A representation of a single HTTP header's name / value pair. +public struct HTTPHeader: Hashable { + /// Name of the header. + public let name: String + + /// Value of the header. + public let value: String + + /// Creates an instance from the given `name` and `value`. + /// + /// - Parameters: + /// - name: The name of the header. + /// - value: The value of the header. + public init(name: String, value: String) { + self.name = name + self.value = value + } +} + +extension HTTPHeader: CustomStringConvertible { + public var description: String { + "\(name): \(value)" + } +} + +extension HTTPHeader { + /// Returns an `Accept` header. + /// + /// - Parameter value: The `Accept` value. + /// - Returns: The header. + public static func accept(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept", value: value) + } + + /// Returns an `Accept-Charset` header. + /// + /// - Parameter value: The `Accept-Charset` value. + /// - Returns: The header. + public static func acceptCharset(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Charset", value: value) + } + + /// Returns an `Accept-Language` header. + /// + /// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages. + /// Use `HTTPHeader.defaultAcceptLanguage`. + /// + /// - Parameter value: The `Accept-Language` value. + /// + /// - Returns: The header. + public static func acceptLanguage(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Language", value: value) + } + + /// Returns an `Accept-Encoding` header. + /// + /// Alamofire offers a default accept encoding value that provides the most common values. Use + /// `HTTPHeader.defaultAcceptEncoding`. + /// + /// - Parameter value: The `Accept-Encoding` value. + /// + /// - Returns: The header + public static func acceptEncoding(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Encoding", value: value) + } + + /// Returns a `Basic` `Authorization` header using the `username` and `password` provided. + /// + /// - Parameters: + /// - username: The username of the header. + /// - password: The password of the header. + /// + /// - Returns: The header. + public static func authorization(username: String, password: String) -> HTTPHeader { + let credential = Data("\(username):\(password)".utf8).base64EncodedString() + + return authorization("Basic \(credential)") + } + + /// Returns a `Bearer` `Authorization` header using the `bearerToken` provided + /// + /// - Parameter bearerToken: The bearer token. + /// + /// - Returns: The header. + public static func authorization(bearerToken: String) -> HTTPHeader { + authorization("Bearer \(bearerToken)") + } + + /// Returns an `Authorization` header. + /// + /// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use + /// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use + /// `HTTPHeader.authorization(bearerToken:)`. + /// + /// - Parameter value: The `Authorization` value. + /// + /// - Returns: The header. + public static func authorization(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Authorization", value: value) + } + + /// Returns a `Content-Disposition` header. + /// + /// - Parameter value: The `Content-Disposition` value. + /// + /// - Returns: The header. + public static func contentDisposition(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Disposition", value: value) + } + + /// Returns a `Content-Encoding` header. + /// + /// - Parameter value: The `Content-Encoding`. + /// + /// - Returns: The header. + public static func contentEncoding(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Encoding", value: value) + } + + /// Returns a `Content-Type` header. + /// + /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not + /// be necessary to manually set this value. + /// + /// - Parameter value: The `Content-Type` value. + /// + /// - Returns: The header. + public static func contentType(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Type", value: value) + } + + /// Returns a `User-Agent` header. + /// + /// - Parameter value: The `User-Agent` value. + /// + /// - Returns: The header. + public static func userAgent(_ value: String) -> HTTPHeader { + HTTPHeader(name: "User-Agent", value: value) + } +} + +extension Array where Element == HTTPHeader { + /// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists. + func index(of name: String) -> Int? { + let lowercasedName = name.lowercased() + return firstIndex { $0.name.lowercased() == lowercasedName } + } +} + +// MARK: - Defaults + +extension HTTPHeaders { + /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and + /// `User-Agent`. + public static let `default`: HTTPHeaders = [.defaultAcceptEncoding, + .defaultAcceptLanguage, + .defaultUserAgent] +} + +extension HTTPHeader { + /// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS + /// versions. + /// + /// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) . + public static let defaultAcceptEncoding: HTTPHeader = { + let encodings: [String] + if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) { + encodings = ["br", "gzip", "deflate"] + } else { + encodings = ["gzip", "deflate"] + } + + return .acceptEncoding(encodings.qualityEncoded()) + }() + + /// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's + /// `preferredLanguages`. + /// + /// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5). + public static let defaultAcceptLanguage: HTTPHeader = .acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded()) + + /// Returns Alamofire's default `User-Agent` header. + /// + /// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3). + /// + /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0` + public static let defaultUserAgent: HTTPHeader = { + let info = Bundle.main.infoDictionary + let executable = (info?["CFBundleExecutable"] as? String) ?? + (ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ?? + "Unknown" + let bundle = info?["CFBundleIdentifier"] as? String ?? "Unknown" + let appVersion = info?["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info?["CFBundleVersion"] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + let osName: String = { + #if os(iOS) + #if targetEnvironment(macCatalyst) + return "macOS(Catalyst)" + #else + return "iOS" + #endif + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "macOS" + #elseif os(Linux) + return "Linux" + #elseif os(Windows) + return "Windows" + #elseif os(Android) + return "Android" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion = "Alamofire/\(version)" + + let userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + + return .userAgent(userAgent) + }() +} + +extension Collection where Element == String { + func qualityEncoded() -> String { + enumerated().map { index, encoding in + let quality = 1.0 - (Double(index) * 0.1) + return "\(encoding);q=\(quality)" + }.joined(separator: ", ") + } +} + +// MARK: - System Type Extensions + +extension URLRequest { + /// Returns `allHTTPHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + get { allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() } + set { allHTTPHeaderFields = newValue.dictionary } + } +} + +extension HTTPURLResponse { + /// Returns `allHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() + } +} + +extension URLSessionConfiguration { + /// Returns `httpAdditionalHeaders` as `HTTPHeaders`. + public var headers: HTTPHeaders { + get { (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() } + set { httpAdditionalHeaders = newValue.dictionary } + } +} diff --git a/Pods/Alamofire/Source/HTTPMethod.swift b/Pods/Alamofire/Source/HTTPMethod.swift new file mode 100644 index 0000000..539d214 --- /dev/null +++ b/Pods/Alamofire/Source/HTTPMethod.swift @@ -0,0 +1,56 @@ +// +// HTTPMethod.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +/// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so +/// `HTTPMethod.get != HTTPMethod(rawValue: "get")`. +/// +/// See https://tools.ietf.org/html/rfc7231#section-4.3 +public struct HTTPMethod: RawRepresentable, Equatable, Hashable { + /// `CONNECT` method. + public static let connect = HTTPMethod(rawValue: "CONNECT") + /// `DELETE` method. + public static let delete = HTTPMethod(rawValue: "DELETE") + /// `GET` method. + public static let get = HTTPMethod(rawValue: "GET") + /// `HEAD` method. + public static let head = HTTPMethod(rawValue: "HEAD") + /// `OPTIONS` method. + public static let options = HTTPMethod(rawValue: "OPTIONS") + /// `PATCH` method. + public static let patch = HTTPMethod(rawValue: "PATCH") + /// `POST` method. + public static let post = HTTPMethod(rawValue: "POST") + /// `PUT` method. + public static let put = HTTPMethod(rawValue: "PUT") + /// `QUERY` method. + public static let query = HTTPMethod(rawValue: "QUERY") + /// `TRACE` method. + public static let trace = HTTPMethod(rawValue: "TRACE") + + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } +} diff --git a/Pods/Alamofire/Source/MultipartFormData.swift b/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..3fb6e2b --- /dev/null +++ b/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,601 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if canImport(MobileCoreServices) +import MobileCoreServices +#elseif canImport(CoreServices) +import CoreServices +#endif + +/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode +/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead +/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the +/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for +/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. +/// +/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well +/// and the w3 form documentation. +/// +/// - https://www.ietf.org/rfc/rfc2388.txt +/// - https://www.ietf.org/rfc/rfc2045.txt +/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +open class MultipartFormData { + // MARK: - Helper Types + + enum EncodingCharacters { + static let crlf = "\r\n" + } + + enum BoundaryGenerator { + enum BoundaryType { + case initial, encapsulated, final + } + + static func randomBoundary() -> String { + let first = UInt32.random(in: UInt32.min...UInt32.max) + let second = UInt32.random(in: UInt32.min...UInt32.max) + + return String(format: "alamofire.boundary.%08x%08x", first, second) + } + + static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + let boundaryText: String + + switch boundaryType { + case .initial: + boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" + case .encapsulated: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" + case .final: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" + } + + return Data(boundaryText.utf8) + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// Default memory threshold used when encoding `MultipartFormData`, in bytes. + public static let encodingMemoryThreshold: UInt64 = 10_000_000 + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + let fileManager: FileManager + + private var bodyParts: [BodyPart] + private var bodyPartError: AFError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /// Creates an instance. + /// + /// - Parameters: + /// - fileManager: `FileManager` to use for file operations, if needed. + /// - boundary: Boundary `String` used to separate body parts. + public init(fileManager: FileManager = .default, boundary: String? = nil) { + self.fileManager = fileManager + self.boundary = boundary ?? BoundaryGenerator.randomBoundary() + bodyParts = [] + + // + // The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + // information, please refer to the following article: + // - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + // + streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /// Creates a body part from the data and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - Parameters: + /// - data: `Data` to encoding into the instance. + /// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the file and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + /// system associated MIME type. + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. + public func append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// Creates a body part from the file and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + /// - Content-Type: #{mimeType} (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header. + public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + #if !(os(Linux) || os(Windows) || os(Android)) + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + #endif + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, headers: headers) + } + + /// Creates a body part from the stream and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header. + public func append(_ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part with the stream, length, and headers and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - headers: `HTTPHeaders` for the body part. + public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all appended body parts into a single `Data` value. + /// + /// - Note: This method will load all the appended body parts into memory all at the same time. This method should + /// only be used when the encoded data will have a small memory footprint. For large data cases, please use + /// the `writeEncodedData(to:))` method. + /// + /// - Returns: The encoded `Data`, if encoding is successful. + /// - Throws: An `AFError` if encoding encounters an error. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(encodedData) + } + + return encoded + } + + /// Writes all appended body parts to the given file `URL`. + /// + /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, + /// this approach is very memory efficient and should be used for large body part data. + /// + /// - Parameter fileURL: File `URL` to which to write the form data. + /// - Throws: An `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if fileManager.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" } + .joined() + + EncodingCharacters.crlf + + return Data(headerText.utf8) + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + guard UInt64(encoded.count) == bodyPart.bodyContentLength else { + let error = AFError.UnexpectedInputStreamLength(bytesExpected: bodyPart.bodyContentLength, + bytesRead: UInt64(encoded.count)) + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + var bytesLeftToRead = bodyPart.bodyContentLength + while inputStream.hasBytesAvailable && bytesLeftToRead > 0 { + let bufferSize = min(streamBufferSize, Int(bytesLeftToRead)) + var buffer = [UInt8](repeating: 0, count: bufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: bufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. HTTPHeaders { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers: HTTPHeaders = [.contentDisposition(disposition)] + if let mimeType = mimeType { headers.add(.contentType(mimeType)) } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} + +#if canImport(UniformTypeIdentifiers) +import UniformTypeIdentifiers + +extension MultipartFormData { + // MARK: - Private - Mime Type + + private func mimeType(forPathExtension pathExtension: String) -> String { + #if swift(>=5.9) + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, visionOS 1, *) { + return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream" + } else { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + + return "application/octet-stream" + } + #else + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) { + return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream" + } else { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + + return "application/octet-stream" + } + #endif + } +} + +#else + +extension MultipartFormData { + // MARK: - Private - Mime Type + + private func mimeType(forPathExtension pathExtension: String) -> String { + #if canImport(CoreServices) || canImport(MobileCoreServices) + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + #endif + + return "application/octet-stream" + } +} + +#endif diff --git a/Pods/Alamofire/Source/MultipartUpload.swift b/Pods/Alamofire/Source/MultipartUpload.swift new file mode 100644 index 0000000..ceda21f --- /dev/null +++ b/Pods/Alamofire/Source/MultipartUpload.swift @@ -0,0 +1,89 @@ +// +// MultipartUpload.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Internal type which encapsulates a `MultipartFormData` upload. +final class MultipartUpload { + lazy var result = Result { try build() } + + @Protected + private(set) var multipartFormData: MultipartFormData + let encodingMemoryThreshold: UInt64 + let request: URLRequestConvertible + let fileManager: FileManager + + init(encodingMemoryThreshold: UInt64, + request: URLRequestConvertible, + multipartFormData: MultipartFormData) { + self.encodingMemoryThreshold = encodingMemoryThreshold + self.request = request + fileManager = multipartFormData.fileManager + self.multipartFormData = multipartFormData + } + + func build() throws -> UploadRequest.Uploadable { + let uploadable: UploadRequest.Uploadable + if $multipartFormData.contentLength < encodingMemoryThreshold { + let data = try $multipartFormData.read { try $0.encode() } + + uploadable = .data(data) + } else { + let tempDirectoryURL = fileManager.temporaryDirectory + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + + do { + try $multipartFormData.read { try $0.writeEncodedData(to: fileURL) } + } catch { + // Cleanup after attempted write if it fails. + try? fileManager.removeItem(at: fileURL) + throw error + } + + uploadable = .file(fileURL, shouldRemove: true) + } + + return uploadable + } +} + +extension MultipartUpload: UploadConvertible { + func asURLRequest() throws -> URLRequest { + var urlRequest = try request.asURLRequest() + + $multipartFormData.read { multipartFormData in + urlRequest.headers.add(.contentType(multipartFormData.contentType)) + } + + return urlRequest + } + + func createUploadable() throws -> UploadRequest.Uploadable { + try result.get() + } +} diff --git a/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..8ba715b --- /dev/null +++ b/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,301 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(SystemConfiguration) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +open class NetworkReachabilityManager { + /// Defines the various states of network reachability. + public enum NetworkReachabilityStatus { + /// It is unknown whether the network is reachable. + case unknown + /// The network is not reachable. + case notReachable + /// The network is reachable on the associated `ConnectionType`. + case reachable(ConnectionType) + + init(_ flags: SCNetworkReachabilityFlags) { + guard flags.isActuallyReachable else { self = .notReachable; return } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + if flags.isCellular { networkStatus = .reachable(.cellular) } + + self = networkStatus + } + + /// Defines the various connection types detected by reachability flags. + public enum ConnectionType { + /// The connection type is either over Ethernet or WiFi. + case ethernetOrWiFi + /// The connection type is a cellular connection. + case cellular + } + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`. + public static let `default` = NetworkReachabilityManager() + + // MARK: - Properties + + /// Whether the network is currently reachable. + open var isReachable: Bool { isReachableOnCellular || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the cellular interface. + /// + /// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended. + /// Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued. + /// + open var isReachableOnCellular: Bool { status == .reachable(.cellular) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + open var isReachableOnEthernetOrWiFi: Bool { status == .reachable(.ethernetOrWiFi) } + + /// `DispatchQueue` on which reachability will update. + public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue") + + /// Flags of the current reachability type, if any. + open var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + return SCNetworkReachabilityGetFlags(reachability, &flags) ? flags : nil + } + + /// The current network reachability status. + open var status: NetworkReachabilityStatus { + flags.map(NetworkReachabilityStatus.init) ?? .unknown + } + + /// Mutable state storage. + struct MutableState { + /// A closure executed when the network reachability status changes. + var listener: Listener? + /// `DispatchQueue` on which listeners will be called. + var listenerQueue: DispatchQueue? + /// Previously calculated status. + var previousStatus: NetworkReachabilityStatus? + } + + /// `SCNetworkReachability` instance providing notifications. + private let reachability: SCNetworkReachability + + /// Protected storage for mutable state. + @Protected + private var mutableState = MutableState() + + // MARK: - Initialization + + /// Creates an instance with the specified host. + /// + /// - Note: The `host` value must *not* contain a scheme, just the hostname. + /// + /// - Parameters: + /// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`). + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + + self.init(reachability: reachability) + } + + /// Creates an instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + public convenience init?() { + var zero = sockaddr() + zero.sa_len = UInt8(MemoryLayout.size) + zero.sa_family = sa_family_t(AF_INET) + + guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - Note: Stops and removes any existing listener. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default. + /// - listener: `Listener` closure called when reachability changes. + /// + /// - Returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + open func startListening(onQueue queue: DispatchQueue = .main, + onUpdatePerforming listener: @escaping Listener) -> Bool { + stopListening() + + $mutableState.write { state in + state.listenerQueue = queue + state.listener = listener + } + + let weakManager = WeakManager(manager: self) + + var context = SCNetworkReachabilityContext( + version: 0, + info: Unmanaged.passUnretained(weakManager).toOpaque(), + retain: { info in + let unmanaged = Unmanaged.fromOpaque(info) + _ = unmanaged.retain() + + return UnsafeRawPointer(unmanaged.toOpaque()) + }, + release: { info in + let unmanaged = Unmanaged.fromOpaque(info) + unmanaged.release() + }, + copyDescription: { info in + let unmanaged = Unmanaged.fromOpaque(info) + let weakManager = unmanaged.takeUnretainedValue() + let description = weakManager.manager?.flags?.readableDescription ?? "nil" + + return Unmanaged.passRetained(description as CFString) + } + ) + let callback: SCNetworkReachabilityCallBack = { _, flags, info in + guard let info = info else { return } + + let weakManager = Unmanaged.fromOpaque(info).takeUnretainedValue() + weakManager.manager?.notifyListener(flags) + } + + let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue) + let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context) + + // Manually call listener to give initial state, since the framework may not. + if let currentFlags = flags { + reachabilityQueue.async { + self.notifyListener(currentFlags) + } + } + + return callbackAdded && queueAdded + } + + /// Stops listening for changes in network reachability status. + open func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + $mutableState.write { state in + state.listener = nil + state.listenerQueue = nil + state.previousStatus = nil + } + } + + // MARK: - Internal - Listener Notification + + /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed. + /// + /// - Note: Should only be called from the `reachabilityQueue`. + /// + /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status. + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + let newStatus = NetworkReachabilityStatus(flags) + + $mutableState.write { state in + guard state.previousStatus != newStatus else { return } + + state.previousStatus = newStatus + + let listener = state.listener + state.listenerQueue?.async { listener?(newStatus) } + } + } + + private final class WeakManager { + weak var manager: NetworkReachabilityManager? + + init(manager: NetworkReachabilityManager?) { + self.manager = manager + } + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +extension SCNetworkReachabilityFlags { + var isReachable: Bool { contains(.reachable) } + var isConnectionRequired: Bool { contains(.connectionRequired) } + var canConnectAutomatically: Bool { contains(.connectionOnDemand) || contains(.connectionOnTraffic) } + var canConnectWithoutUserInteraction: Bool { canConnectAutomatically && !contains(.interventionRequired) } + var isActuallyReachable: Bool { isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) } + var isCellular: Bool { + #if swift(>=5.9) + #if os(iOS) || os(tvOS) || os(visionOS) + return contains(.isWWAN) + #else + return false + #endif + #else + #if os(iOS) || os(tvOS) + return contains(.isWWAN) + #else + return false + #endif + #endif + } + + /// Human readable `String` for all states, to help with debugging. + var readableDescription: String { + let W = isCellular ? "W" : "-" + let R = isReachable ? "R" : "-" + let c = isConnectionRequired ? "c" : "-" + let t = contains(.transientConnection) ? "t" : "-" + let i = contains(.interventionRequired) ? "i" : "-" + let C = contains(.connectionOnTraffic) ? "C" : "-" + let D = contains(.connectionOnDemand) ? "D" : "-" + let l = contains(.isLocalAddress) ? "l" : "-" + let d = contains(.isDirect) ? "d" : "-" + let a = contains(.connectionAutomatic) ? "a" : "-" + + return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)" + } +} +#endif diff --git a/Pods/Alamofire/Source/Notifications.swift b/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..66434b6 --- /dev/null +++ b/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,115 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`. + public static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume") + /// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`. + public static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend") + /// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`. + public static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel") + /// Posted when a `Request` is finished. The `Notification` contains the completed `Request`. + public static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish") + + /// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didResumeTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResumeTask") + /// Posted when a `URLSessionTask` is suspended. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didSuspendTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspendTask") + /// Posted when a `URLSessionTask` is cancelled. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didCancelTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancelTask") + /// Posted when a `URLSessionTask` is completed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask") +} + +// MARK: - + +extension Notification { + /// The `Request` contained by the instance's `userInfo`, `nil` otherwise. + public var request: Request? { + userInfo?[String.requestKey] as? Request + } + + /// Convenience initializer for a `Notification` containing a `Request` payload. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + init(name: Notification.Name, request: Request) { + self.init(name: name, object: nil, userInfo: [String.requestKey: request]) + } +} + +extension NotificationCenter { + /// Convenience function for posting notifications with `Request` payloads. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + func postNotification(named name: Notification.Name, with request: Request) { + let notification = Notification(name: name, request: request) + post(notification) + } +} + +extension String { + /// User info dictionary key representing the `Request` associated with the notification. + fileprivate static let requestKey = "org.alamofire.notification.key.request" +} + +/// `EventMonitor` that provides Alamofire's notifications. +public final class AlamofireNotifications: EventMonitor { + public func requestDidResume(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didResumeNotification, with: request) + } + + public func requestDidSuspend(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didSuspendNotification, with: request) + } + + public func requestDidCancel(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didCancelNotification, with: request) + } + + public func requestDidFinish(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didFinishNotification, with: request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didResumeTaskNotification, with: request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didSuspendTaskNotification, with: request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didCancelTaskNotification, with: request) + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request) + } +} diff --git a/Pods/Alamofire/Source/OperationQueue+Alamofire.swift b/Pods/Alamofire/Source/OperationQueue+Alamofire.swift new file mode 100644 index 0000000..b06a0cc --- /dev/null +++ b/Pods/Alamofire/Source/OperationQueue+Alamofire.swift @@ -0,0 +1,49 @@ +// +// OperationQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension OperationQueue { + /// Creates an instance using the provided parameters. + /// + /// - Parameters: + /// - qualityOfService: `QualityOfService` to be applied to the queue. `.default` by default. + /// - maxConcurrentOperationCount: Maximum concurrent operations. + /// `OperationQueue.defaultMaxConcurrentOperationCount` by default. + /// - underlyingQueue: Underlying `DispatchQueue`. `nil` by default. + /// - name: Name for the queue. `nil` by default. + /// - startSuspended: Whether the queue starts suspended. `false` by default. + convenience init(qualityOfService: QualityOfService = .default, + maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount, + underlyingQueue: DispatchQueue? = nil, + name: String? = nil, + startSuspended: Bool = false) { + self.init() + self.qualityOfService = qualityOfService + self.maxConcurrentOperationCount = maxConcurrentOperationCount + self.underlyingQueue = underlyingQueue + self.name = name + isSuspended = startSuspended + } +} diff --git a/Pods/Alamofire/Source/ParameterEncoder.swift b/Pods/Alamofire/Source/ParameterEncoder.swift new file mode 100644 index 0000000..8916978 --- /dev/null +++ b/Pods/Alamofire/Source/ParameterEncoder.swift @@ -0,0 +1,213 @@ +// +// ParameterEncoder.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that can encode any `Encodable` type into a `URLRequest`. +public protocol ParameterEncoder { + /// Encode the provided `Encodable` parameters into `request`. + /// + /// - Parameters: + /// - parameters: The `Encodable` parameter value. + /// - request: The `URLRequest` into which to encode the parameters. + /// + /// - Returns: A `URLRequest` with the result of the encoding. + /// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of + /// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`. + func encode(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest +} + +/// A `ParameterEncoder` that encodes types as JSON body data. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`. +open class JSONParameterEncoder: ParameterEncoder { + /// Returns an encoder with default parameters. + public static var `default`: JSONParameterEncoder { JSONParameterEncoder() } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`. + public static var prettyPrinted: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .prettyPrinted + + return JSONParameterEncoder(encoder: encoder) + } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`. + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public static var sortedKeys: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + + return JSONParameterEncoder(encoder: encoder) + } + + /// `JSONEncoder` used to encode parameters. + public let encoder: JSONEncoder + + /// Creates an instance with the provided `JSONEncoder`. + /// + /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default. + public init(encoder: JSONEncoder = JSONEncoder()) { + self.encoder = encoder + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters = parameters else { return request } + + var request = request + + do { + let data = try encoder.encode(parameters) + request.httpBody = data + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/json")) + } + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return request + } +} + +extension ParameterEncoder where Self == JSONParameterEncoder { + /// Provides a default `JSONParameterEncoder` instance. + public static var json: JSONParameterEncoder { JSONParameterEncoder() } + + /// Creates a `JSONParameterEncoder` using the provided `JSONEncoder`. + /// + /// - Parameter encoder: `JSONEncoder` used to encode parameters. `JSONEncoder()` by default. + /// - Returns: The `JSONParameterEncoder`. + public static func json(encoder: JSONEncoder = JSONEncoder()) -> JSONParameterEncoder { + JSONParameterEncoder(encoder: encoder) + } +} + +/// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending +/// on the `Destination` set. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer. +open class URLEncodedFormParameterEncoder: ParameterEncoder { + /// Defines where the URL-encoded string should be set for each `URLRequest`. + public enum Destination { + /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request. + /// Sets it to the `httpBody` for all other methods. + case methodDependent + /// Applies the encoded query string to any existing query string from the `URLRequest`. + case queryString + /// Applies the encoded query string to the `httpBody` of the `URLRequest`. + case httpBody + + /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`. + /// + /// - Parameter method: The `HTTPMethod`. + /// + /// - Returns: Whether the URL-encoded string should be applied to a `URL`. + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: return [.get, .head, .delete].contains(method) + case .queryString: return true + case .httpBody: return false + } + } + } + + /// Returns an encoder with default parameters. + public static var `default`: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } + + /// The `URLEncodedFormEncoder` to use. + public let encoder: URLEncodedFormEncoder + + /// The `Destination` for the URL-encoded string. + public let destination: Destination + + /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value. + /// + /// - Parameters: + /// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default. + /// - destination: The `Destination`. `.methodDependent` by default. + public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) { + self.encoder = encoder + self.destination = destination + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters = parameters else { return request } + + var request = request + + guard let url = request.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + guard let method = request.method else { + let rawValue = request.method?.rawValue ?? "nil" + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue))) + } + + if destination.encodesParametersInURL(for: method), + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { + let query: String = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands() + components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString + + guard let newURL = components.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + request.url = newURL + } else { + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) + } + + request.httpBody = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + } + + return request + } +} + +extension ParameterEncoder where Self == URLEncodedFormParameterEncoder { + /// Provides a default `URLEncodedFormParameterEncoder` instance. + public static var urlEncodedForm: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } + + /// Creates a `URLEncodedFormParameterEncoder` with the provided encoder and destination. + /// + /// - Parameters: + /// - encoder: `URLEncodedFormEncoder` used to encode the parameters. `URLEncodedFormEncoder()` by default. + /// - destination: `Destination` to which to encode the parameters. `.methodDependent` by default. + /// - Returns: The `URLEncodedFormParameterEncoder`. + public static func urlEncodedForm(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), + destination: URLEncodedFormParameterEncoder.Destination = .methodDependent) -> URLEncodedFormParameterEncoder { + URLEncodedFormParameterEncoder(encoder: encoder, destination: destination) + } +} diff --git a/Pods/Alamofire/Source/ParameterEncoding.swift b/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..ea61256 --- /dev/null +++ b/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,346 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// Creates a `URLRequest` by encoding parameters and applying them on the passed request. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. + /// - parameters: `Parameters` to encode onto the request. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during parameter encoding. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// There is no published specification for how to encode collection types. By default the convention of appending +/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for +/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the +/// square brackets appended to array keys. +/// +/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. +public struct URLEncoding: ParameterEncoding { + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + public enum Destination { + /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and + /// sets as the HTTP body for requests with any other HTTP method. + case methodDependent + /// Sets or appends encoded query string result to existing query string. + case queryString + /// Sets encoded query string result as the HTTP body of the URL request. + case httpBody + + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: return [.get, .head, .delete].contains(method) + case .queryString: return true + case .httpBody: return false + } + } + } + + /// Configures how `Array` parameters are encoded. + public enum ArrayEncoding { + /// An empty set of square brackets is appended to the key for every value. This is the default behavior. + case brackets + /// No brackets are appended. The key is encoded as is. + case noBrackets + /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. + case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custom((_ key: String, _ index: Int) -> String) + + func encode(key: String, atIndex index: Int) -> String { + switch self { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + case .indexInBrackets: + return "\(key)[\(index)]" + case let .custom(encoding): + return encoding(key, index) + } + } + } + + /// Configures how `Bool` parameters are encoded. + public enum BoolEncoding { + /// Encode `true` as `1` and `false` as `0`. This is the default behavior. + case numeric + /// Encode `true` and `false` as string literals. + case literal + + func encode(value: Bool) -> String { + switch self { + case .numeric: + return value ? "1" : "0" + case .literal: + return value ? "true" : "false" + } + } + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance with a `.methodDependent` destination. + public static var `default`: URLEncoding { URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + /// The encoding to use for `Array` parameters. + public let arrayEncoding: ArrayEncoding + + /// The encoding to use for `Bool` parameters. + public let boolEncoding: BoolEncoding + + // MARK: Initialization + + /// Creates an instance using the specified parameters. + /// + /// - Parameters: + /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by + /// default. + /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default. + public init(destination: Destination = .methodDependent, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric) { + self.destination = destination + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + } + + // MARK: Encoding + + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = urlRequest.method, destination.encodesParametersInURL(for: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) + } + + urlRequest.httpBody = Data(query(parameters).utf8) + } + + return urlRequest + } + + /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively. + /// + /// - Parameters: + /// - key: Key of the query component. + /// - value: Value of the query component. + /// + /// - Returns: The percent-escaped, URL encoded query string components. + public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + switch value { + case let dictionary as [String: Any]: + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + case let array as [Any]: + for (index, value) in array.enumerated() { + components += queryComponents(fromKey: arrayEncoding.encode(key: key, atIndex: index), value: value) + } + case let number as NSNumber: + if number.isBool { + components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue)))) + } else { + components.append((escape(key), escape("\(number)"))) + } + case let bool as Bool: + components.append((escape(key), escape(boolEncoding.encode(value: bool)))) + default: + components.append((escape(key), escape("\(value)"))) + } + return components + } + + /// Creates a percent-escaped string following RFC 3986 for a query string key or value. + /// + /// - Parameter string: `String` to be percent-escaped. + /// + /// - Returns: The percent-escaped `String`. + public func escape(_ string: String) -> String { + string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string + } + + private func query(_ parameters: [String: Any]) -> String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + return components.map { "\($0)=\($1)" }.joined(separator: "&") + } +} + +// MARK: - + +/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the +/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +public struct JSONEncoding: ParameterEncoding { + public enum Error: Swift.Error { + case invalidJSONObject + } + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates an instance using the specified `WritingOptions`. + /// + /// - Parameter options: `JSONSerialization.WritingOptions` to use. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + guard JSONSerialization.isValidJSONObject(parameters) else { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) + } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/json")) + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Encodes any JSON compatible object into a `URLRequest`. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value into which the object will be encoded. + /// - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during encoding. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + guard JSONSerialization.isValidJSONObject(jsonObject) else { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) + } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/json")) + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +extension JSONEncoding.Error { + public var localizedDescription: String { + """ + Invalid JSON object provided for parameter or object encoding. \ + This is most likely due to a value which can't be represented in Objective-C. + """ + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { + // Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of + // swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22). + String(cString: objCType) == "c" + } +} diff --git a/Pods/Alamofire/Source/Protected.swift b/Pods/Alamofire/Source/Protected.swift new file mode 100644 index 0000000..9449412 --- /dev/null +++ b/Pods/Alamofire/Source/Protected.swift @@ -0,0 +1,161 @@ +// +// Protected.swift +// +// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +private protocol Lock { + func lock() + func unlock() +} + +extension Lock { + /// Executes a closure returning a value while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + /// + /// - Returns: The value the closure generated. + func around(_ closure: () throws -> T) rethrows -> T { + lock(); defer { unlock() } + return try closure() + } + + /// Execute a closure while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + func around(_ closure: () throws -> Void) rethrows { + lock(); defer { unlock() } + try closure() + } +} + +#if os(Linux) || os(Windows) || os(Android) + +extension NSLock: Lock {} + +#endif + +#if canImport(Darwin) +/// An `os_unfair_lock` wrapper. +final class UnfairLock: Lock { + private let unfairLock: os_unfair_lock_t + + init() { + unfairLock = .allocate(capacity: 1) + unfairLock.initialize(to: os_unfair_lock()) + } + + deinit { + unfairLock.deinitialize(count: 1) + unfairLock.deallocate() + } + + fileprivate func lock() { + os_unfair_lock_lock(unfairLock) + } + + fileprivate func unlock() { + os_unfair_lock_unlock(unfairLock) + } +} +#endif + +/// A thread-safe wrapper around a value. +@propertyWrapper +@dynamicMemberLookup +final class Protected { + #if canImport(Darwin) + private let lock = UnfairLock() + #elseif os(Linux) || os(Windows) || os(Android) + private let lock = NSLock() + #endif + private var value: T + + init(_ value: T) { + self.value = value + } + + /// The contained value. Unsafe for anything more than direct read or write. + var wrappedValue: T { + get { lock.around { value } } + set { lock.around { value = newValue } } + } + + var projectedValue: Protected { self } + + init(wrappedValue: T) { + value = wrappedValue + } + + /// Synchronously read or transform the contained value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The return value of the closure passed. + func read(_ closure: (T) throws -> U) rethrows -> U { + try lock.around { try closure(self.value) } + } + + /// Synchronously modify the protected value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The modified value. + @discardableResult + func write(_ closure: (inout T) throws -> U) rethrows -> U { + try lock.around { try closure(&self.value) } + } + + subscript(dynamicMember keyPath: WritableKeyPath) -> Property { + get { lock.around { value[keyPath: keyPath] } } + set { lock.around { value[keyPath: keyPath] = newValue } } + } + + subscript(dynamicMember keyPath: KeyPath) -> Property { + lock.around { value[keyPath: keyPath] } + } +} + +extension Protected where T == Request.MutableState { + /// Attempts to transition to the passed `State`. + /// + /// - Parameter state: The `State` to attempt transition to. + /// + /// - Returns: Whether the transition occurred. + func attemptToTransitionTo(_ state: Request.State) -> Bool { + lock.around { + guard value.state.canTransitionTo(state) else { return false } + + value.state = state + + return true + } + } + + /// Perform a closure while locked with the provided `Request.State`. + /// + /// - Parameter perform: The closure to perform while locked. + func withState(perform: (Request.State) -> Void) { + lock.around { perform(value.state) } + } +} diff --git a/Pods/Alamofire/Source/RedirectHandler.swift b/Pods/Alamofire/Source/RedirectHandler.swift new file mode 100644 index 0000000..cf88abf --- /dev/null +++ b/Pods/Alamofire/Source/RedirectHandler.swift @@ -0,0 +1,111 @@ +// +// RedirectHandler.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that handles how an HTTP redirect response from a remote server should be redirected to the new request. +public protocol RedirectHandler { + /// Determines how the HTTP redirect response should be redirected to the new request. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The new request specified by the redirect (this is the most common use case). + /// 2. A modified version of the new request (you may want to route it somewhere else). + /// 3. A `nil` value to deny the redirect request and return the body of the redirect response. + /// + /// - Parameters: + /// - task: The `URLSessionTask` whose request resulted in a redirect. + /// - request: The `URLRequest` to the new location specified by the redirect response. + /// - response: The `HTTPURLResponse` containing the server's response to the original request. + /// - completion: The closure to execute containing the new `URLRequest`, a modified `URLRequest`, or `nil`. + func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) +} + +// MARK: - + +/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect. +public struct Redirector { + /// Defines the behavior of the `Redirector` type. + public enum Behavior { + /// Follow the redirect as defined in the response. + case follow + /// Do not follow the redirect defined in the response. + case doNotFollow + /// Modify the redirect request defined in the response. + case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) + } + + /// Returns a `Redirector` with a `.follow` `Behavior`. + public static let follow = Redirector(behavior: .follow) + /// Returns a `Redirector` with a `.doNotFollow` `Behavior`. + public static let doNotFollow = Redirector(behavior: .doNotFollow) + + /// The `Behavior` of the `Redirector`. + public let behavior: Behavior + + /// Creates a `Redirector` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +// MARK: - + +extension Redirector: RedirectHandler { + public func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) { + switch behavior { + case .follow: + completion(request) + case .doNotFollow: + completion(nil) + case let .modify(closure): + let request = closure(task, request, response) + completion(request) + } + } +} + +extension RedirectHandler where Self == Redirector { + /// Provides a `Redirector` which follows redirects. Equivalent to `Redirector.follow`. + public static var follow: Redirector { .follow } + + /// Provides a `Redirector` which does not follow redirects. Equivalent to `Redirector.doNotFollow`. + public static var doNotFollow: Redirector { .doNotFollow } + + /// Creates a `Redirector` which modifies the redirected `URLRequest` using the provided closure. + /// + /// - Parameter closure: Closure used to modify the redirect. + /// - Returns: The `Redirector`. + public static func modify(using closure: @escaping (URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) -> Redirector { + Redirector(behavior: .modify(closure)) + } +} diff --git a/Pods/Alamofire/Source/Request.swift b/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000..fbae9db --- /dev/null +++ b/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,2070 @@ +// +// Request.swift +// +// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback +/// handling. +public class Request { + /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or + /// `cancel()` on the `Request`. + public enum State { + /// Initial state of the `Request`. + case initialized + /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on + /// them in this state. + case resumed + /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on + /// them in this state. + case suspended + /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on + /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition + /// to any other state. + case cancelled + /// `State` set when all response serialization completion closures have been cleared on the `Request` and + /// enqueued on their respective queues. + case finished + + /// Determines whether `self` can be transitioned to the provided `State`. + func canTransitionTo(_ state: State) -> Bool { + switch (self, state) { + case (.initialized, _): + return true + case (_, .initialized), (.cancelled, _), (.finished, _): + return false + case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed): + return true + case (.suspended, .suspended), (.resumed, .resumed): + return false + case (_, .finished): + return true + } + } + } + + // MARK: - Initial State + + /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances. + public let id: UUID + /// The serial queue for all internal async actions. + public let underlyingQueue: DispatchQueue + /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`. + public let serializationQueue: DispatchQueue + /// `EventMonitor` used for event callbacks. + public let eventMonitor: EventMonitor? + /// The `Request`'s interceptor. + public let interceptor: RequestInterceptor? + /// The `Request`'s delegate. + public private(set) weak var delegate: RequestDelegate? + + // MARK: - Mutable State + + /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`. + struct MutableState { + /// State of the `Request`. + var state: State = .initialized + /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks. + var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks. + var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `RedirectHandler` provided for to handle request redirection. + var redirectHandler: RedirectHandler? + /// `CachedResponseHandler` provided to handle response caching. + var cachedResponseHandler: CachedResponseHandler? + /// Queue and closure called when the `Request` is able to create a cURL description of itself. + var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)? + /// Queue and closure called when the `Request` creates a `URLRequest`. + var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)? + /// Queue and closure called when the `Request` creates a `URLSessionTask`. + var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)? + /// Response serialization closures that handle response parsing. + var responseSerializers: [() -> Void] = [] + /// Response serialization completion closures executed once all response serializers are complete. + var responseSerializerCompletions: [() -> Void] = [] + /// Whether response serializer processing is finished. + var responseSerializerProcessingFinished = false + /// `URLCredential` used for authentication challenges. + var credential: URLCredential? + /// All `URLRequest`s created by Alamofire on behalf of the `Request`. + var requests: [URLRequest] = [] + /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`. + var tasks: [URLSessionTask] = [] + /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond + /// exactly the the `tasks` created. + var metrics: [URLSessionTaskMetrics] = [] + /// Number of times any retriers provided retried the `Request`. + var retryCount = 0 + /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`. + var error: AFError? + /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a + /// representation in the state machine in the future. + var isFinishing = false + /// Actions to run when requests are finished. Use for concurrency support. + var finishHandlers: [() -> Void] = [] + } + + /// Protected `MutableState` value that provides thread-safe access to state values. + @Protected + fileprivate var mutableState = MutableState() + + /// `State` of the `Request`. + public var state: State { $mutableState.state } + /// Returns whether `state` is `.initialized`. + public var isInitialized: Bool { state == .initialized } + /// Returns whether `state is `.resumed`. + public var isResumed: Bool { state == .resumed } + /// Returns whether `state` is `.suspended`. + public var isSuspended: Bool { state == .suspended } + /// Returns whether `state` is `.cancelled`. + public var isCancelled: Bool { state == .cancelled } + /// Returns whether `state` is `.finished`. + public var isFinished: Bool { state == .finished } + + // MARK: Progress + + /// Closure type executed when monitoring the upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried. + public let uploadProgress = Progress(totalUnitCount: 0) + /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried. + public let downloadProgress = Progress(totalUnitCount: 0) + /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`. + private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { $mutableState.uploadProgressHandler } + set { $mutableState.uploadProgressHandler = newValue } + } + + /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. + fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { $mutableState.downloadProgressHandler } + set { $mutableState.downloadProgressHandler = newValue } + } + + // MARK: Redirect Handling + + /// `RedirectHandler` set on the instance. + public private(set) var redirectHandler: RedirectHandler? { + get { $mutableState.redirectHandler } + set { $mutableState.redirectHandler = newValue } + } + + // MARK: Cached Response Handling + + /// `CachedResponseHandler` set on the instance. + public private(set) var cachedResponseHandler: CachedResponseHandler? { + get { $mutableState.cachedResponseHandler } + set { $mutableState.cachedResponseHandler = newValue } + } + + // MARK: URLCredential + + /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. + public private(set) var credential: URLCredential? { + get { $mutableState.credential } + set { $mutableState.credential = newValue } + } + + // MARK: Validators + + /// `Validator` callback closures that store the validation calls enqueued. + @Protected + fileprivate var validators: [() -> Void] = [] + + // MARK: URLRequests + + /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests. + public var requests: [URLRequest] { $mutableState.requests } + /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. + public var firstRequest: URLRequest? { requests.first } + /// Last `URLRequest` created on behalf of the `Request`. + public var lastRequest: URLRequest? { requests.last } + /// Current `URLRequest` created on behalf of the `Request`. + public var request: URLRequest? { lastRequest } + + /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from + /// `requests` due to `URLSession` manipulation. + public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap(\.currentRequest) } } + + // MARK: HTTPURLResponse + + /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the + /// last `URLSessionTask`. + public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse } + + // MARK: Tasks + + /// All `URLSessionTask`s created on behalf of the `Request`. + public var tasks: [URLSessionTask] { $mutableState.tasks } + /// First `URLSessionTask` created on behalf of the `Request`. + public var firstTask: URLSessionTask? { tasks.first } + /// Last `URLSessionTask` created on behalf of the `Request`. + public var lastTask: URLSessionTask? { tasks.last } + /// Current `URLSessionTask` created on behalf of the `Request`. + public var task: URLSessionTask? { lastTask } + + // MARK: Metrics + + /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. + public var allMetrics: [URLSessionTaskMetrics] { $mutableState.metrics } + /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first } + /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last } + /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var metrics: URLSessionTaskMetrics? { lastMetrics } + + // MARK: Retry Count + + /// Number of times the `Request` has been retried. + public var retryCount: Int { $mutableState.retryCount } + + // MARK: Error + + /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. + public fileprivate(set) var error: AFError? { + get { $mutableState.error } + set { $mutableState.error = newValue } + } + + /// Default initializer for the `Request` superclass. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.id = id + self.underlyingQueue = underlyingQueue + self.serializationQueue = serializationQueue + self.eventMonitor = eventMonitor + self.interceptor = interceptor + self.delegate = delegate + } + + // MARK: - Internal Event API + + // All API must be called from underlyingQueue. + + /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, + /// the `URLRequest` will be adapted before being issued. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateInitialURLRequest(_ request: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { $0.requests.append(request) } + + eventMonitor?.request(self, didCreateInitialURLRequest: request) + } + + /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. + /// + /// - Note: Triggers retry. + /// + /// - Parameter error: `AFError` thrown from the failed creation. + func didFailToCreateURLRequest(with error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`. + /// + /// - Parameters: + /// - initialRequest: The `URLRequest` that was adapted. + /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`. + func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { $0.requests.append(adaptedRequest) } + + eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) + } + + /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. + /// + /// - Note: Triggers retry. + /// + /// - Parameters: + /// - request: The `URLRequest` the adapter was called with. + /// - error: The `AFError` returned by the `RequestAdapter`. + func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Final `URLRequest` has been created for the instance. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateURLRequest(_ request: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.read { state in + state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) } + } + + eventMonitor?.request(self, didCreateURLRequest: request) + + callCURLHandlerIfNecessary() + } + + /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. + private func callCURLHandlerIfNecessary() { + $mutableState.write { mutableState in + guard let cURLHandler = mutableState.cURLHandler else { return } + + cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) } + + mutableState.cURLHandler = nil + } + } + + /// Called when a `URLSessionTask` is created on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` created. + func didCreateTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { state in + state.tasks.append(task) + + guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return } + + urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) } + } + + eventMonitor?.request(self, didCreateTask: task) + } + + /// Called when resumption is completed. + func didResume() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.requestDidResume(self) + } + + /// Called when a `URLSessionTask` is resumed on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` resumed. + func didResumeTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didResumeTask: task) + } + + /// Called when suspension is completed. + func didSuspend() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.requestDidSuspend(self) + } + + /// Called when a `URLSessionTask` is suspended on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` suspended. + func didSuspendTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didSuspendTask: task) + } + + /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. + func didCancel() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { mutableState in + mutableState.error = mutableState.error ?? AFError.explicitlyCancelled + } + + eventMonitor?.requestDidCancel(self) + } + + /// Called when a `URLSessionTask` is cancelled on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` cancelled. + func didCancelTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didCancelTask: task) + } + + /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance. + /// + /// - Parameter metrics: The `URLSessionTaskMetrics` gathered. + func didGatherMetrics(_ metrics: URLSessionTaskMetrics) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { $0.metrics.append(metrics) } + + eventMonitor?.request(self, didGatherMetrics: metrics) + } + + /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which failed. + /// - error: The early failure `AFError`. + func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + // Task will still complete, so didCompleteTask(_:with:) will handle retry. + eventMonitor?.request(self, didFailTask: task, earlyWithError: error) + } + + /// Called when a `URLSessionTask` completes. All tasks will eventually call this method. + /// + /// - Note: Response validation is synchronously triggered in this step. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which completed. + /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this + /// value is ignored. + func didCompleteTask(_ task: URLSessionTask, with error: AFError?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = self.error ?? error + + validators.forEach { $0() } + + eventMonitor?.request(self, didCompleteTask: task, with: error) + + retryOrFinish(error: self.error) + } + + /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. + func prepareForRetry() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + $mutableState.write { $0.retryCount += 1 } + + reset() + + eventMonitor?.requestIsRetrying(self) + } + + /// Called to determine whether retry will be triggered for the particular error, or whether the instance should + /// call `finish()`. + /// + /// - Parameter error: The possible `AFError` which may trigger retry. + func retryOrFinish(error: AFError?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + guard !isCancelled, let error = error, let delegate = delegate else { finish(); return } + + delegate.retryResult(for: self, dueTo: error) { retryResult in + switch retryResult { + case .doNotRetry: + self.finish() + case let .doNotRetryWithError(retryError): + self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + + /// Finishes this `Request` and starts the response serializers. + /// + /// - Parameter error: The possible `Error` with which the instance will finish. + func finish(error: AFError? = nil) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + guard !$mutableState.isFinishing else { return } + + $mutableState.isFinishing = true + + if let error = error { self.error = error } + + // Start response handlers + processNextResponseSerializer() + + eventMonitor?.requestDidFinish(self) + } + + /// Appends the response serialization closure to the instance. + /// + /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. + /// + /// - Parameter closure: The closure containing the response serialization call. + func appendResponseSerializer(_ closure: @escaping () -> Void) { + $mutableState.write { mutableState in + mutableState.responseSerializers.append(closure) + + if mutableState.state == .finished { + mutableState.state = .resumed + } + + if mutableState.responseSerializerProcessingFinished { + underlyingQueue.async { self.processNextResponseSerializer() } + } + + if mutableState.state.canTransitionTo(.resumed) { + underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } } + } + } + } + + /// Returns the next response serializer closure to execute if there's one left. + /// + /// - Returns: The next response serialization closure, if there is one. + func nextResponseSerializer() -> (() -> Void)? { + var responseSerializer: (() -> Void)? + + $mutableState.write { mutableState in + let responseSerializerIndex = mutableState.responseSerializerCompletions.count + + if responseSerializerIndex < mutableState.responseSerializers.count { + responseSerializer = mutableState.responseSerializers[responseSerializerIndex] + } + } + + return responseSerializer + } + + /// Processes the next response serializer and calls all completions if response serialization is complete. + func processNextResponseSerializer() { + guard let responseSerializer = nextResponseSerializer() else { + // Execute all response serializer completions and clear them + var completions: [() -> Void] = [] + + $mutableState.write { mutableState in + completions = mutableState.responseSerializerCompletions + + // Clear out all response serializers and response serializer completions in mutable state since the + // request is complete. It's important to do this prior to calling the completion closures in case + // the completions call back into the request triggering a re-processing of the response serializers. + // An example of how this can happen is by calling cancel inside a response completion closure. + mutableState.responseSerializers.removeAll() + mutableState.responseSerializerCompletions.removeAll() + + if mutableState.state.canTransitionTo(.finished) { + mutableState.state = .finished + } + + mutableState.responseSerializerProcessingFinished = true + mutableState.isFinishing = false + } + + completions.forEach { $0() } + + // Cleanup the request + cleanup() + + return + } + + serializationQueue.async { responseSerializer() } + } + + /// Notifies the `Request` that the response serializer is complete. + /// + /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers + /// are complete. + func responseSerializerDidComplete(completion: @escaping () -> Void) { + $mutableState.write { $0.responseSerializerCompletions.append(completion) } + processNextResponseSerializer() + } + + /// Resets all task and response serializer related state for retry. + func reset() { + error = nil + + uploadProgress.totalUnitCount = 0 + uploadProgress.completedUnitCount = 0 + downloadProgress.totalUnitCount = 0 + downloadProgress.completedUnitCount = 0 + + $mutableState.write { state in + state.isFinishing = false + state.responseSerializerCompletions = [] + } + } + + /// Called when updating the upload progress. + /// + /// - Parameters: + /// - totalBytesSent: Total bytes sent so far. + /// - totalBytesExpectedToSend: Total bytes expected to send. + func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } + } + + /// Perform a closure on the current `state` while locked. + /// + /// - Parameter perform: The closure to perform. + func withState(perform: (State) -> Void) { + $mutableState.withState(perform: perform) + } + + // MARK: Task Creation + + /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override. + /// + /// - Parameters: + /// - request: `URLRequest` to use to create the `URLSessionTask`. + /// - session: `URLSession` which creates the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + fatalError("Subclasses must override.") + } + + // MARK: - Public API + + // These APIs are callable from any queue. + + // MARK: State + + /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. + /// + /// - Returns: The instance. + @discardableResult + public func cancel() -> Self { + $mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + underlyingQueue.async { self.didCancelTask(task) } + } + + return self + } + + /// Suspends the instance. + /// + /// - Returns: The instance. + @discardableResult + public func suspend() -> Self { + $mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.suspended) else { return } + + mutableState.state = .suspended + + underlyingQueue.async { self.didSuspend() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.suspend() + underlyingQueue.async { self.didSuspendTask(task) } + } + + return self + } + + /// Resumes the instance. + /// + /// - Returns: The instance. + @discardableResult + public func resume() -> Self { + $mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.resumed) else { return } + + mutableState.state = .resumed + + underlyingQueue.async { self.didResume() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.resume() + underlyingQueue.async { self.didResumeTask(task) } + } + + return self + } + + // MARK: - Closure API + + /// Associates a credential using the provided values with the instance. + /// + /// - Parameters: + /// - username: The username. + /// - password: The password. + /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { + let credential = URLCredential(user: username, password: password, persistence: persistence) + + return authenticate(with: credential) + } + + /// Associates the provided credential with the instance. + /// + /// - Parameter credential: The `URLCredential`. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(with credential: URLCredential) -> Self { + $mutableState.credential = credential + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is read from the server. + /// + /// - Returns: The instance. + @discardableResult + public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + $mutableState.downloadProgressHandler = (handler: closure, queue: queue) + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is sent to the server. + /// + /// - Returns: The instance. + @discardableResult + public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + $mutableState.uploadProgressHandler = (handler: closure, queue: queue) + + return self + } + + // MARK: Redirects + + /// Sets the redirect handler for the instance which will be used if a redirect response is encountered. + /// + /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `RedirectHandler`. + /// + /// - Returns: The instance. + @discardableResult + public func redirect(using handler: RedirectHandler) -> Self { + $mutableState.write { mutableState in + precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") + mutableState.redirectHandler = handler + } + + return self + } + + // MARK: Cached Responses + + /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response. + /// + /// - Note: Attempting to set the cache handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `CachedResponseHandler`. + /// + /// - Returns: The instance. + @discardableResult + public func cacheResponse(using handler: CachedResponseHandler) -> Self { + $mutableState.write { mutableState in + precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") + mutableState.cachedResponseHandler = handler + } + + return self + } + + // MARK: - Lifetime APIs + + /// Sets a handler to be called when the cURL description of the request is available. + /// + /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. + /// - handler: Closure to be called when the cURL description is available. + /// + /// - Returns: The instance. + @discardableResult + public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self { + $mutableState.write { mutableState in + if mutableState.requests.last != nil { + queue.async { handler(self.cURLDescription()) } + } else { + mutableState.cURLHandler = (queue, handler) + } + } + + return self + } + + /// Sets a handler to be called when the cURL description of the request is available. + /// + /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. + /// + /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's + /// `underlyingQueue` by default. + /// + /// - Returns: The instance. + @discardableResult + public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { + cURLDescription(on: underlyingQueue, calling: handler) + + return self + } + + /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance. + /// + /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. + /// - handler: Closure to be called when a `URLRequest` is available. + /// + /// - Returns: The instance. + @discardableResult + public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self { + $mutableState.write { state in + if let request = state.requests.last { + queue.async { handler(request) } + } + + state.urlRequestHandler = (queue, handler) + } + + return self + } + + /// Sets a closure to be called whenever the instance creates a `URLSessionTask`. + /// + /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It + /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features. + /// Additionally, this closure may be called multiple times if the instance is retried. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. + /// - handler: Closure to be called when the `URLSessionTask` is available. + /// + /// - Returns: The instance. + @discardableResult + public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self { + $mutableState.write { state in + if let task = state.tasks.last { + queue.async { handler(task) } + } + + state.urlSessionTaskHandler = (queue, handler) + } + + return self + } + + // MARK: Cleanup + + /// Adds a `finishHandler` closure to be called when the request completes. + /// + /// - Parameter closure: Closure to be called when the request finishes. + func onFinish(perform finishHandler: @escaping () -> Void) { + guard !isFinished else { finishHandler(); return } + + $mutableState.write { state in + state.finishHandlers.append(finishHandler) + } + } + + /// Final cleanup step executed when the instance finishes response serialization. + func cleanup() { + let handlers = $mutableState.finishHandlers + handlers.forEach { $0() } + $mutableState.write { state in + state.finishHandlers.removeAll() + } + + delegate?.cleanup(after: self) + } +} + +extension Request { + /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`. + public enum ResponseDisposition { + /// Allow the request to continue normally. + case allow + /// Cancel the request, similar to calling `cancel()`. + case cancel + + var sessionDisposition: URLSession.ResponseDisposition { + switch self { + case .allow: return .allow + case .cancel: return .cancel + } + } + } +} + +// MARK: - Protocol Conformances + +extension Request: Equatable { + public static func ==(lhs: Request, rhs: Request) -> Bool { + lhs.id == rhs.id + } +} + +extension Request: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(id) + } +} + +extension Request: CustomStringConvertible { + /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been + /// created, as well as the response status code, if a response has been received. + public var description: String { + guard let request = performedRequests.last ?? lastRequest, + let url = request.url, + let method = request.httpMethod else { return "No request created yet." } + + let requestDescription = "\(method) \(url.absoluteString)" + + return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription + } +} + +extension Request { + /// cURL representation of the instance. + /// + /// - Returns: The cURL equivalent of the instance. + public func cURLDescription() -> String { + guard + let request = lastRequest, + let url = request.url, + let host = url.host, + let method = request.httpMethod else { return "$ curl command could not be created" } + + var components = ["$ curl -v"] + + components.append("-X \(method)") + + if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace(host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic) + + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { + for credential in credentials { + guard let user = credential.user, let password = credential.password else { continue } + components.append("-u \(user):\(password)") + } + } else { + if let credential = credential, let user = credential.user, let password = credential.password { + components.append("-u \(user):\(password)") + } + } + } + + if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { + if + let cookieStorage = configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { + let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";") + + components.append("-b \"\(allCookies)\"") + } + } + + var headers = HTTPHeaders() + + if let sessionHeaders = delegate?.sessionConfiguration.headers { + for header in sessionHeaders where header.name != "Cookie" { + headers[header.name] = header.value + } + } + + for header in request.headers where header.name != "Cookie" { + headers[header.name] = header.value + } + + for header in headers { + let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"") + components.append("-H \"\(header.name): \(escapedValue)\"") + } + + if let httpBodyData = request.httpBody { + let httpBody = String(decoding: httpBodyData, as: UTF8.self) + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(url.absoluteString)\"") + + return components.joined(separator: " \\\n\t") + } +} + +/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`. +public protocol RequestDelegate: AnyObject { + /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s. + var sessionConfiguration: URLSessionConfiguration { get } + + /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler. + var startImmediately: Bool { get } + + /// Notifies the delegate the `Request` has reached a point where it needs cleanup. + /// + /// - Parameter request: The `Request` to cleanup after. + func cleanup(after request: Request) + + /// Asynchronously ask the delegate whether a `Request` will be retried. + /// + /// - Parameters: + /// - request: `Request` which failed. + /// - error: `Error` which produced the failure. + /// - completion: Closure taking the `RetryResult` for evaluation. + func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) + + /// Asynchronously retry the `Request`. + /// + /// - Parameters: + /// - request: `Request` which will be retried. + /// - timeDelay: `TimeInterval` after which the retry will be triggered. + func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) +} + +// MARK: - Subclasses + +// MARK: - DataRequest + +/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`. +public class DataRequest: Request { + /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. + public let convertible: URLRequestConvertible + /// `Data` read from the server so far. + public var data: Data? { $dataMutableState.data } + + private struct DataMutableState { + var data: Data? + var httpResponseHandler: (queue: DispatchQueue, + handler: (_ response: HTTPURLResponse, + _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)? + } + + @Protected + private var dataMutableState = DataMutableState() + + /// Creates a `DataRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: URLRequestConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.convertible = convertible + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + $dataMutableState.write { mutableState in + mutableState.data = nil + } + } + + /// Called when `Data` is received by this instance. + /// + /// - Note: Also calls `updateDownloadProgress`. + /// + /// - Parameter data: The `Data` received. + func didReceive(data: Data) { + $dataMutableState.write { mutableState in + if mutableState.data == nil { + mutableState.data = data + } else { + mutableState.data?.append(data) + } + } + + updateDownloadProgress() + } + + func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + $dataMutableState.read { dataMutableState in + guard let httpResponseHandler = dataMutableState.httpResponseHandler else { + underlyingQueue.async { completionHandler(.allow) } + return + } + + httpResponseHandler.queue.async { + httpResponseHandler.handler(response) { disposition in + if disposition == .cancel { + self.$mutableState.write { mutableState in + mutableState.state = .cancelled + mutableState.error = mutableState.error ?? AFError.explicitlyCancelled + } + } + + self.underlyingQueue.async { + completionHandler(disposition.sessionDisposition) + } + } + } + } + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + /// Called to update the `downloadProgress` of the instance. + func updateDownloadProgress() { + let totalBytesReceived = Int64(data?.count ?? 0) + let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + downloadProgress.totalUnitCount = totalBytesExpected + downloadProgress.completedUnitCount = totalBytesReceived + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure used to validate the response. + /// + /// - Returns: The instance. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard error == nil, let response = response else { return } + + let result = validation(request, response, data) + + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + data: data, + withResult: result) + } + + $validators.write { $0.append(validator) } + + return self + } + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion + /// handler to return a `ResponseDisposition` value. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided + /// MUST be called, otherwise the request will never complete. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse( + on queue: DispatchQueue = .main, + perform handler: @escaping (_ response: HTTPURLResponse, + _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void + ) -> Self { + $dataMutableState.write { mutableState in + mutableState.httpResponseHandler = (queue, handler) + } + + return self + } + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(on queue: DispatchQueue = .main, + perform handler: @escaping (HTTPURLResponse) -> Void) -> Self { + onHTTPResponse(on: queue) { response, completionHandler in + handler(response) + completionHandler(.allow) + } + + return self + } +} + +// MARK: - DataStreamRequest + +/// `Request` subclass which streams HTTP response `Data` through a `Handler` closure. +public final class DataStreamRequest: Request { + /// Closure type handling `DataStreamRequest.Stream` values. + public typealias Handler = (Stream) throws -> Void + + /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used + /// to stop the stream at any time. + public struct Stream { + /// Latest `Event` from the stream. + public let event: Event + /// Token used to cancel the stream. + public let token: CancellationToken + + /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. + public func cancel() { + token.cancel() + } + } + + /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed + /// `Data` or the completion of the stream. + public enum Event { + /// Output produced every time the instance receives additional `Data`. The associated value contains the + /// `Result` of processing the incoming `Data`. + case stream(Result) + /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error. + /// Associated `Completion` value contains the final state. + case complete(Completion) + } + + /// Value containing the state of a `DataStreamRequest` when the stream was completed. + public struct Completion { + /// Last `URLRequest` issued by the instance. + public let request: URLRequest? + /// Last `HTTPURLResponse` received by the instance. + public let response: HTTPURLResponse? + /// Last `URLSessionTaskMetrics` produced for the instance. + public let metrics: URLSessionTaskMetrics? + /// `AFError` produced for the instance, if any. + public let error: AFError? + } + + /// Type used to cancel an ongoing stream. + public struct CancellationToken { + weak var request: DataStreamRequest? + + init(_ request: DataStreamRequest) { + self.request = request + } + + /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. + public func cancel() { + request?.cancel() + } + } + + /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. + public let convertible: URLRequestConvertible + /// Whether or not the instance will be cancelled if stream parsing encounters an error. + public let automaticallyCancelOnStreamError: Bool + + /// Internal mutable state specific to this type. + struct StreamMutableState { + /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called. + var outputStream: OutputStream? + /// Stream closures called as `Data` is received. + var streams: [(_ data: Data) -> Void] = [] + /// Number of currently executing streams. Used to ensure completions are only fired after all streams are + /// enqueued. + var numberOfExecutingStreams = 0 + /// Completion calls enqueued while streams are still executing. + var enqueuedCompletionEvents: [() -> Void] = [] + /// Handler for any `HTTPURLResponse`s received. + var httpResponseHandler: (queue: DispatchQueue, + handler: (_ response: HTTPURLResponse, + _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)? + } + + @Protected + var streamMutableState = StreamMutableState() + + /// Creates a `DataStreamRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` + /// by default. + /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this + /// instance. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error` + /// is thrown while serializing stream `Data`. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default + /// targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by + /// the `Request`. + init(id: UUID = UUID(), + convertible: URLRequestConvertible, + automaticallyCancelOnStreamError: Bool, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.convertible = convertible + self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + override func finish(error: AFError? = nil) { + $streamMutableState.write { state in + state.outputStream?.close() + } + + super.finish(error: error) + } + + func didReceive(data: Data) { + $streamMutableState.write { state in + #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. + if let stream = state.outputStream { + underlyingQueue.async { + var bytes = Array(data) + stream.write(&bytes, maxLength: bytes.count) + } + } + #endif + state.numberOfExecutingStreams += state.streams.count + let localState = state + underlyingQueue.async { localState.streams.forEach { $0(data) } } + } + } + + func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + $streamMutableState.read { dataMutableState in + guard let httpResponseHandler = dataMutableState.httpResponseHandler else { + underlyingQueue.async { completionHandler(.allow) } + return + } + + httpResponseHandler.queue.async { + httpResponseHandler.handler(response) { disposition in + if disposition == .cancel { + self.$mutableState.write { mutableState in + mutableState.state = .cancelled + mutableState.error = mutableState.error ?? AFError.explicitlyCancelled + } + } + + self.underlyingQueue.async { + completionHandler(disposition.sessionDisposition) + } + } + } + } + } + + /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure. + /// + /// - Parameter validation: `Validation` closure used to validate the request and response. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard error == nil, let response = response else { return } + + let result = validation(request, response) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + withResult: result) + } + + $validators.write { $0.append(validator) } + + return self + } + + #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. + /// Produces an `InputStream` that receives the `Data` received by the instance. + /// + /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`. + /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or + /// not the creating session has `startRequestsImmediately` set to `true`. + /// + /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`. + /// + /// - Returns: The `InputStream` bound to the internal `OutboundStream`. + public func asInputStream(bufferSize: Int = 1024) -> InputStream? { + defer { resume() } + + var inputStream: InputStream? + $streamMutableState.write { state in + Foundation.Stream.getBoundStreams(withBufferSize: bufferSize, + inputStream: &inputStream, + outputStream: &state.outputStream) + state.outputStream?.open() + } + + return inputStream + } + #endif + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion + /// handler to return a `ResponseDisposition` value. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided + /// MUST be called, otherwise the request will never complete. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse( + on queue: DispatchQueue = .main, + perform handler: @escaping (_ response: HTTPURLResponse, + _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void + ) -> Self { + $streamMutableState.write { mutableState in + mutableState.httpResponseHandler = (queue, handler) + } + + return self + } + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(on queue: DispatchQueue = .main, + perform handler: @escaping (HTTPURLResponse) -> Void) -> Self { + onHTTPResponse(on: queue) { response, completionHandler in + handler(response) + completionHandler(.allow) + } + + return self + } + + func capturingError(from closure: () throws -> Void) { + do { + try closure() + } catch { + self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + cancel() + } + } + + func appendStreamCompletion(on queue: DispatchQueue, + stream: @escaping Handler) { + appendResponseSerializer { + self.underlyingQueue.async { + self.responseSerializerDidComplete { + self.$streamMutableState.write { state in + guard state.numberOfExecutingStreams == 0 else { + state.enqueuedCompletionEvents.append { + self.enqueueCompletion(on: queue, stream: stream) + } + + return + } + + self.enqueueCompletion(on: queue, stream: stream) + } + } + } + } + } + + func enqueueCompletion(on queue: DispatchQueue, + stream: @escaping Handler) { + queue.async { + do { + let completion = Completion(request: self.request, + response: self.response, + metrics: self.metrics, + error: self.error) + try stream(.init(event: .complete(completion), token: .init(self))) + } catch { + // Ignore error, as errors on Completion can't be handled anyway. + } + } + } +} + +extension DataStreamRequest.Stream { + /// Incoming `Result` values from `Event.stream`. + public var result: Result? { + guard case let .stream(result) = event else { return nil } + + return result + } + + /// `Success` value of the instance, if any. + public var value: Success? { + guard case let .success(value) = result else { return nil } + + return value + } + + /// `Failure` value of the instance, if any. + public var error: Failure? { + guard case let .failure(error) = result else { return nil } + + return error + } + + /// `Completion` value of the instance, if any. + public var completion: DataStreamRequest.Completion? { + guard case let .complete(completion) = event else { return nil } + + return completion + } +} + +// MARK: - DownloadRequest + +/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`. +public class DownloadRequest: Request { + /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination + /// `URL`. + public struct Options: OptionSet { + /// Specifies that intermediate directories for the destination URL should be created. + public static let createIntermediateDirectories = Options(rawValue: 1 << 0) + /// Specifies that any previous file at the destination `URL` should be removed. + public static let removePreviousFile = Options(rawValue: 1 << 1) + + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + } + + // MARK: Destination + + /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the + /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL + /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + /// + /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not + /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory. + public typealias Destination = (_ temporaryURL: URL, + _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) + + /// Creates a download file destination closure which uses the default file manager to move the temporary file to a + /// file URL in the first available directory with the specified search path directory and search path domain mask. + /// + /// - Parameters: + /// - directory: The search path directory. `.documentDirectory` by default. + /// - domain: The search path domain mask. `.userDomainMask` by default. + /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by + /// default. + /// - Returns: The `Destination` closure. + public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask, + options: Options = []) -> Destination { + { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL + + return (url, options) + } + } + + /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends + /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files + /// with this destination must be additionally moved if they should survive the system reclamation of temporary + /// space. + static let defaultDestination: Destination = { url, _ in + (defaultDestinationURL(url), []) + } + + /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the + /// provided file name. + static let defaultDestinationURL: (URL) -> URL = { url in + let filename = "Alamofire_\(url.lastPathComponent)" + let destination = url.deletingLastPathComponent().appendingPathComponent(filename) + + return destination + } + + // MARK: Downloadable + + /// Type describing the source used to create the underlying `URLSessionDownloadTask`. + public enum Downloadable { + /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. + case request(URLRequestConvertible) + /// Download should be started from the associated resume `Data` value. + case resumeData(Data) + } + + // MARK: Mutable State + + /// Type containing all mutable state for `DownloadRequest` instances. + private struct DownloadRequestMutableState { + /// Possible resume `Data` produced when cancelling the instance. + var resumeData: Data? + /// `URL` to which `Data` is being downloaded. + var fileURL: URL? + } + + /// Protected mutable state specific to `DownloadRequest`. + @Protected + private var mutableDownloadState = DownloadRequestMutableState() + + /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download + /// using the `download(resumingWith data:)` API. + /// + /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel). + public var resumeData: Data? { + #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. + return $mutableDownloadState.resumeData ?? error?.downloadResumeData + #else + return $mutableDownloadState.resumeData + #endif + } + + /// If the download is successful, the `URL` where the file was downloaded. + public var fileURL: URL? { $mutableDownloadState.fileURL } + + // MARK: Initial State + + /// `Downloadable` value used for this instance. + public let downloadable: Downloadable + /// The `Destination` to which the downloaded file is moved. + let destination: Destination + + /// Creates a `DownloadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request` + /// - destination: `Destination` closure used to move the downloaded file to its final location. + init(id: UUID = UUID(), + downloadable: Downloadable, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate, + destination: @escaping Destination) { + self.downloadable = downloadable + self.destination = destination + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + $mutableDownloadState.write { + $0.resumeData = nil + $0.fileURL = nil + } + } + + /// Called when a download has finished. + /// + /// - Parameters: + /// - task: `URLSessionTask` that finished the download. + /// - result: `Result` of the automatic move to `destination`. + func didFinishDownloading(using task: URLSessionTask, with result: Result) { + eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) + + switch result { + case let .success(url): $mutableDownloadState.fileURL = url + case let .failure(error): self.error = error + } + } + + /// Updates the `downloadProgress` using the provided values. + /// + /// - Parameters: + /// - bytesWritten: Total bytes written so far. + /// - totalBytesExpectedToWrite: Total bytes expected to write. + func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + downloadProgress.totalUnitCount = totalBytesExpectedToWrite + downloadProgress.completedUnitCount += bytesWritten + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + session.downloadTask(with: request) + } + + /// Creates a `URLSessionTask` from the provided resume data. + /// + /// - Parameters: + /// - data: `Data` used to resume the download. + /// - session: `URLSession` used to create the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { + session.downloadTask(withResumeData: data) + } + + /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended. + /// + /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use + /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`. + /// + /// - Returns: The instance. + @discardableResult + override public func cancel() -> Self { + cancel(producingResumeData: false) + } + + /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be + /// resumed or suspended. + /// + /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if + /// available. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self { + cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil) + } + + /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed + /// or suspended. + /// + /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` + /// property. + /// + /// - Parameter completionHandler: The completion handler that is called when the download has been successfully + /// cancelled. It is not guaranteed to be called on a particular queue, so you may + /// want use an appropriate queue to perform your work. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self { + cancel(optionallyProducingResumeData: completionHandler) + } + + /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed, + /// cancellation is performed without producing resume data. + /// + /// - Parameter completionHandler: Optional resume data handler. + /// + /// - Returns: The instance. + private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self { + $mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + if let completionHandler = completionHandler { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel { resumeData in + self.$mutableDownloadState.resumeData = resumeData + self.underlyingQueue.async { self.didCancelTask(task) } + completionHandler(resumeData) + } + } else { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + self.underlyingQueue.async { self.didCancelTask(task) } + } + } + + return self + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure to validate the response. + /// + /// - Returns: The instance. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard error == nil, let response = response else { return } + + let result = validation(request, response, fileURL) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + fileURL: fileURL, + withResult: result) + } + + $validators.write { $0.append(validator) } + + return self + } +} + +// MARK: - UploadRequest + +/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`. +public class UploadRequest: DataRequest { + /// Type describing the origin of the upload, whether `Data`, file, or stream. + public enum Uploadable { + /// Upload from the provided `Data` value. + case data(Data) + /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be + /// automatically removed once uploaded. + case file(URL, shouldRemove: Bool) + /// Upload from the provided `InputStream`. + case stream(InputStream) + } + + // MARK: Initial State + + /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. + public let upload: UploadableConvertible + + /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written + /// to disk. + public let fileManager: FileManager + + // MARK: Mutable State + + /// `Uploadable` value used by the instance. + public var uploadable: Uploadable? + + /// Creates an `UploadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form + /// encoded payloads written to disk. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: UploadConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + fileManager: FileManager, + delegate: RequestDelegate) { + upload = convertible + self.fileManager = fileManager + + super.init(id: id, + convertible: convertible, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + /// Called when the `Uploadable` value has been created from the `UploadConvertible`. + /// + /// - Parameter uploadable: The `Uploadable` that was created. + func didCreateUploadable(_ uploadable: Uploadable) { + self.uploadable = uploadable + + eventMonitor?.request(self, didCreateUploadable: uploadable) + } + + /// Called when the `Uploadable` value could not be created. + /// + /// - Parameter error: `AFError` produced by the failure. + func didFailToCreateUploadable(with error: AFError) { + self.error = error + + eventMonitor?.request(self, didFailToCreateUploadableWithError: error) + + retryOrFinish(error: error) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + guard let uploadable = uploadable else { + fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.") + } + + switch uploadable { + case let .data(data): return session.uploadTask(with: request, from: data) + case let .file(url, _): return session.uploadTask(with: request, fromFile: url) + case .stream: return session.uploadTask(withStreamedRequest: request) + } + } + + override func reset() { + // Uploadable must be recreated on every retry. + uploadable = nil + + super.reset() + } + + /// Produces the `InputStream` from `uploadable`, if it can. + /// + /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash. + /// + /// - Returns: The `InputStream`. + func inputStream() -> InputStream { + guard let uploadable = uploadable else { + fatalError("Attempting to access the input stream but the uploadable doesn't exist.") + } + + guard case let .stream(stream) = uploadable else { + fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") + } + + eventMonitor?.request(self, didProvideInputStream: stream) + + return stream + } + + override public func cleanup() { + defer { super.cleanup() } + + guard + let uploadable = uploadable, + case let .file(url, shouldRemove) = uploadable, + shouldRemove + else { return } + + try? fileManager.removeItem(at: url) + } +} + +/// A type that can produce an `UploadRequest.Uploadable` value. +public protocol UploadableConvertible { + /// Produces an `UploadRequest.Uploadable` value from the instance. + /// + /// - Returns: The `UploadRequest.Uploadable`. + /// - Throws: Any `Error` produced during creation. + func createUploadable() throws -> UploadRequest.Uploadable +} + +extension UploadRequest.Uploadable: UploadableConvertible { + public func createUploadable() throws -> UploadRequest.Uploadable { + self + } +} + +/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. +public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {} diff --git a/Pods/Alamofire/Source/RequestCompression.swift b/Pods/Alamofire/Source/RequestCompression.swift new file mode 100644 index 0000000..c543e06 --- /dev/null +++ b/Pods/Alamofire/Source/RequestCompression.swift @@ -0,0 +1,153 @@ +// +// RequestCompression.swift +// +// Copyright (c) 2023 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(zlib) +import Foundation +import zlib + +/// `RequestAdapter` which compresses outgoing `URLRequest` bodies using the `deflate` `Content-Encoding` and adds the +/// appropriate header. +/// +/// - Note: Most requests to most APIs are small and so would only be slowed down by applying this adapter. Measure the +/// size of your request bodies and the performance impact of using this adapter before use. Using this adapter +/// with already compressed data, such as images, will, at best, have no effect. Additionally, body compression +/// is a synchronous operation, so measuring the performance impact may be important to determine whether you +/// want to use a dedicated `requestQueue` in your `Session` instance. Finally, not all servers support request +/// compression, so test with all of your server configurations before deploying. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DeflateRequestCompressor: RequestInterceptor { + /// Type that determines the action taken when the `URLRequest` already has a `Content-Encoding` header. + public enum DuplicateHeaderBehavior { + /// Throws a `DuplicateHeaderError`. The default. + case error + /// Replaces the existing header value with `deflate`. + case replace + /// Silently skips compression when the header exists. + case skip + } + + /// `Error` produced when the outgoing `URLRequest` already has a `Content-Encoding` header, when the instance has + /// been configured to produce an error. + public struct DuplicateHeaderError: Error {} + + /// Behavior to use when the outgoing `URLRequest` already has a `Content-Encoding` header. + public let duplicateHeaderBehavior: DuplicateHeaderBehavior + /// Closure which determines whether the outgoing body data should be compressed. + public let shouldCompressBodyData: (_ bodyData: Data) -> Bool + + /// Creates an instance with the provided parameters. + /// + /// - Parameters: + /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. `.error` by default. + /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. + public init(duplicateHeaderBehavior: DuplicateHeaderBehavior = .error, + shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true }) { + self.duplicateHeaderBehavior = duplicateHeaderBehavior + self.shouldCompressBodyData = shouldCompressBodyData + } + + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + // No need to compress unless we have body data. No support for compressing streams. + guard let bodyData = urlRequest.httpBody else { + completion(.success(urlRequest)) + return + } + + guard shouldCompressBodyData(bodyData) else { + completion(.success(urlRequest)) + return + } + + if urlRequest.headers.value(for: "Content-Encoding") != nil { + switch duplicateHeaderBehavior { + case .error: + completion(.failure(DuplicateHeaderError())) + return + case .replace: + // Header will be replaced once the body data is compressed. + break + case .skip: + completion(.success(urlRequest)) + return + } + } + + var compressedRequest = urlRequest + + do { + compressedRequest.httpBody = try deflate(bodyData) + compressedRequest.headers.update(.contentEncoding("deflate")) + completion(.success(compressedRequest)) + } catch { + completion(.failure(error)) + } + } + + func deflate(_ data: Data) throws -> Data { + var output = Data([0x78, 0x5E]) // Header + try output.append((data as NSData).compressed(using: .zlib) as Data) + var checksum = adler32Checksum(of: data).bigEndian + output.append(Data(bytes: &checksum, count: MemoryLayout.size)) + + return output + } + + func adler32Checksum(of data: Data) -> UInt32 { + #if swift(>=5.6) + data.withUnsafeBytes { buffer in + UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count))) + } + #else + data.withUnsafeBytes { buffer in + let buffer = buffer.bindMemory(to: UInt8.self) + return UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count))) + } + #endif + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension RequestInterceptor where Self == DeflateRequestCompressor { + /// Create a `DeflateRequestCompressor` with default `duplicateHeaderBehavior` and `shouldCompressBodyData` values. + public static var deflateCompressor: DeflateRequestCompressor { + DeflateRequestCompressor() + } + + /// Creates a `DeflateRequestCompressor` with the provided `DuplicateHeaderBehavior` and `shouldCompressBodyData` + /// closure. + /// + /// - Parameters: + /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. + /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. + /// + /// - Returns: The `DeflateRequestCompressor`. + public static func deflateCompressor( + duplicateHeaderBehavior: DeflateRequestCompressor.DuplicateHeaderBehavior = .error, + shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true } + ) -> DeflateRequestCompressor { + DeflateRequestCompressor(duplicateHeaderBehavior: duplicateHeaderBehavior, + shouldCompressBodyData: shouldCompressBodyData) + } +} +#endif diff --git a/Pods/Alamofire/Source/RequestInterceptor.swift b/Pods/Alamofire/Source/RequestInterceptor.swift new file mode 100644 index 0000000..9acd986 --- /dev/null +++ b/Pods/Alamofire/Source/RequestInterceptor.swift @@ -0,0 +1,351 @@ +// +// RequestInterceptor.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Stores all state associated with a `URLRequest` being adapted. +public struct RequestAdapterState { + /// The `UUID` of the `Request` associated with the `URLRequest` to adapt. + public let requestID: UUID + + /// The `Session` associated with the `URLRequest` to adapt. + public let session: Session +} + +// MARK: - + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest` to adapt. + /// - session: The `Session` that will execute the `URLRequest`. + /// - completion: The completion handler that must be called when adaptation is complete. + func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) + + /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest` to adapt. + /// - state: The `RequestAdapterState` associated with the `URLRequest`. + /// - completion: The completion handler that must be called when adaptation is complete. + func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) +} + +extension RequestAdapter { + public func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { + adapt(urlRequest, for: state.session, completion: completion) + } +} + +// MARK: - + +/// Outcome of determination whether retry is necessary. +public enum RetryResult { + /// Retry should be attempted immediately. + case retry + /// Retry should be attempted after the associated `TimeInterval`. + case retryWithDelay(TimeInterval) + /// Do not retry. + case doNotRetry + /// Do not retry due to the associated `Error`. + case doNotRetryWithError(Error) +} + +extension RetryResult { + var retryRequired: Bool { + switch self { + case .retry, .retryWithDelay: return true + default: return false + } + } + + var delay: TimeInterval? { + switch self { + case let .retryWithDelay(delay): return delay + default: return nil + } + } + + var error: Error? { + guard case let .doNotRetryWithError(error) = self else { return nil } + return error + } +} + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - Parameters: + /// - request: `Request` that failed due to the provided `Error`. + /// - session: `Session` that produced the `Request`. + /// - error: `Error` encountered while executing the `Request`. + /// - completion: Completion closure to be executed when a retry decision has been determined. + func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) +} + +// MARK: - + +/// Type that provides both `RequestAdapter` and `RequestRetrier` functionality. +public protocol RequestInterceptor: RequestAdapter, RequestRetrier {} + +extension RequestInterceptor { + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + completion(.success(urlRequest)) + } + + public func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + completion(.doNotRetry) + } +} + +/// `RequestAdapter` closure definition. +public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result) -> Void) -> Void +/// `RequestRetrier` closure definition. +public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void + +// MARK: - + +/// Closure-based `RequestAdapter`. +open class Adapter: RequestInterceptor { + private let adaptHandler: AdaptHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation. + public init(_ adaptHandler: @escaping AdaptHandler) { + self.adaptHandler = adaptHandler + } + + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + adaptHandler(urlRequest, session, completion) + } + + open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { + adaptHandler(urlRequest, state.session, completion) + } +} + +extension RequestAdapter where Self == Adapter { + /// Creates an `Adapter` using the provided `AdaptHandler` closure. + /// + /// - Parameter closure: `AdaptHandler` to use to adapt the request. + /// - Returns: The `Adapter`. + public static func adapter(using closure: @escaping AdaptHandler) -> Adapter { + Adapter(closure) + } +} + +// MARK: - + +/// Closure-based `RequestRetrier`. +open class Retrier: RequestInterceptor { + private let retryHandler: RetryHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry. + public init(_ retryHandler: @escaping RetryHandler) { + self.retryHandler = retryHandler + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + retryHandler(request, session, error, completion) + } +} + +extension RequestRetrier where Self == Retrier { + /// Creates a `Retrier` using the provided `RetryHandler` closure. + /// + /// - Parameter closure: `RetryHandler` to use to retry the request. + /// - Returns: The `Retrier`. + public static func retrier(using closure: @escaping RetryHandler) -> Retrier { + Retrier(closure) + } +} + +// MARK: - + +/// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values. +open class Interceptor: RequestInterceptor { + /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails. + public let adapters: [RequestAdapter] + /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry. + public let retriers: [RequestRetrier] + + /// Creates an instance from `AdaptHandler` and `RetryHandler` closures. + /// + /// - Parameters: + /// - adaptHandler: `AdaptHandler` closure to be used. + /// - retryHandler: `RetryHandler` closure to be used. + public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) { + adapters = [Adapter(adaptHandler)] + retriers = [Retrier(retryHandler)] + } + + /// Creates an instance from `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapter: `RequestAdapter` value to be used. + /// - retrier: `RequestRetrier` value to be used. + public init(adapter: RequestAdapter, retrier: RequestRetrier) { + adapters = [adapter] + retriers = [retrier] + } + + /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapters: `RequestAdapter` values to be used. + /// - retriers: `RequestRetrier` values to be used. + /// - interceptors: `RequestInterceptor`s to be used. + public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = [], interceptors: [RequestInterceptor] = []) { + self.adapters = adapters + interceptors + self.retriers = retriers + interceptors + } + + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + adapt(urlRequest, for: session, using: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + for session: Session, + using adapters: [RequestAdapter], + completion: @escaping (Result) -> Void) { + var pendingAdapters = adapters + + guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } + + let adapter = pendingAdapters.removeFirst() + + adapter.adapt(urlRequest, for: session) { result in + switch result { + case let .success(urlRequest): + self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion) + case .failure: + completion(result) + } + } + } + + open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { + adapt(urlRequest, using: state, adapters: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + using state: RequestAdapterState, + adapters: [RequestAdapter], + completion: @escaping (Result) -> Void) { + var pendingAdapters = adapters + + guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } + + let adapter = pendingAdapters.removeFirst() + + adapter.adapt(urlRequest, using: state) { result in + switch result { + case let .success(urlRequest): + self.adapt(urlRequest, using: state, adapters: pendingAdapters, completion: completion) + case .failure: + completion(result) + } + } + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + retry(request, for: session, dueTo: error, using: retriers, completion: completion) + } + + private func retry(_ request: Request, + for session: Session, + dueTo error: Error, + using retriers: [RequestRetrier], + completion: @escaping (RetryResult) -> Void) { + var pendingRetriers = retriers + + guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return } + + let retrier = pendingRetriers.removeFirst() + + retrier.retry(request, for: session, dueTo: error) { result in + switch result { + case .retry, .retryWithDelay, .doNotRetryWithError: + completion(result) + case .doNotRetry: + // Only continue to the next retrier if retry was not triggered and no error was encountered + self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion) + } + } + } +} + +extension RequestInterceptor where Self == Interceptor { + /// Creates an `Interceptor` using the provided `AdaptHandler` and `RetryHandler` closures. + /// + /// - Parameters: + /// - adapter: `AdapterHandler`to use to adapt the request. + /// - retrier: `RetryHandler` to use to retry the request. + /// - Returns: The `Interceptor`. + public static func interceptor(adapter: @escaping AdaptHandler, retrier: @escaping RetryHandler) -> Interceptor { + Interceptor(adaptHandler: adapter, retryHandler: retrier) + } + + /// Creates an `Interceptor` using the provided `RequestAdapter` and `RequestRetrier` instances. + /// - Parameters: + /// - adapter: `RequestAdapter` to use to adapt the request + /// - retrier: `RequestRetrier` to use to retry the request. + /// - Returns: The `Interceptor`. + public static func interceptor(adapter: RequestAdapter, retrier: RequestRetrier) -> Interceptor { + Interceptor(adapter: adapter, retrier: retrier) + } + + /// Creates an `Interceptor` using the provided `RequestAdapter`s, `RequestRetrier`s, and `RequestInterceptor`s. + /// - Parameters: + /// - adapters: `RequestAdapter`s to use to adapt the request. These adapters will be run until one fails. + /// - retriers: `RequestRetrier`s to use to retry the request. These retriers will be run one at a time until + /// a retry is triggered. + /// - interceptors: `RequestInterceptor`s to use to intercept the request. + /// - Returns: The `Interceptor`. + public static func interceptor(adapters: [RequestAdapter] = [], + retriers: [RequestRetrier] = [], + interceptors: [RequestInterceptor] = []) -> Interceptor { + Interceptor(adapters: adapters, retriers: retriers, interceptors: interceptors) + } +} diff --git a/Pods/Alamofire/Source/RequestTaskMap.swift b/Pods/Alamofire/Source/RequestTaskMap.swift new file mode 100644 index 0000000..9955875 --- /dev/null +++ b/Pods/Alamofire/Source/RequestTaskMap.swift @@ -0,0 +1,149 @@ +// +// RequestTaskMap.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that maintains a two way, one to one map of `URLSessionTask`s to `Request`s. +struct RequestTaskMap { + private typealias Events = (completed: Bool, metricsGathered: Bool) + + private var tasksToRequests: [URLSessionTask: Request] + private var requestsToTasks: [Request: URLSessionTask] + private var taskEvents: [URLSessionTask: Events] + + var requests: [Request] { + Array(tasksToRequests.values) + } + + init(tasksToRequests: [URLSessionTask: Request] = [:], + requestsToTasks: [Request: URLSessionTask] = [:], + taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:]) { + self.tasksToRequests = tasksToRequests + self.requestsToTasks = requestsToTasks + self.taskEvents = taskEvents + } + + subscript(_ request: Request) -> URLSessionTask? { + get { requestsToTasks[request] } + set { + guard let newValue = newValue else { + guard let task = requestsToTasks[request] else { + fatalError("RequestTaskMap consistency error: no task corresponding to request found.") + } + + requestsToTasks.removeValue(forKey: request) + tasksToRequests.removeValue(forKey: task) + taskEvents.removeValue(forKey: task) + + return + } + + requestsToTasks[request] = newValue + tasksToRequests[newValue] = request + taskEvents[newValue] = (completed: false, metricsGathered: false) + } + } + + subscript(_ task: URLSessionTask) -> Request? { + get { tasksToRequests[task] } + set { + guard let newValue = newValue else { + guard let request = tasksToRequests[task] else { + fatalError("RequestTaskMap consistency error: no request corresponding to task found.") + } + + tasksToRequests.removeValue(forKey: task) + requestsToTasks.removeValue(forKey: request) + taskEvents.removeValue(forKey: task) + + return + } + + tasksToRequests[task] = newValue + requestsToTasks[newValue] = task + taskEvents[task] = (completed: false, metricsGathered: false) + } + } + + var count: Int { + precondition(tasksToRequests.count == requestsToTasks.count, + "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)") + + return tasksToRequests.count + } + + var eventCount: Int { + precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)") + + return taskEvents.count + } + + var isEmpty: Bool { + precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty, + "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)") + + return tasksToRequests.isEmpty + } + + var isEventsEmpty: Bool { + precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)") + + return taskEvents.isEmpty + } + + mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) -> Bool { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.") + case (false, false): taskEvents[task] = (completed: false, metricsGathered: true); return false + case (true, false): self[task] = nil; return true + } + } + + mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) -> Bool { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.") + #if os(Linux) || os(Android) // Linux doesn't gather metrics, so unconditionally remove the reference and return true. + default: self[task] = nil; return true + #else + case (false, false): + if #available(macOS 10.12, iOS 10, watchOS 7, tvOS 10, *) { + taskEvents[task] = (completed: true, metricsGathered: false); return false + } else { + // watchOS < 7 doesn't gather metrics, so unconditionally remove the reference and return true. + self[task] = nil; return true + } + case (false, true): + self[task] = nil; return true + #endif + } + } +} diff --git a/Pods/Alamofire/Source/Response.swift b/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..d9ae9d8 --- /dev/null +++ b/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,453 @@ +// +// Response.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDataResponse = DataResponse +/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDownloadResponse = DownloadResponse + +/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The final metrics of the response. + /// + /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` + /// + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { result.failure } + + /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - data: The `Data` returned by the server. + /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.data = data + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + "\(result)" + } + + /// The debug textual representation used when written to an output stream, which includes (if available) a summary + /// of the `URLRequest`, the request's headers and body (if decodable as a `String` below 100KB); the + /// `HTTPURLResponse`'s status code, headers, and body; the duration of the network and serialization actions; and + /// the `Result` of serialization. + public var debugDescription: String { + guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } + + let requestDescription = DebugDescription.description(of: urlRequest) + + let responseDescription = response.map { response in + let responseBodyDescription = DebugDescription.description(for: data, headers: response.headers) + + return """ + \(DebugDescription.description(of: response)) + \(responseBodyDescription.indentingNewlines()) + """ + } ?? "[Response]: None" + + let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + + return """ + \(requestDescription) + \(responseDescription) + [Network Duration]: \(networkDuration) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Success) -> NewSuccess) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func mapError(_ transform: (Failure) -> NewFailure) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The final destination URL of the data returned from the server after it is moved. + public let fileURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The final metrics of the response. + /// + /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` + /// + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { result.failure } + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - fileURL: The final destination URL of the data returned from the server after it is moved. + /// - resumeData: The resume `Data` generated if the request was cancelled. + /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + fileURL: URL?, + resumeData: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.fileURL = fileURL + self.resumeData = resumeData + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + "\(result)" + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization + /// actions, and the response serialization result. + public var debugDescription: String { + guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } + + let requestDescription = DebugDescription.description(of: urlRequest) + let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None" + let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + let resumeDataDescription = resumeData.map { "\($0)" } ?? "None" + + return """ + \(requestDescription) + \(responseDescription) + [File URL]: \(fileURL?.path ?? "None") + [Resume Data]: \(resumeDataDescription) + [Network Duration]: \(networkDuration) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Success) -> NewSuccess) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func mapError(_ transform: (Failure) -> NewFailure) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} + +private enum DebugDescription { + static func description(of request: URLRequest) -> String { + let requestSummary = "\(request.httpMethod!) \(request)" + let requestHeadersDescription = DebugDescription.description(for: request.headers) + let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers) + + return """ + [Request]: \(requestSummary) + \(requestHeadersDescription.indentingNewlines()) + \(requestBodyDescription.indentingNewlines()) + """ + } + + static func description(of response: HTTPURLResponse) -> String { + """ + [Response]: + [Status Code]: \(response.statusCode) + \(DebugDescription.description(for: response.headers).indentingNewlines()) + """ + } + + static func description(for headers: HTTPHeaders) -> String { + guard !headers.isEmpty else { return "[Headers]: None" } + + let headerDescription = "\(headers.sorted())".indentingNewlines() + return """ + [Headers]: + \(headerDescription) + """ + } + + static func description(for data: Data?, + headers: HTTPHeaders, + allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"], + maximumLength: Int = 100_000) -> String { + guard let data = data, !data.isEmpty else { return "[Body]: None" } + + guard + data.count <= maximumLength, + printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true) + else { return "[Body]: \(data.count) bytes" } + + return """ + [Body]: + \(String(decoding: data, as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines) + .indentingNewlines()) + """ + } +} + +extension String { + fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String { + let spaces = String(repeating: " ", count: spaceCount) + return replacingOccurrences(of: "\n", with: "\n\(spaces)") + } +} diff --git a/Pods/Alamofire/Source/ResponseSerialization.swift b/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..0e718bd --- /dev/null +++ b/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,1270 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +// MARK: Protocols + +/// The type to which all data response serializers must conform in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created. + associatedtype SerializedObject + + /// Serialize the response `Data` into the provided type.. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - data: `Data` returned from the server, if any. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject +} + +/// The type to which all download response serializers must conform in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created. + associatedtype SerializedObject + + /// Serialize the downloaded response `Data` from disk into the provided type.. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - fileURL: File `URL` to which the response data was downloaded. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject +} + +/// A serializer that can handle both data and download responses. +public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { + /// `DataPreprocessor` used to prepare incoming `Data` for serialization. + var dataPreprocessor: DataPreprocessor { get } + /// `HTTPMethod`s for which empty response bodies are considered appropriate. + var emptyRequestMethods: Set { get } + /// HTTP response codes for which empty response bodies are considered appropriate. + var emptyResponseCodes: Set { get } +} + +/// Type used to preprocess `Data` before it handled by a serializer. +public protocol DataPreprocessor { + /// Process `Data` before it's handled by a serializer. + /// - Parameter data: The raw `Data` to process. + func preprocess(_ data: Data) throws -> Data +} + +/// `DataPreprocessor` that returns passed `Data` without any transform. +public struct PassthroughPreprocessor: DataPreprocessor { + public init() {} + + public func preprocess(_ data: Data) throws -> Data { data } +} + +/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header. +public struct GoogleXSSIPreprocessor: DataPreprocessor { + public init() {} + + public func preprocess(_ data: Data) throws -> Data { + (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data + } +} + +extension DataPreprocessor where Self == PassthroughPreprocessor { + /// Provides a `PassthroughPreprocessor` instance. + public static var passthrough: PassthroughPreprocessor { PassthroughPreprocessor() } +} + +extension DataPreprocessor where Self == GoogleXSSIPreprocessor { + /// Provides a `GoogleXSSIPreprocessor` instance. + public static var googleXSSI: GoogleXSSIPreprocessor { GoogleXSSIPreprocessor() } +} + +extension ResponseSerializer { + /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default. + public static var defaultDataPreprocessor: DataPreprocessor { PassthroughPreprocessor() } + /// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default. + public static var defaultEmptyRequestMethods: Set { [.head] } + /// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default. + public static var defaultEmptyResponseCodes: Set { [204, 205] } + + public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor } + public var emptyRequestMethods: Set { Self.defaultEmptyRequestMethods } + public var emptyResponseCodes: Set { Self.defaultEmptyResponseCodes } + + /// Determines whether the `request` allows empty response bodies, if `request` exists. + /// + /// - Parameter request: `URLRequest` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`. + public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? { + request.flatMap(\.httpMethod) + .flatMap(HTTPMethod.init) + .map { emptyRequestMethods.contains($0) } + } + + /// Determines whether the `response` allows empty response bodies, if `response` exists`. + /// + /// - Parameter response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`. + public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? { + response.map(\.statusCode) + .map { emptyResponseCodes.contains($0) } + } + + /// Determines whether `request` and `response` allow empty response bodies. + /// + /// - Parameters: + /// - request: `URLRequest` to evaluate. + /// - response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise. + public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool { + (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true) + } +} + +/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds +/// the data read from disk into the data response serializer. +extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol { + public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject { + guard error == nil else { throw error! } + + guard let fileURL = fileURL else { + throw AFError.responseSerializationFailed(reason: .inputFileNil) + } + + let data: Data + do { + data = try Data(contentsOf: fileURL) + } catch { + throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)) + } + + do { + return try serialize(request: request, response: response, data: data, error: error) + } catch { + throw error + } + } +} + +// MARK: - Default + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.data, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + private func _response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = ProcessInfo.processInfo.systemUptime + let result: AFResult = Result { + try responseSerializer.serialize(request: self.request, + response: self.response, + data: self.data, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + + let end = ProcessInfo.processInfo.systemUptime + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard !self.isCancelled, let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (() -> Void)? + + defer { + if let didComplete = didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.fileURL, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + private func _response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = ProcessInfo.processInfo.systemUptime + let result: AFResult = Result { + try responseSerializer.serializeDownload(request: self.request, + response: self.response, + fileURL: self.fileURL, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + let end = ProcessInfo.processInfo.systemUptime + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (() -> Void)? + + defer { + if let didComplete = didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data + /// contained in the destination `URL`. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data + /// contained in the destination `URL`. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} + +// MARK: - URL + +/// A `DownloadResponseSerializerProtocol` that performs only `Error` checking and ensures that a downloaded `fileURL` +/// is present. +public struct URLResponseSerializer: DownloadResponseSerializerProtocol { + /// Creates an instance. + public init() {} + + public func serializeDownload(request: URLRequest?, + response: HTTPURLResponse?, + fileURL: URL?, + error: Error?) throws -> URL { + guard error == nil else { throw error! } + + guard let url = fileURL else { + throw AFError.responseSerializationFailed(reason: .inputFileNil) + } + + return url + } +} + +extension DownloadResponseSerializerProtocol where Self == URLResponseSerializer { + /// Provides a `URLResponseSerializer` instance. + public static var url: URLResponseSerializer { URLResponseSerializer() } +} + +extension DownloadRequest { + /// Adds a handler using a `URLResponseSerializer` to be called once the request is finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseURL(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler) + } +} + +// MARK: - Data + +/// A `ResponseSerializer` that performs minimal response checking and returns any response `Data` as-is. By default, a +/// request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the +/// response has an HTTP status code valid for empty responses, then an empty `Data` value is returned. +public final class DataResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates a `DataResponseSerializer` using the provided parameters. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return Data() + } + + data = try dataPreprocessor.preprocess(data) + + return data + } +} + +extension ResponseSerializer where Self == DataResponseSerializer { + /// Provides a default `DataResponseSerializer` instance. + public static var data: DataResponseSerializer { DataResponseSerializer() } + + /// Creates a `DataResponseSerializer` using the provided parameters. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `DataResponseSerializer`. + public static func data(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponseSerializer { + DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +extension DataRequest { + /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseData(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseData(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +// MARK: - String + +/// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no +/// data is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code +/// valid for empty responses, then an empty `String` is returned. +public final class StringResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + /// Optional string encoding used to validate the response. + public let encoding: String.Encoding? + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.encoding = encoding + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return "" + } + + data = try dataPreprocessor.preprocess(data) + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName, convertedEncoding == nil { + convertedEncoding = String.Encoding(ianaCharsetName: encodingName) + } + + let actualEncoding = convertedEncoding ?? .isoLatin1 + + guard let string = String(data: data, encoding: actualEncoding) else { + throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)) + } + + return string + } +} + +extension ResponseSerializer where Self == StringResponseSerializer { + /// Provides a default `StringResponseSerializer` instance. + public static var string: StringResponseSerializer { StringResponseSerializer() } + + /// Creates a `StringResponseSerializer` with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `StringResponseSerializer`. + public static func string(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> StringResponseSerializer { + StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +extension DataRequest { + /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseString(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseString(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +// MARK: - JSON + +/// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning +/// `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the response has an +/// HTTP status code valid for empty responses, then an `NSNull` value is returned. +@available(*, deprecated, message: "JSONResponseSerializer deprecated and will be removed in Alamofire 6. Use DecodableResponseSerializer instead.") +public final class JSONResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + /// `JSONSerialization.ReadingOptions` used when serializing a response. + public let options: JSONSerialization.ReadingOptions + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// - options: The options to use. `.allowFragments` by default. + public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + self.options = options + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return NSNull() + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try JSONSerialization.jsonObject(with: data, options: options) + } catch { + throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)) + } + } +} + +extension DataRequest { + /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` + /// by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods, + options: options), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` + /// by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods, + options: options), + completionHandler: completionHandler) + } +} + +// MARK: - Empty + +/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance. +public protocol EmptyResponse { + /// Empty value for the conforming type. + /// + /// - Returns: Value of `Self` to use for empty values. + static func emptyValue() -> Self +} + +/// Type representing an empty value. Use `Empty.value` to get the static instance. +public struct Empty: Codable { + /// Static `Empty` instance used for all `Empty` responses. + public static let value = Empty() +} + +extension Empty: EmptyResponse { + public static func emptyValue() -> Empty { + value + } +} + +// MARK: - DataDecoder Protocol + +/// Any type which can decode `Data` into a `Decodable` type. +public protocol DataDecoder { + /// Decode `Data` into the provided type. + /// + /// - Parameters: + /// - type: The `Type` to be decoded. + /// - data: The `Data` to be decoded. + /// + /// - Returns: The decoded value of type `D`. + /// - Throws: Any error that occurs during decode. + func decode(_ type: D.Type, from data: Data) throws -> D +} + +/// `JSONDecoder` automatically conforms to `DataDecoder`. +extension JSONDecoder: DataDecoder {} +/// `PropertyListDecoder` automatically conforms to `DataDecoder`. +extension PropertyListDecoder: DataDecoder {} + +// MARK: - Decodable + +/// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to +/// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data +/// is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code valid +/// for empty responses then an empty value will be returned. If the decoded type conforms to `EmptyResponse`, the +/// type's `emptyValue()` will be returned. If the decoded type is `Empty`, the `.value` instance is returned. If the +/// decoded type *does not* conform to `EmptyResponse` and isn't `Empty`, an error will be produced. +public final class DecodableResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + /// The `DataDecoder` instance used to decode responses. + public let decoder: DataDecoder + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance using the values provided. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.decoder = decoder + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else { + throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)")) + } + + return emptyValue + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try decoder.decode(T.self, from: data) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) + } + } +} + +extension ResponseSerializer { + /// Creates a `DecodableResponseSerializer` using the values provided. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `DecodableResponseSerializer`. + public static func decodable(of type: T.Type, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DecodableResponseSerializer where Self == DecodableResponseSerializer { + DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +extension DataRequest { + /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} + +// MARK: - DataStreamRequest + +/// A type which can serialize incoming `Data`. +public protocol DataStreamSerializer { + /// Type produced from the serialized `Data`. + associatedtype SerializedObject + + /// Serializes incoming `Data` into a `SerializedObject` value. + /// + /// - Parameter data: `Data` to be serialized. + /// + /// - Throws: Any error produced during serialization. + func serialize(_ data: Data) throws -> SerializedObject +} + +/// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`. +public struct DecodableStreamSerializer: DataStreamSerializer { + /// `DataDecoder` used to decode incoming `Data`. + public let decoder: DataDecoder + /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`. + public let dataPreprocessor: DataPreprocessor + + /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`. + /// - Parameters: + /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. + /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the + /// `decoder`. `PassthroughPreprocessor()` by default. + public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) { + self.decoder = decoder + self.dataPreprocessor = dataPreprocessor + } + + public func serialize(_ data: Data) throws -> T { + let processedData = try dataPreprocessor.preprocess(data) + do { + return try decoder.decode(T.self, from: processedData) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) + } + } +} + +/// `DataStreamSerializer` which performs no serialization on incoming `Data`. +public struct PassthroughStreamSerializer: DataStreamSerializer { + /// Creates an instance. + public init() {} + + public func serialize(_ data: Data) throws -> Data { data } +} + +/// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values. +public struct StringStreamSerializer: DataStreamSerializer { + /// Creates an instance. + public init() {} + + public func serialize(_ data: Data) throws -> String { + String(decoding: data, as: UTF8.self) + } +} + +extension DataStreamSerializer { + /// Creates a `DecodableStreamSerializer` instance with the provided `DataDecoder` and `DataPreprocessor`. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from stream data. + /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. + /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the + /// `decoder`. `PassthroughPreprocessor()` by default. + public static func decodable(of type: T.Type, + decoder: DataDecoder = JSONDecoder(), + dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) -> Self where Self == DecodableStreamSerializer { + DecodableStreamSerializer(decoder: decoder, dataPreprocessor: dataPreprocessor) + } +} + +extension DataStreamSerializer where Self == PassthroughStreamSerializer { + /// Provides a `PassthroughStreamSerializer` instance. + public static var passthrough: PassthroughStreamSerializer { PassthroughStreamSerializer() } +} + +extension DataStreamSerializer where Self == StringStreamSerializer { + /// Provides a `StringStreamSerializer` instance. + public static var string: StringStreamSerializer { StringStreamSerializer() } +} + +extension DataStreamRequest { + /// Adds a `StreamHandler` which performs no parsing on incoming `Data`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler) -> Self { + let parser = { [unowned self] (data: Data) in + queue.async { + self.capturingError { + try stream(.init(event: .stream(.success(data)), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + + $streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`. + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStream(using serializer: Serializer, + on queue: DispatchQueue = .main, + stream: @escaping Handler) -> Self { + let parser = { [unowned self] (data: Data) in + serializationQueue.async { + // Start work on serialization queue. + let result = Result { try serializer.serialize(data) } + .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) } + // End work on serialization queue. + self.underlyingQueue.async { + self.eventMonitor?.request(self, didParseStream: result) + + if result.isFailure, self.automaticallyCancelOnStreamError { + self.cancel() + } + + queue.async { + self.capturingError { + try stream(.init(event: .stream(result), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + } + } + + $streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStreamString(on queue: DispatchQueue = .main, + stream: @escaping Handler) -> Self { + let parser = { [unowned self] (data: Data) in + serializationQueue.async { + // Start work on serialization queue. + let string = String(decoding: data, as: UTF8.self) + // End work on serialization queue. + self.underlyingQueue.async { + self.eventMonitor?.request(self, didParseStream: .success(string)) + + queue.async { + self.capturingError { + try stream(.init(event: .stream(.success(string)), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + } + } + + $streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + private func updateAndCompleteIfPossible() { + $streamMutableState.write { state in + state.numberOfExecutingStreams -= 1 + + guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return } + + let completionEvents = state.enqueuedCompletionEvents + self.underlyingQueue.async { completionEvents.forEach { $0() } } + state.enqueuedCompletionEvents.removeAll() + } + } + + /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`. + /// + /// - Parameters: + /// - type: `Decodable` type to parse incoming `Data` into. + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - decoder: `DataDecoder` used to decode the incoming `Data`. + /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStreamDecodable(of type: T.Type = T.self, + on queue: DispatchQueue = .main, + using decoder: DataDecoder = JSONDecoder(), + preprocessor: DataPreprocessor = PassthroughPreprocessor(), + stream: @escaping Handler) -> Self { + responseStream(using: DecodableStreamSerializer(decoder: decoder, dataPreprocessor: preprocessor), + stream: stream) + } +} diff --git a/Pods/Alamofire/Source/Result+Alamofire.swift b/Pods/Alamofire/Source/Result+Alamofire.swift new file mode 100644 index 0000000..39ac286 --- /dev/null +++ b/Pods/Alamofire/Source/Result+Alamofire.swift @@ -0,0 +1,120 @@ +// +// Result+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Default type of `Result` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFResult = Result + +// MARK: - Internal APIs + +extension Result { + /// Returns whether the instance is `.success`. + var isSuccess: Bool { + guard case .success = self else { return false } + return true + } + + /// Returns whether the instance is `.failure`. + var isFailure: Bool { + !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + var success: Success? { + guard case let .success(value) = self else { return nil } + return value + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + var failure: Failure? { + guard case let .failure(error) = self else { return nil } + return error + } + + /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise. + /// + /// - Parameters: + /// - value: A value. + /// - error: An `Error`. + init(value: Success, error: Failure?) { + if let error = error { + self = .failure(error) + } else { + self = .success(value) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + func tryMap(_ transform: (Success) throws -> NewSuccess) -> Result { + switch self { + case let .success(value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case let .failure(error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same success. + func tryMapError(_ transform: (Failure) throws -> NewFailure) -> Result { + switch self { + case let .failure(error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case let .success(value): + return .success(value) + } + } +} diff --git a/Pods/Alamofire/Source/RetryPolicy.swift b/Pods/Alamofire/Source/RetryPolicy.swift new file mode 100644 index 0000000..bb52c6c --- /dev/null +++ b/Pods/Alamofire/Source/RetryPolicy.swift @@ -0,0 +1,430 @@ +// +// RetryPolicy.swift +// +// Copyright (c) 2019-2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes +/// as well as certain types of networking errors. +open class RetryPolicy: RequestInterceptor { + /// The default retry limit for retry policies. + public static let defaultRetryLimit: UInt = 2 + + /// The default exponential backoff base for retry policies (must be a minimum of 2). + public static let defaultExponentialBackoffBase: UInt = 2 + + /// The default exponential backoff scale for retry policies. + public static let defaultExponentialBackoffScale: Double = 0.5 + + /// The default HTTP methods to retry. + /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information. + public static let defaultRetryableHTTPMethods: Set = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent + .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent + .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent + .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent + .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent + .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent + ] + + /// The default HTTP status codes to retry. + /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information. + public static let defaultRetryableHTTPStatusCodes: Set = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9) + 500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1) + 502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3) + 503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4) + 504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5) + ] + + /// The default URL error codes to retry. + public static let defaultRetryableURLErrorCodes: Set = [ // [Security] App Transport Security disallowed a connection because there is no secure network connection. + // - [Disabled] ATS settings do not change at runtime. + // .appTransportSecurityRequiresSecureConnection, + + // [System] An app or app extension attempted to connect to a background session that is already connected to a + // process. + // - [Enabled] The other process could release the background session. + .backgroundSessionInUseByAnotherProcess, + + // [System] The shared container identifier of the URL session configuration is needed but has not been set. + // - [Disabled] Cannot change at runtime. + // .backgroundSessionRequiresSharedContainer, + + // [System] The app is suspended or exits while a background data task is processing. + // - [Enabled] App can be foregrounded or launched to recover. + .backgroundSessionWasDisconnected, + + // [Network] The URL Loading system received bad data from the server. + // - [Enabled] Server could return valid data when retrying. + .badServerResponse, + + // [Resource] A malformed URL prevented a URL request from being initiated. + // - [Disabled] URL was most likely constructed incorrectly. + // .badURL, + + // [System] A connection was attempted while a phone call is active on a network that does not support + // simultaneous phone and data communication (EDGE or GPRS). + // - [Enabled] Phone call could be ended to allow request to recover. + .callIsActive, + + // [Client] An asynchronous load has been canceled. + // - [Disabled] Request was cancelled by the client. + // .cancelled, + + // [File System] A download task couldn’t close the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCloseFile, + + // [Network] An attempt to connect to a host failed. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotConnectToHost, + + // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCreateFile, + + // [Data] Content data received during a connection request had an unknown content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeContentData, + + // [Data] Content data received during a connection request could not be decoded for a known content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeRawData, + + // [Network] The host name for a URL could not be resolved. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotFindHost, + + // [Network] A request to load an item only from the cache could not be satisfied. + // - [Enabled] Cache could be populated during a retry. + .cannotLoadFromNetwork, + + // [File System] A download task was unable to move a downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotMoveFile, + + // [File System] A download task was unable to open the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotOpenFile, + + // [Data] A task could not parse a response. + // - [Disabled] Invalid response is unlikely to recover with retry. + // .cannotParseResponse, + + // [File System] A download task was unable to remove a downloaded file from disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotRemoveFile, + + // [File System] A download task was unable to write to the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotWriteToFile, + + // [Security] A client certificate was rejected. + // - [Disabled] Client certificate is unlikely to change with retry. + // .clientCertificateRejected, + + // [Security] A client certificate was required to authenticate an SSL connection during a request. + // - [Disabled] Client certificate is unlikely to be provided with retry. + // .clientCertificateRequired, + + // [Data] The length of the resource data exceeds the maximum allowed. + // - [Disabled] Resource will likely still exceed the length maximum on retry. + // .dataLengthExceedsMaximum, + + // [System] The cellular network disallowed a connection. + // - [Enabled] WiFi connection could be established during retry. + .dataNotAllowed, + + // [Network] The host address could not be found via DNS lookup. + // - [Enabled] DNS lookup could succeed during retry. + .dnsLookupFailed, + + // [Data] A download task failed to decode an encoded file during the download. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedMidStream, + + // [Data] A download task failed to decode an encoded file after downloading. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedToComplete, + + // [File System] A file does not exist. + // - [Disabled] File system error is unlikely to recover with retry. + // .fileDoesNotExist, + + // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file, + // but a directory. + // - [Disabled] FTP directory is not likely to change to a file during a retry. + // .fileIsDirectory, + + // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been + // exceeded (currently 16). + // - [Disabled] The redirect loop is unlikely to be resolved within the retry window. + // .httpTooManyRedirects, + + // [System] The attempted connection required activating a data context while roaming, but international roaming + // is disabled. + // - [Enabled] WiFi connection could be established during retry. + .internationalRoamingOff, + + // [Connectivity] A client or server connection was severed in the middle of an in-progress load. + // - [Enabled] A network connection could be established during retry. + .networkConnectionLost, + + // [File System] A resource couldn’t be read because of insufficient permissions. + // - [Disabled] Permissions are unlikely to be granted during retry. + // .noPermissionsToReadFile, + + // [Connectivity] A network resource was requested, but an internet connection has not been established and + // cannot be established automatically. + // - [Enabled] A network connection could be established during retry. + .notConnectedToInternet, + + // [Resource] A redirect was specified by way of server response code, but the server did not accompany this + // code with a redirect URL. + // - [Disabled] The redirect URL is unlikely to be supplied during a retry. + // .redirectToNonExistentLocation, + + // [Client] A body stream is needed but the client did not provide one. + // - [Disabled] The client will be unlikely to supply a body stream during retry. + // .requestBodyStreamExhausted, + + // [Resource] A requested resource couldn’t be retrieved. + // - [Disabled] The resource is unlikely to become available during the retry window. + // .resourceUnavailable, + + // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more + // specifically. + // - [Enabled] The secure connection could be established during a retry given the lack of specificity + // provided by the error. + .secureConnectionFailed, + + // [Security] A server certificate had a date which indicates it has expired, or is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateHasBadDate, + + // [Security] A server certificate was not signed by any root server. + // - [Disabled] The server certificate is unlikely to change during the retry window. + // .serverCertificateHasUnknownRoot, + + // [Security] A server certificate is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateNotYetValid, + + // [Security] A server certificate was signed by a root server that isn’t trusted. + // - [Disabled] The server certificate is unlikely to become trusted within the retry window. + // .serverCertificateUntrusted, + + // [Network] An asynchronous operation timed out. + // - [Enabled] The request timed out for an unknown reason and should be retried. + .timedOut + + // [System] The URL Loading System encountered an error that it can’t interpret. + // - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry. + // .unknown, + + // [Resource] A properly formed URL couldn’t be handled by the framework. + // - [Disabled] The URL is unlikely to change during a retry. + // .unsupportedURL, + + // [Client] Authentication is required to access a resource. + // - [Disabled] The user authentication is unlikely to be provided by retrying. + // .userAuthenticationRequired, + + // [Client] An asynchronous request for authentication has been canceled by the user. + // - [Disabled] The user cancelled authentication and explicitly took action to not retry. + // .userCancelledAuthentication, + + // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection + // gracefully without sending any data. + // - [Disabled] The server is unlikely to provide data during the retry window. + // .zeroByteResource, + ] + + /// The total number of times the request is allowed to be retried. + public let retryLimit: UInt + + /// The base of the exponential backoff policy (should always be greater than or equal to 2). + public let exponentialBackoffBase: UInt + + /// The scale of the exponential backoff. + public let exponentialBackoffScale: Double + + /// The HTTP methods that are allowed to be retried. + public let retryableHTTPMethods: Set + + /// The HTTP status codes that are automatically retried by the policy. + public let retryableHTTPStatusCodes: Set + + /// The URL error codes that are automatically retried by the policy. + public let retryableURLErrorCodes: Set + + /// Creates a `RetryPolicy` from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. + /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. + /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) { + precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.") + + self.retryLimit = retryLimit + self.exponentialBackoffBase = exponentialBackoffBase + self.exponentialBackoffScale = exponentialBackoffScale + self.retryableHTTPMethods = retryableHTTPMethods + self.retryableHTTPStatusCodes = retryableHTTPStatusCodes + self.retryableURLErrorCodes = retryableURLErrorCodes + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + if request.retryCount < retryLimit, shouldRetry(request: request, dueTo: error) { + completion(.retryWithDelay(pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale)) + } else { + completion(.doNotRetry) + } + } + + /// Determines whether or not to retry the provided `Request`. + /// + /// - Parameters: + /// - request: `Request` that failed due to the provided `Error`. + /// - error: `Error` encountered while executing the `Request`. + /// + /// - Returns: `Bool` determining whether or not to retry the `Request`. + open func shouldRetry(request: Request, dueTo error: Error) -> Bool { + guard let httpMethod = request.request?.method, retryableHTTPMethods.contains(httpMethod) else { return false } + + if let statusCode = request.response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) { + return true + } else { + let errorCode = (error as? URLError)?.code + let afErrorCode = (error.asAFError?.underlyingError as? URLError)?.code + + guard let code = errorCode ?? afErrorCode else { return false } + + return retryableURLErrorCodes.contains(code) + } + } +} + +extension RequestInterceptor where Self == RetryPolicy { + /// Provides a default `RetryPolicy` instance. + public static var retryPolicy: RetryPolicy { RetryPolicy() } + + /// Creates an `RetryPolicy` from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. + /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. + /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. + /// + /// - Returns: The `RetryPolicy` + public static func retryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) -> RetryPolicy { + RetryPolicy(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: retryableHTTPStatusCodes, + retryableURLErrorCodes: retryableURLErrorCodes) + } +} + +// MARK: - + +/// A retry policy that automatically retries idempotent requests for network connection lost errors. For more +/// information about retrying network connection lost errors, please refer to Apple's +/// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html). +open class ConnectionLostRetryPolicy: RetryPolicy { + /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. + /// `RetryPolicy.defaultRetryLimit` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. + /// `RetryPolicy.defaultExponentialBackoffBase` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. + /// `RetryPolicy.defaultExponentialBackoffScale` by default. + /// - retryableHTTPMethods: The idempotent http methods to retry. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) { + super.init(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: [], + retryableURLErrorCodes: [.networkConnectionLost]) + } +} + +extension RequestInterceptor where Self == ConnectionLostRetryPolicy { + /// Provides a default `ConnectionLostRetryPolicy` instance. + public static var connectionLostRetryPolicy: ConnectionLostRetryPolicy { ConnectionLostRetryPolicy() } + + /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. + /// `RetryPolicy.defaultRetryLimit` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. + /// `RetryPolicy.defaultExponentialBackoffBase` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. + /// `RetryPolicy.defaultExponentialBackoffScale` by default. + /// - retryableHTTPMethods: The idempotent http methods to retry. + /// + /// - Returns: The `ConnectionLostRetryPolicy`. + public static func connectionLostRetryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) -> ConnectionLostRetryPolicy { + ConnectionLostRetryPolicy(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods) + } +} diff --git a/Pods/Alamofire/Source/ServerTrustEvaluation.swift b/Pods/Alamofire/Source/ServerTrustEvaluation.swift new file mode 100644 index 0000000..e490ab4 --- /dev/null +++ b/Pods/Alamofire/Source/ServerTrustEvaluation.swift @@ -0,0 +1,772 @@ +// +// ServerTrustEvaluation.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts. +open class ServerTrustManager { + /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default. + public let allHostsMustBeEvaluated: Bool + + /// The dictionary of policies mapped to a particular host. + public let evaluators: [String: ServerTrustEvaluating] + + /// Initializes the `ServerTrustManager` instance with the given evaluators. + /// + /// Since different servers and web services can have different leaf certificates, intermediate and even root + /// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + /// pinning for host3 and disabling evaluation for host4. + /// + /// - Parameters: + /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true` + /// by default. + /// - evaluators: A dictionary of evaluators mapped to hosts. + public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) { + self.allHostsMustBeEvaluated = allHostsMustBeEvaluated + self.evaluators = evaluators + } + + #if canImport(Security) + /// Returns the `ServerTrustEvaluating` value for the given host, if one is set. + /// + /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override + /// this method and implement more complex mapping implementations such as wildcards. + /// + /// - Parameter host: The host to use when searching for a matching policy. + /// + /// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise. + /// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching + /// evaluators are found. + open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? { + guard let evaluator = evaluators[host] else { + if allHostsMustBeEvaluated { + throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host)) + } + + return nil + } + + return evaluator + } + #endif +} + +/// A protocol describing the API used to evaluate server trusts. +public protocol ServerTrustEvaluating { + #if !canImport(Security) + // Implement this once other platforms have API for evaluating server trusts. + #else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`. + func evaluate(_ trust: SecTrust, forHost host: String) throws + #endif +} + +// MARK: - Server Trust Evaluators + +#if canImport(Security) +/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the +/// host provided by the challenge. Applications are encouraged to always validate the host in production environments +/// to guarantee the validity of the server's certificate chain. +public final class DefaultTrustEvaluator: ServerTrustEvaluating { + private let validateHost: Bool + + /// Creates a `DefaultTrustEvaluator`. + /// + /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default. + public init(validateHost: Bool = true) { + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if validateHost { + try trust.af.performValidation(forHost: host) + } + + try trust.af.performDefaultValidation(forHost: host) + } +} + +/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate +/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. +/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS +/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production +/// environments to guarantee the validity of the server's certificate chain. +public final class RevocationTrustEvaluator: ServerTrustEvaluating { + /// Represents the options to be use when evaluating the status of a certificate. + /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants). + public struct Options: OptionSet { + /// Perform revocation checking using the CRL (Certification Revocation List) method. + public static let crl = Options(rawValue: kSecRevocationCRLMethod) + /// Consult only locally cached replies; do not use network access. + public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled) + /// Perform revocation checking using OCSP (Online Certificate Status Protocol). + public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod) + /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred. + public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL) + /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a + /// "best attempt" basis, where failure to reach the server is not considered fatal. + public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse) + /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the + /// certificate and the value of `preferCRL`. + public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod) + + /// The raw value of the option. + public let rawValue: CFOptionFlags + + /// Creates an `Options` value with the given `CFOptionFlags`. + /// + /// - Parameter rawValue: The `CFOptionFlags` value to initialize with. + public init(rawValue: CFOptionFlags) { + self.rawValue = rawValue + } + } + + private let performDefaultValidation: Bool + private let validateHost: Bool + private let options: Options + + /// Creates a `RevocationTrustEvaluator` using the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + /// - options: The `Options` to use to check the revocation status of the certificate. `.any` by + /// default. + public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) { + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + self.options = options + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + #if swift(>=5.9) + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { + try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) + } else { + try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) + } + } + #else + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { + try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) + } else { + try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) + } + } + #endif + } +} + +extension ServerTrustEvaluating where Self == RevocationTrustEvaluator { + /// Provides a default `RevocationTrustEvaluator` instance. + public static var revocationChecking: RevocationTrustEvaluator { RevocationTrustEvaluator() } + + /// Creates a `RevocationTrustEvaluator` using the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + /// - options: The `Options` to use to check the revocation status of the certificate. `.any` + /// by default. + /// - Returns: The `RevocationTrustEvaluator`. + public static func revocationChecking(performDefaultValidation: Bool = true, + validateHost: Bool = true, + options: RevocationTrustEvaluator.Options = .any) -> RevocationTrustEvaluator { + RevocationTrustEvaluator(performDefaultValidation: performDefaultValidation, + validateHost: validateHost, + options: options) + } +} + +/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned +/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate +/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate chain in production +/// environments. +public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating { + private let certificates: [SecCertificate] + private let acceptSelfSignedCertificates: Bool + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PinnedCertificatesTrustEvaluator` from the provided parameters. + /// + /// - Parameters: + /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing + /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE + /// FALSE IN PRODUCTION! + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + public init(certificates: [SecCertificate] = Bundle.main.af.certificates, + acceptSelfSignedCertificates: Bool = false, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.certificates = certificates + self.acceptSelfSignedCertificates = acceptSelfSignedCertificates + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !certificates.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) + } + + if acceptSelfSignedCertificates { + try trust.af.setAnchorCertificates(certificates) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let serverCertificatesData = Set(trust.af.certificateData) + let pinnedCertificatesData = Set(certificates.af.data) + let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData) + if !pinnedCertificatesInServerData { + throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host, + trust: trust, + pinnedCertificates: certificates, + serverCertificates: trust.af.certificates)) + } + } +} + +extension ServerTrustEvaluating where Self == PinnedCertificatesTrustEvaluator { + /// Provides a default `PinnedCertificatesTrustEvaluator` instance. + public static var pinnedCertificates: PinnedCertificatesTrustEvaluator { PinnedCertificatesTrustEvaluator() } + + /// Creates a `PinnedCertificatesTrustEvaluator` using the provided parameters. + /// + /// - Parameters: + /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing + /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE + /// FALSE IN PRODUCTION! + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + public static func pinnedCertificates(certificates: [SecCertificate] = Bundle.main.af.certificates, + acceptSelfSignedCertificates: Bool = false, + performDefaultValidation: Bool = true, + validateHost: Bool = true) -> PinnedCertificatesTrustEvaluator { + PinnedCertificatesTrustEvaluator(certificates: certificates, + acceptSelfSignedCertificates: acceptSelfSignedCertificates, + performDefaultValidation: performDefaultValidation, + validateHost: validateHost) + } +} + +/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned +/// public keys match one of the server certificate public keys. By validating both the certificate chain and host, +/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate chain in production +/// environments. +public final class PublicKeysTrustEvaluator: ServerTrustEvaluating { + private let keys: [SecKey] + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all + /// certificates included in the main bundle. + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + public init(keys: [SecKey] = Bundle.main.af.publicKeys, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.keys = keys + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !keys.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let pinnedKeysInServerKeys: Bool = { + for serverPublicKey in trust.af.publicKeys { + if keys.contains(serverPublicKey) { + return true + } + } + return false + }() + + if !pinnedKeysInServerKeys { + throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host, + trust: trust, + pinnedKeys: keys, + serverKeys: trust.af.publicKeys)) + } + } +} + +extension ServerTrustEvaluating where Self == PublicKeysTrustEvaluator { + /// Provides a default `PublicKeysTrustEvaluator` instance. + public static var publicKeys: PublicKeysTrustEvaluator { PublicKeysTrustEvaluator() } + + /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all + /// certificates included in the main bundle. + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + public static func publicKeys(keys: [SecKey] = Bundle.main.af.publicKeys, + performDefaultValidation: Bool = true, + validateHost: Bool = true) -> PublicKeysTrustEvaluator { + PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: performDefaultValidation, validateHost: validateHost) + } +} + +/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the +/// evaluators consider it valid. +public final class CompositeTrustEvaluator: ServerTrustEvaluating { + private let evaluators: [ServerTrustEvaluating] + + /// Creates a `CompositeTrustEvaluator` from the provided evaluators. + /// + /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. + public init(evaluators: [ServerTrustEvaluating]) { + self.evaluators = evaluators + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + try evaluators.evaluate(trust, forHost: host) + } +} + +extension ServerTrustEvaluating where Self == CompositeTrustEvaluator { + /// Creates a `CompositeTrustEvaluator` from the provided evaluators. + /// + /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. + public static func composite(evaluators: [ServerTrustEvaluating]) -> CompositeTrustEvaluator { + CompositeTrustEvaluator(evaluators: evaluators) + } +} + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test +/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +@available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.") +public typealias DisabledEvaluator = DisabledTrustEvaluator + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// +/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test +/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +public final class DisabledTrustEvaluator: ServerTrustEvaluating { + /// Creates an instance. + public init() {} + + public func evaluate(_ trust: SecTrust, forHost host: String) throws {} +} + +// MARK: - Extensions + +extension Array where Element == ServerTrustEvaluating { + #if os(Linux) || os(Windows) || os(Android) + // Add this same convenience method for Linux/Windows. + #else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`. + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + for evaluator in self { + try evaluator.evaluate(trust, forHost: host) + } + } + #endif +} + +extension Bundle: AlamofireExtended {} +extension AlamofireExtension where ExtendedType: Bundle { + /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle. + public var certificates: [SecCertificate] { + paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in + guard + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil } + + return certificate + } + } + + /// Returns all public keys for the valid certificates in the bundle. + public var publicKeys: [SecKey] { + certificates.af.publicKeys + } + + /// Returns all pathnames for the resources identified by the provided file extensions. + /// + /// - Parameter types: The filename extensions locate. + /// + /// - Returns: All pathnames for the given filename extensions. + public func paths(forResourcesOfTypes types: [String]) -> [String] { + Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) })) + } +} + +extension SecTrust: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecTrust { + /// Evaluates `self` after applying the `SecPolicy` value provided. + /// + /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation. + /// + /// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + public func evaluate(afterApplying policy: SecPolicy) throws { + try apply(policy: policy).af.evaluate() + } + + /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed. + /// + /// - Parameters: + /// - policy: The `SecPolicy` used to evaluate `self`. + /// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`. + /// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)") + public func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { + try apply(policy: policy).af.validate(errorProducer: errorProducer) + } + + /// Applies a `SecPolicy` to `self`, throwing if it fails. + /// + /// - Parameter policy: The `SecPolicy`. + /// + /// - Returns: `self`, with the policy applied. + /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason. + public func apply(policy: SecPolicy) throws -> SecTrust { + let status = SecTrustSetPolicies(type, policy) + + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type, + policy: policy, + status: status)) + } + + return type + } + + /// Evaluate `self`, throwing an `Error` if evaluation fails. + /// + /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from + /// the underlying evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + public func evaluate() throws { + var error: CFError? + let evaluationSucceeded = SecTrustEvaluateWithError(type, &error) + + if !evaluationSucceeded { + throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error)) + } + } + + /// Validate `self`, passing any failure values through `errorProducer`. + /// + /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an + /// `Error`. + /// - Throws: The `Error` produced by the `errorProducer` closure. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()") + public func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(type, &result) + + guard status.af.isSuccess && result.af.isSuccess else { + throw errorProducer(status, result) + } + } + + /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain. + /// + /// - Parameter certificates: The `SecCertificate`s to add to the chain. + /// - Throws: Any error produced when applying the new certificate chain. + public func setAnchorCertificates(_ certificates: [SecCertificate]) throws { + // Add additional anchor certificates. + let status = SecTrustSetAnchorCertificates(type, certificates as CFArray) + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status, + certificates: certificates)) + } + + // Trust only the set anchor certs. + let onlyStatus = SecTrustSetAnchorCertificatesOnly(type, true) + guard onlyStatus.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: onlyStatus, + certificates: certificates)) + } + } + + /// The public keys contained in `self`. + public var publicKeys: [SecKey] { + certificates.af.publicKeys + } + + /// The `SecCertificate`s contained in `self`. + public var certificates: [SecCertificate] { + #if swift(>=5.9) + if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, visionOS 1, *) { + return (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? [] + } else { + return (0..=5.5.1) // Xcode 13.1 / 2021 SDKs. + if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { + return (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? [] + } else { + return (0..=5.9) + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { + try evaluate(afterApplying: SecPolicy.af.default) + } else { + try validate(policy: SecPolicy.af.default) { status, result in + AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result))) + } + } + #else + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { + try evaluate(afterApplying: SecPolicy.af.default) + } else { + try validate(policy: SecPolicy.af.default) { status, result in + AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result))) + } + } + #endif + } + + /// Validates `self` after applying `SecPolicy.af.hostname(host)`, which performs the default validation as well as + /// hostname validation. + /// + /// - Parameter host: The hostname to use in the validation. + /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason. + public func performValidation(forHost host: String) throws { + #if swift(>=5.9) + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { + try evaluate(afterApplying: SecPolicy.af.hostname(host)) + } else { + try validate(policy: SecPolicy.af.hostname(host)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result))) + } + } + #else + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { + try evaluate(afterApplying: SecPolicy.af.hostname(host)) + } else { + try validate(policy: SecPolicy.af.hostname(host)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result))) + } + } + #endif + } +} + +extension SecPolicy: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecPolicy { + /// Creates a `SecPolicy` instance which will validate server certificates but not require a host name match. + public static let `default` = SecPolicyCreateSSL(true, nil) + + /// Creates a `SecPolicy` instance which will validate server certificates and much match the provided hostname. + /// + /// - Parameter hostname: The hostname to validate against. + /// + /// - Returns: The `SecPolicy`. + public static func hostname(_ hostname: String) -> SecPolicy { + SecPolicyCreateSSL(true, hostname as CFString) + } + + /// Creates a `SecPolicy` which checks the revocation of certificates. + /// + /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation. + /// + /// - Returns: The `SecPolicy`. + /// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed` + /// if the policy cannot be created. + public static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy { + guard let policy = SecPolicyCreateRevocation(options.rawValue) else { + throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed) + } + + return policy + } +} + +extension Array: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == [SecCertificate] { + /// All `Data` values for the contained `SecCertificate`s. + public var data: [Data] { + type.map { SecCertificateCopyData($0) as Data } + } + + /// All public `SecKey` values for the contained `SecCertificate`s. + public var publicKeys: [SecKey] { + type.compactMap(\.af.publicKey) + } +} + +extension SecCertificate: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecCertificate { + /// The public key for `self`, if it can be extracted. + /// + /// - Note: On 2020 OSes and newer, only RSA and ECDSA keys are supported. + /// + public var publicKey: SecKey? { + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust) + + guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil } + + #if swift(>=5.9) + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, visionOS 1, *) { + return SecTrustCopyKey(createdTrust) + } else { + return SecTrustCopyPublicKey(createdTrust) + } + #else + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) { + return SecTrustCopyKey(createdTrust) + } else { + return SecTrustCopyPublicKey(createdTrust) + } + #endif + } +} + +extension OSStatus: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == OSStatus { + /// Returns whether `self` is `errSecSuccess`. + public var isSuccess: Bool { type == errSecSuccess } +} + +extension SecTrustResultType: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecTrustResultType { + /// Returns whether `self is `.unspecified` or `.proceed`. + public var isSuccess: Bool { + type == .unspecified || type == .proceed + } +} +#endif diff --git a/Pods/Alamofire/Source/Session.swift b/Pods/Alamofire/Source/Session.swift new file mode 100644 index 0000000..4232f85 --- /dev/null +++ b/Pods/Alamofire/Source/Session.swift @@ -0,0 +1,1264 @@ +// +// Session.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common +/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response +/// cache handling. +open class Session { + /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified. + public static let `default` = Session() + + /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's + /// `delegate` handles `URLSessionDelegate` callbacks. + /// + /// - Note: This instance should **NOT** be used to interact with the underlying `URLSessionTask`s. Doing so will + /// break internal Alamofire logic that tracks those tasks. + /// + public let session: URLSession + /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction. + public let delegate: SessionDelegate + /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue. + public let rootQueue: DispatchQueue + /// Value determining whether this instance automatically calls `resume()` on all created `Request`s. + public let startRequestsImmediately: Bool + /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its + /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile + /// and test before introducing an additional queue. + public let requestQueue: DispatchQueue + /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this + /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined + /// to be a bottleneck. Always profile and test before introducing an additional queue. + public let serializationQueue: DispatchQueue + /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a + /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value. + public let interceptor: RequestInterceptor? + /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning. + public let serverTrustManager: ServerTrustManager? + /// `RedirectHandler` instance used to provide customization for request redirection. + public let redirectHandler: RedirectHandler? + /// `CachedResponseHandler` instance used to provide customization of cached response handling. + public let cachedResponseHandler: CachedResponseHandler? + /// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s. + public let eventMonitor: CompositeEventMonitor + /// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default. + public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()] + + /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them. + var requestTaskMap = RequestTaskMap() + /// `Set` of currently active `Request`s. + var activeRequests: Set = [] + /// Completion events awaiting `URLSessionTaskMetrics`. + var waitingCompletions: [URLSessionTask: () -> Void] = [:] + + /// Creates a `Session` from a `URLSession` and other parameters. + /// + /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and + /// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer. + /// + /// - Parameters: + /// - session: Underlying `URLSession` for this instance. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a + /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. + public init(session: URLSession, + delegate: SessionDelegate, + rootQueue: DispatchQueue, + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: RequestInterceptor? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: RedirectHandler? = nil, + cachedResponseHandler: CachedResponseHandler? = nil, + eventMonitors: [EventMonitor] = []) { + precondition(session.configuration.identifier == nil, + "Alamofire does not support background URLSessionConfigurations.") + precondition(session.delegateQueue.underlyingQueue === rootQueue, + "Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.") + + self.session = session + self.delegate = delegate + self.rootQueue = rootQueue + self.startRequestsImmediately = startRequestsImmediately + self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue) + self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue) + self.interceptor = interceptor + self.serverTrustManager = serverTrustManager + self.redirectHandler = redirectHandler + self.cachedResponseHandler = cachedResponseHandler + eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors) + delegate.eventMonitor = eventMonitor + delegate.stateProvider = self + } + + /// Creates a `Session` from a `URLSessionConfiguration`. + /// + /// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its + /// `delegateQueue`, and is the recommended initializer for most uses. + /// + /// - Parameters: + /// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes + /// to this value after being passed to this initializer will have no effect. + /// `URLSessionConfiguration.af.default` by default. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. `SessionDelegate()` by default. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a + /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. + public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default, + delegate: SessionDelegate = SessionDelegate(), + rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"), + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: RequestInterceptor? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: RedirectHandler? = nil, + cachedResponseHandler: CachedResponseHandler? = nil, + eventMonitors: [EventMonitor] = []) { + precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.") + + // Retarget the incoming rootQueue for safety, unless it's the main queue, which we know is safe. + let serialRootQueue = (rootQueue === DispatchQueue.main) ? rootQueue : DispatchQueue(label: rootQueue.label, + target: rootQueue) + let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: serialRootQueue, name: "\(serialRootQueue.label).sessionDelegate") + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue) + + self.init(session: session, + delegate: delegate, + rootQueue: serialRootQueue, + startRequestsImmediately: startRequestsImmediately, + requestQueue: requestQueue, + serializationQueue: serializationQueue, + interceptor: interceptor, + serverTrustManager: serverTrustManager, + redirectHandler: redirectHandler, + cachedResponseHandler: cachedResponseHandler, + eventMonitors: eventMonitors) + } + + deinit { + finishRequestsForDeinit() + session.invalidateAndCancel() + } + + // MARK: - All Requests API + + /// Perform an action on all active `Request`s. + /// + /// - Note: The provided `action` closure is performed asynchronously, meaning that some `Request`s may complete and + /// be unavailable by time it runs. Additionally, this action is performed on the instances's `rootQueue`, + /// so care should be taken that actions are fast. Once the work on the `Request`s is complete, any + /// additional work should be performed on another queue. + /// + /// - Parameters: + /// - action: Closure to perform with all `Request`s. + public func withAllRequests(perform action: @escaping (Set) -> Void) { + rootQueue.async { + action(self.activeRequests) + } + } + + /// Cancel all active `Request`s, optionally calling a completion handler when complete. + /// + /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled + /// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to + /// completion when cancelled. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default. + /// - completion: Closure to be called when all `Request`s have been cancelled. + public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) { + withAllRequests { requests in + requests.forEach { $0.cancel() } + queue.async { + completion?() + } + } + } + + // MARK: - DataRequest + + /// Closure which provides a `URLRequest` for mutation. + public typealias RequestModifier = (inout URLRequest) throws -> Void + + struct RequestConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoding: ParameterEncoding + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return try encoding.encode(request, with: parameters) + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by + /// default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncoding.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + requestModifier: requestModifier) + + return request(convertible, interceptor: interceptor) + } + + struct RequestEncodableConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoder: ParameterEncoder + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return try parameters.map { try encoder.encode($0, into: request) } ?? request + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncodedFormParameterEncoder.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return request(convertible, interceptor: interceptor) + } + + /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { + let request = DataRequest(convertible: convertible, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + // MARK: - DataStreamRequest + + /// Creates a `DataStreamRequest` from the passed components, `Encodable` parameters, and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the + /// `URLRequest`. + /// `URLEncodedFormParameterEncoder.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataStream` request. + open func streamRequest(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + automaticallyCancelOnStreamError: Bool = false, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataStreamRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return streamRequest(convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + interceptor: interceptor) + } + + /// Creates a `DataStreamRequest` from the passed components and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataStream` request. + open func streamRequest(_ convertible: URLConvertible, + method: HTTPMethod = .get, + headers: HTTPHeaders? = nil, + automaticallyCancelOnStreamError: Bool = false, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataStreamRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: Empty?.none, + encoder: URLEncodedFormParameterEncoder.default, + headers: headers, + requestModifier: requestModifier) + + return streamRequest(convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + interceptor: interceptor) + } + + /// Creates a `DataStreamRequest` from the passed `URLRequestConvertible` value and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// + /// - Returns: The created `DataStreamRequest`. + open func streamRequest(_ convertible: URLRequestConvertible, + automaticallyCancelOnStreamError: Bool = false, + interceptor: RequestInterceptor? = nil) -> DataStreamRequest { + let request = DataStreamRequest(convertible: convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + // MARK: - DownloadRequest + + /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and + /// `Destination`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by + /// default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. + /// Defaults to `URLEncoding.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + requestModifier: requestModifier) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and + /// a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. + /// Defaults to `URLEncodedFormParameterEncoder.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .request(convertible), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as + /// well as a `RequestInterceptor`, and a `Destination`. + /// + /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by + /// Alamofire. The file will not be deleted until the system purges the temporary files. + /// + /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), + /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` + /// generation logic where the data is written incorrectly and will always fail to resume the download. For more + /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462). + /// + /// - Parameters: + /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(resumingWith data: Data, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .resumeData(data), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + // MARK: - UploadRequest + + struct ParameterlessRequestConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return request + } + } + + struct Upload: UploadConvertible { + let request: URLRequestConvertible + let uploadable: UploadableConvertible + + func createUploadable() throws -> UploadRequest.Uploadable { + try uploadable.createUploadable() + } + + func asURLRequest() throws -> URLRequest { + try request.asURLRequest() + } + } + + // MARK: Data + + /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: File + + /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided + /// components and `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: MultipartFormData + + /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided + /// `URLRequest` components and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the + /// provided parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + to url: URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, + method: method, + headers: headers, + requestModifier: requestModifier) + + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: convertible, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible` + /// value, and a `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: request, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components + /// and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the + /// provided parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + to url: URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, + method: method, + headers: headers, + requestModifier: requestModifier) + + let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, + request: convertible, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible` + /// value and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, + request: request, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: - Internal API + + // MARK: Uploadable + + func upload(_ uploadable: UploadRequest.Uploadable, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor?, + fileManager: FileManager) -> UploadRequest { + let uploadable = Upload(request: convertible, uploadable: uploadable) + + return upload(uploadable, interceptor: interceptor, fileManager: fileManager) + } + + func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest { + let request = UploadRequest(convertible: upload, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + fileManager: fileManager, + delegate: self) + + perform(request) + + return request + } + + // MARK: Perform + + /// Starts performing the provided `Request`. + /// + /// - Parameter request: The `Request` to perform. + func perform(_ request: Request) { + rootQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + self.requestQueue.async { + // Leaf types must come first, otherwise they will cast as their superclass. + switch request { + case let r as UploadRequest: self.performUploadRequest(r) // UploadRequest must come before DataRequest due to subtype relationship. + case let r as DataRequest: self.performDataRequest(r) + case let r as DownloadRequest: self.performDownloadRequest(r) + case let r as DataStreamRequest: self.performDataStreamRequest(r) + default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") + } + } + } + } + + func performDataRequest(_ request: DataRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + + func performDataStreamRequest(_ request: DataStreamRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + + func performUploadRequest(_ request: UploadRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) { + do { + let uploadable = try request.upload.createUploadable() + self.rootQueue.async { request.didCreateUploadable(uploadable) } + return true + } catch { + self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) } + return false + } + } + } + + func performDownloadRequest(_ request: DownloadRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + switch request.downloadable { + case let .request(convertible): + performSetupOperations(for: request, convertible: convertible) + case let .resumeData(resumeData): + rootQueue.async { self.didReceiveResumeData(resumeData, for: request) } + } + } + + func performSetupOperations(for request: Request, + convertible: URLRequestConvertible, + shouldCreateTask: @escaping () -> Bool = { true }) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + let initialRequest: URLRequest + + do { + initialRequest = try convertible.asURLRequest() + try initialRequest.validate() + } catch { + rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) } + return + } + + rootQueue.async { request.didCreateInitialURLRequest(initialRequest) } + + guard !request.isCancelled else { return } + + guard let adapter = adapter(for: request) else { + guard shouldCreateTask() else { return } + rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) } + return + } + + let adapterState = RequestAdapterState(requestID: request.id, session: self) + + adapter.adapt(initialRequest, using: adapterState) { result in + do { + let adaptedRequest = try result.get() + try adaptedRequest.validate() + + self.rootQueue.async { request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) } + + guard shouldCreateTask() else { return } + + self.rootQueue.async { self.didCreateURLRequest(adaptedRequest, for: request) } + } catch { + self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) } + } + } + } + + // MARK: - Task Handling + + func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + request.didCreateURLRequest(urlRequest) + + guard !request.isCancelled else { return } + + let task = request.task(for: urlRequest, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func didReceiveResumeData(_ data: Data, for request: DownloadRequest) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + guard !request.isCancelled else { return } + + let task = request.task(forResumeData: data, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func updateStatesForTask(_ task: URLSessionTask, request: Request) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + request.withState { state in + switch state { + case .initialized, .finished: + // Do nothing. + break + case .resumed: + task.resume() + rootQueue.async { request.didResumeTask(task) } + case .suspended: + task.suspend() + rootQueue.async { request.didSuspendTask(task) } + case .cancelled: + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + rootQueue.async { request.didCancelTask(task) } + } + } + } + + // MARK: - Adapters and Retriers + + func adapter(for request: Request) -> RequestAdapter? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + return Interceptor(adapters: [requestInterceptor, sessionInterceptor]) + } else { + return request.interceptor ?? interceptor + } + } + + func retrier(for request: Request) -> RequestRetrier? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + return Interceptor(retriers: [requestInterceptor, sessionInterceptor]) + } else { + return request.interceptor ?? interceptor + } + } + + // MARK: - Invalidation + + func finishRequestsForDeinit() { + requestTaskMap.requests.forEach { request in + rootQueue.async { + request.finish(error: AFError.sessionDeinitialized) + } + } + } +} + +// MARK: - RequestDelegate + +extension Session: RequestDelegate { + public var sessionConfiguration: URLSessionConfiguration { + session.configuration + } + + public var startImmediately: Bool { startRequestsImmediately } + + public func cleanup(after request: Request) { + activeRequests.remove(request) + } + + public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) { + guard let retrier = retrier(for: request) else { + rootQueue.async { completion(.doNotRetry) } + return + } + + retrier.retry(request, for: self, dueTo: error) { retryResult in + self.rootQueue.async { + guard let retryResultError = retryResult.error else { completion(retryResult); return } + + let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error) + completion(.doNotRetryWithError(retryError)) + } + } + } + + public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) { + rootQueue.async { + let retry: () -> Void = { + guard !request.isCancelled else { return } + + request.prepareForRetry() + self.perform(request) + } + + if let retryDelay = timeDelay { + self.rootQueue.after(retryDelay) { retry() } + } else { + retry() + } + } + } +} + +// MARK: - SessionStateProvider + +extension Session: SessionStateProvider { + func request(for task: URLSessionTask) -> Request? { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + return requestTaskMap[task] + } + + func didGatherMetricsForTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task) + + if didDisassociate { + waitingCompletions[task]?() + waitingCompletions[task] = nil + } + } + + func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task) + + if didDisassociate { + completion() + } else { + waitingCompletions[task] = completion + } + } + + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + return requestTaskMap[task]?.credential ?? + session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace) + } + + func cancelRequestsForSessionInvalidation(with error: Error?) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) } + } +} diff --git a/Pods/Alamofire/Source/SessionDelegate.swift b/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..af45b27 --- /dev/null +++ b/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,355 @@ +// +// SessionDelegate.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. +open class SessionDelegate: NSObject { + private let fileManager: FileManager + + weak var stateProvider: SessionStateProvider? + var eventMonitor: EventMonitor? + + /// Creates an instance from the given `FileManager`. + /// + /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files. + /// `.default` by default. + public init(fileManager: FileManager = .default) { + self.fileManager = fileManager + } + + /// Internal method to find and cast requests while maintaining some integrity checking. + /// + /// - Parameters: + /// - task: The `URLSessionTask` for which to find the associated `Request`. + /// - type: The `Request` subclass type to cast any `Request` associate with `task`. + func request(for task: URLSessionTask, as type: R.Type) -> R? { + guard let provider = stateProvider else { + assertionFailure("StateProvider is nil.") + return nil + } + + return provider.request(for: task) as? R + } +} + +/// Type which provides various `Session` state values. +protocol SessionStateProvider: AnyObject { + var serverTrustManager: ServerTrustManager? { get } + var redirectHandler: RedirectHandler? { get } + var cachedResponseHandler: CachedResponseHandler? { get } + + func request(for task: URLSessionTask) -> Request? + func didGatherMetricsForTask(_ task: URLSessionTask) + func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? + func cancelRequestsForSessionInvalidation(with error: Error?) +} + +// MARK: URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) + + stateProvider?.cancelRequestsForSessionInvalidation(with: error) + } +} + +// MARK: URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// Result of a `URLAuthenticationChallenge` evaluation. + typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?) + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + eventMonitor?.urlSession(session, task: task, didReceive: challenge) + + let evaluation: ChallengeEvaluation + switch challenge.protectionSpace.authenticationMethod { + case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, + NSURLAuthenticationMethodNegotiate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + #if canImport(Security) + case NSURLAuthenticationMethodServerTrust: + evaluation = attemptServerTrustAuthentication(with: challenge) + case NSURLAuthenticationMethodClientCertificate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + #endif + default: + evaluation = (.performDefaultHandling, nil, nil) + } + + if let error = evaluation.error { + stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) + } + + completionHandler(evaluation.disposition, evaluation.credential) + } + + #if canImport(Security) + /// Evaluates the server trust `URLAuthenticationChallenge` received. + /// + /// - Parameter challenge: The `URLAuthenticationChallenge`. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { + let host = challenge.protectionSpace.host + + guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, + let trust = challenge.protectionSpace.serverTrust + else { + return (.performDefaultHandling, nil, nil) + } + + do { + guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { + return (.performDefaultHandling, nil, nil) + } + + try evaluator.evaluate(trust, forHost: host) + + return (.useCredential, URLCredential(trust: trust), nil) + } catch { + return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) + } + } + #endif + + /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. + /// + /// - Parameters: + /// - challenge: The `URLAuthenticationChallenge`. + /// - task: The `URLSessionTask` which received the challenge. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge, + belongingTo task: URLSessionTask) -> ChallengeEvaluation { + guard challenge.previousFailureCount == 0 else { + return (.rejectProtectionSpace, nil, nil) + } + + guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { + return (.performDefaultHandling, nil, nil) + } + + return (.useCredential, credential, nil) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + eventMonitor?.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + + stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { + eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) + + guard let request = request(for: task, as: UploadRequest.self) else { + assertionFailure("needNewBodyStream did not find UploadRequest.") + completionHandler(nil) + return + } + + completionHandler(request.inputStream()) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { + eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request) + + if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { + redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) + } else { + completionHandler(request) + } + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) + + stateProvider?.request(for: task)?.didGatherMetrics(metrics) + + stateProvider?.didGatherMetricsForTask(task) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) + + let request = stateProvider?.request(for: task) + + stateProvider?.didCompleteTask(task) { + request?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) + } + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task) + } +} + +// MARK: URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + open func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: response) + + guard let response = response as? HTTPURLResponse else { completionHandler(.allow); return } + + if let request = request(for: dataTask, as: DataRequest.self) { + request.didReceiveResponse(response, completionHandler: completionHandler) + } else if let request = request(for: dataTask, as: DataStreamRequest.self) { + request.didReceiveResponse(response, completionHandler: completionHandler) + } else { + assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive response") + completionHandler(.allow) + return + } + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) + + if let request = request(for: dataTask, as: DataRequest.self) { + request.didReceive(data: data) + } else if let request = request(for: dataTask, as: DataStreamRequest.self) { + request.didReceive(data: data) + } else { + assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive data") + return + } + } + + open func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) { + eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) + + if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { + handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, + totalBytesExpectedToWrite: expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + + guard let request = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + let (destination, options): (URL, DownloadRequest.Options) + if let response = request.response { + (destination, options) = request.destination(location, response) + } else { + // If there's no response this is likely a local file download, so generate the temporary URL directly. + (destination, options) = (DownloadRequest.defaultDestinationURL(location), []) + } + + eventMonitor?.request(request, didCreateDestinationURL: destination) + + do { + if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { + try fileManager.removeItem(at: destination) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destination.deletingLastPathComponent() + try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try fileManager.moveItem(at: location, to: destination) + + request.didFinishDownloading(using: downloadTask, with: .success(destination)) + } catch { + request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, + source: location, + destination: destination))) + } + } +} diff --git a/Pods/Alamofire/Source/StringEncoding+Alamofire.swift b/Pods/Alamofire/Source/StringEncoding+Alamofire.swift new file mode 100644 index 0000000..8fa6133 --- /dev/null +++ b/Pods/Alamofire/Source/StringEncoding+Alamofire.swift @@ -0,0 +1,55 @@ +// +// StringEncoding+Alamofire.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension String.Encoding { + /// Creates an encoding from the IANA charset name. + /// + /// - Notes: These mappings match those [provided by CoreFoundation](https://opensource.apple.com/source/CF/CF-476.18/CFStringUtilities.c.auto.html) + /// + /// - Parameter name: IANA charset name. + init?(ianaCharsetName name: String) { + switch name.lowercased() { + case "utf-8": + self = .utf8 + case "iso-8859-1": + self = .isoLatin1 + case "unicode-1-1", "iso-10646-ucs-2", "utf-16": + self = .utf16 + case "utf-16be": + self = .utf16BigEndian + case "utf-16le": + self = .utf16LittleEndian + case "utf-32": + self = .utf32 + case "utf-32be": + self = .utf32BigEndian + case "utf-32le": + self = .utf32LittleEndian + default: + return nil + } + } +} diff --git a/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift b/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift new file mode 100644 index 0000000..455c4bc --- /dev/null +++ b/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift @@ -0,0 +1,105 @@ +// +// URLConvertible+URLRequestConvertible.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `URLConvertible` protocol can be used to construct `URL`s, which can then be used to construct +/// `URLRequests`. +public protocol URLConvertible { + /// Returns a `URL` from the conforming instance or throws. + /// + /// - Returns: The `URL` created from the instance. + /// - Throws: Any error thrown while creating the `URL`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a `URL` if `self` can be used to initialize a `URL` instance, otherwise throws. + /// + /// - Returns: The `URL` initialized with `self`. + /// - Throws: An `AFError.invalidURL` instance. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + + return url + } +} + +extension URL: URLConvertible { + /// Returns `self`. + public func asURL() throws -> URL { self } +} + +extension URLComponents: URLConvertible { + /// Returns a `URL` if the `self`'s `url` is not nil, otherwise throws. + /// + /// - Returns: The `URL` from the `url` property. + /// - Throws: An `AFError.invalidURL` instance. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to safely construct `URLRequest`s. +public protocol URLRequestConvertible { + /// Returns a `URLRequest` or throws if an `Error` was encountered. + /// + /// - Returns: A `URLRequest`. + /// - Throws: Any error thrown while constructing the `URLRequest`. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The `URLRequest` returned by discarding any `Error` encountered. + public var urlRequest: URLRequest? { try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns `self`. + public func asURLRequest() throws -> URLRequest { self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `url`, `method`, and `headers`. + /// + /// - Parameters: + /// - url: The `URLConvertible` value. + /// - method: The `HTTPMethod`. + /// - headers: The `HTTPHeaders`, `nil` by default. + /// - Throws: Any error thrown while converting the `URLConvertible` to a `URL`. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + allHTTPHeaderFields = headers?.dictionary + } +} diff --git a/Pods/Alamofire/Source/URLEncodedFormEncoder.swift b/Pods/Alamofire/Source/URLEncodedFormEncoder.swift new file mode 100644 index 0000000..dcb5991 --- /dev/null +++ b/Pods/Alamofire/Source/URLEncodedFormEncoder.swift @@ -0,0 +1,1083 @@ +// +// URLEncodedFormEncoder.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// An object that encodes instances into URL-encoded query strings. +/// +/// `ArrayEncoding` can be used to configure how `Array` values are encoded. By default, the `.brackets` encoding is +/// used, encoding array values with brackets for each value. e.g `array[]=1&array[]=2`. +/// +/// `BoolEncoding` can be used to configure how `Bool` values are encoded. By default, the `.numeric` encoding is used, +/// encoding `true` as `1` and `false` as `0`. +/// +/// `DataEncoding` can be used to configure how `Data` values are encoded. By default, the `.deferredToData` encoding is +/// used, which encodes `Data` values using their default `Encodable` implementation. +/// +/// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` +/// encoding is used, which encodes `Date`s using their default `Encodable` implementation. +/// +/// `KeyEncoding` can be used to configure how keys are encoded. By default, the `.useDefaultKeys` encoding is used, +/// which encodes the keys directly from the `Encodable` implementation. +/// +/// `KeyPathEncoding` can be used to configure how paths within nested objects are encoded. By default, the `.brackets` +/// encoding is used, which encodes each sub-key in brackets. e.g. `parent[child][grandchild]=value`. +/// +/// `NilEncoding` can be used to configure how `nil` `Optional` values are encoded. By default, the `.dropKey` encoding +/// is used, which drops `nil` key / value pairs from the output entirely. +/// +/// `SpaceEncoding` can be used to configure how spaces are encoded. By default, the `.percentEscaped` encoding is used, +/// replacing spaces with `%20`. +/// +/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. +public final class URLEncodedFormEncoder { + /// Encoding to use for `Array` values. + public enum ArrayEncoding { + /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding. + case brackets + /// No brackets are appended to the key and the key is encoded as is. + case noBrackets + /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. + case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custom((_ key: String, _ index: Int) -> String) + + /// Encodes the key according to the encoding. + /// + /// - Parameters: + /// - key: The `key` to encode. + /// - index: When this enum instance is `.indexInBrackets`, the `index` to encode. + /// + /// - Returns: The encoded key. + func encode(_ key: String, atIndex index: Int) -> String { + switch self { + case .brackets: return "\(key)[]" + case .noBrackets: return key + case .indexInBrackets: return "\(key)[\(index)]" + case let .custom(encoding): return encoding(key, index) + } + } + } + + /// Encoding to use for `Bool` values. + public enum BoolEncoding { + /// Encodes `true` as `1`, `false` as `0`. + case numeric + /// Encodes `true` as "true", `false` as "false". This is the default encoding. + case literal + + /// Encodes the given `Bool` as a `String`. + /// + /// - Parameter value: The `Bool` to encode. + /// + /// - Returns: The encoded `String`. + func encode(_ value: Bool) -> String { + switch self { + case .numeric: return value ? "1" : "0" + case .literal: return value ? "true" : "false" + } + } + } + + /// Encoding to use for `Data` values. + public enum DataEncoding { + /// Defers encoding to the `Data` type. + case deferredToData + /// Encodes `Data` as a Base64-encoded string. This is the default encoding. + case base64 + /// Encode the `Data` as a custom value encoded by the given closure. + case custom((Data) throws -> String) + + /// Encodes `Data` according to the encoding. + /// + /// - Parameter data: The `Data` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its + /// `Encodable` implementation. + func encode(_ data: Data) throws -> String? { + switch self { + case .deferredToData: return nil + case .base64: return data.base64EncodedString() + case let .custom(encoding): return try encoding(data) + } + } + } + + /// Encoding to use for `Date` values. + public enum DateEncoding { + /// ISO8601 and RFC3339 formatter. + private static let iso8601Formatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter + }() + + /// Defers encoding to the `Date` type. This is the default encoding. + case deferredToDate + /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970. + case secondsSince1970 + /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970. + case millisecondsSince1970 + /// Encodes `Date`s according to the ISO8601 and RFC3339 standards. + case iso8601 + /// Encodes `Date`s using the given `DateFormatter`. + case formatted(DateFormatter) + /// Encodes `Date`s using the given closure. + case custom((Date) throws -> String) + + /// Encodes the date according to the encoding. + /// + /// - Parameter date: The `Date` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its + /// `Encodable` implementation. + func encode(_ date: Date) throws -> String? { + switch self { + case .deferredToDate: + return nil + case .secondsSince1970: + return String(date.timeIntervalSince1970) + case .millisecondsSince1970: + return String(date.timeIntervalSince1970 * 1000.0) + case .iso8601: + return DateEncoding.iso8601Formatter.string(from: date) + case let .formatted(formatter): + return formatter.string(from: date) + case let .custom(closure): + return try closure(date) + } + } + } + + /// Encoding to use for keys. + /// + /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128) + /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102). + public enum KeyEncoding { + /// Use the keys specified by each type. This is the default encoding. + case useDefaultKeys + /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key. + /// + /// Capital characters are determined by testing membership in + /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` + /// (Unicode General Categories Lu and Lt). + /// The conversion to lower case uses `Locale.system`, also known as + /// the ICU "root" locale. This means the result is consistent + /// regardless of the current user's locale and language preferences. + /// + /// Converting from camel case to snake case: + /// 1. Splits words at the boundary of lower-case to upper-case + /// 2. Inserts `_` between words + /// 3. Lowercases the entire string + /// 4. Preserves starting and ending `_`. + /// + /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. + /// + /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. + case convertToSnakeCase + /// Same as convertToSnakeCase, but using `-` instead of `_`. + /// For example `oneTwoThree` becomes `one-two-three`. + case convertToKebabCase + /// Capitalize the first letter only. + /// For example `oneTwoThree` becomes `OneTwoThree`. + case capitalized + /// Uppercase all letters. + /// For example `oneTwoThree` becomes `ONETWOTHREE`. + case uppercased + /// Lowercase all letters. + /// For example `oneTwoThree` becomes `onetwothree`. + case lowercased + /// A custom encoding using the provided closure. + case custom((String) -> String) + + func encode(_ key: String) -> String { + switch self { + case .useDefaultKeys: return key + case .convertToSnakeCase: return convertToSnakeCase(key) + case .convertToKebabCase: return convertToKebabCase(key) + case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst()) + case .uppercased: return key.uppercased() + case .lowercased: return key.lowercased() + case let .custom(encoding): return encoding(key) + } + } + + private func convertToSnakeCase(_ key: String) -> String { + convert(key, usingSeparator: "_") + } + + private func convertToKebabCase(_ key: String) -> String { + convert(key, usingSeparator: "-") + } + + private func convert(_ key: String, usingSeparator separator: String) -> String { + guard !key.isEmpty else { return key } + + var words: [Range] = [] + // The general idea of this algorithm is to split words on + // transition from lower to upper case, then on transition of >1 + // upper case characters to lowercase + // + // myProperty -> my_property + // myURLProperty -> my_url_property + // + // It is assumed, per Swift naming conventions, that the first character of the key is lowercase. + var wordStart = key.startIndex + var searchRange = key.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before + // the lower case character. + let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound) + words.append(upperCaseRange.lowerBound.. String + + /// Creates an instance with the encoding closure called for each sub-key in a key path. + /// + /// - Parameter encoding: Closure used to perform the encoding. + public init(encoding: @escaping (_ subkey: String) -> String) { + self.encoding = encoding + } + + func encodeKeyPath(_ keyPath: String) -> String { + encoding(keyPath) + } + } + + /// Encoding to use for `nil` values. + public struct NilEncoding { + /// Encodes `nil` by dropping the entire key / value pair. + public static let dropKey = NilEncoding { nil } + /// Encodes `nil` by dropping only the value. e.g. `value1=one&nilValue=&value2=two`. + public static let dropValue = NilEncoding { "" } + /// Encodes `nil` as `null`. + public static let null = NilEncoding { "null" } + + private let encoding: () -> String? + + /// Creates an instance with the encoding closure called for `nil` values. + /// + /// - Parameter encoding: Closure used to perform the encoding. + public init(encoding: @escaping () -> String?) { + self.encoding = encoding + } + + func encodeNil() -> String? { + encoding() + } + } + + /// Encoding to use for spaces. + public enum SpaceEncoding { + /// Encodes spaces using percent escaping (`%20`). + case percentEscaped + /// Encodes spaces as `+`. + case plusReplaced + + /// Encodes the string according to the encoding. + /// + /// - Parameter string: The `String` to encode. + /// + /// - Returns: The encoded `String`. + func encode(_ string: String) -> String { + switch self { + case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20") + case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+") + } + } + } + + /// `URLEncodedFormEncoder` error. + public enum Error: Swift.Error { + /// An invalid root object was created by the encoder. Only keyed values are valid. + case invalidRootObject(String) + + var localizedDescription: String { + switch self { + case let .invalidRootObject(object): + return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead." + } + } + } + + /// Whether or not to sort the encoded key value pairs. + /// + /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, + /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to + /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order. + public let alphabetizeKeyValuePairs: Bool + /// The `ArrayEncoding` to use. + public let arrayEncoding: ArrayEncoding + /// The `BoolEncoding` to use. + public let boolEncoding: BoolEncoding + /// THe `DataEncoding` to use. + public let dataEncoding: DataEncoding + /// The `DateEncoding` to use. + public let dateEncoding: DateEncoding + /// The `KeyEncoding` to use. + public let keyEncoding: KeyEncoding + /// The `KeyPathEncoding` to use. + public let keyPathEncoding: KeyPathEncoding + /// The `NilEncoding` to use. + public let nilEncoding: NilEncoding + /// The `SpaceEncoding` to use. + public let spaceEncoding: SpaceEncoding + /// The `CharacterSet` of allowed (non-escaped) characters. + public var allowedCharacters: CharacterSet + + /// Creates an instance from the supplied parameters. + /// + /// - Parameters: + /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default. + /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default. + /// - dataEncoding: The `DataEncoding` to use. `.base64` by default. + /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default. + /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default. + /// - nilEncoding: The `NilEncoding` to use. `.drop` by default. + /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default. + /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by + /// default. + public init(alphabetizeKeyValuePairs: Bool = true, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric, + dataEncoding: DataEncoding = .base64, + dateEncoding: DateEncoding = .deferredToDate, + keyEncoding: KeyEncoding = .useDefaultKeys, + keyPathEncoding: KeyPathEncoding = .brackets, + nilEncoding: NilEncoding = .dropKey, + spaceEncoding: SpaceEncoding = .percentEscaped, + allowedCharacters: CharacterSet = .afURLQueryAllowed) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.keyEncoding = keyEncoding + self.keyPathEncoding = keyPathEncoding + self.nilEncoding = nilEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func encode(_ value: Encodable) throws -> URLEncodedFormComponent { + let context = URLEncodedFormContext(.object([])) + let encoder = _URLEncodedFormEncoder(context: context, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + try value.encode(to: encoder) + + return context.component + } + + /// Encodes the `value` as a URL form encoded `String`. + /// + /// - Parameter value: The `Encodable` value.` + /// + /// - Returns: The encoded `String`. + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: Encodable) throws -> String { + let component: URLEncodedFormComponent = try encode(value) + + guard case let .object(object) = component else { + throw Error.invalidRootObject("\(component)") + } + + let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs, + arrayEncoding: arrayEncoding, + keyEncoding: keyEncoding, + keyPathEncoding: keyPathEncoding, + spaceEncoding: spaceEncoding, + allowedCharacters: allowedCharacters) + let query = serializer.serialize(object) + + return query + } + + /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the + /// `.utf8` data. + /// + /// - Parameter value: The `Encodable` value. + /// + /// - Returns: The encoded `Data`. + /// + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: Encodable) throws -> Data { + let string: String = try encode(value) + + return Data(string.utf8) + } +} + +final class _URLEncodedFormEncoder { + var codingPath: [CodingKey] + // Returns an empty dictionary, as this encoder doesn't support userInfo. + var userInfo: [CodingUserInfoKey: Any] { [:] } + + let context: URLEncodedFormContext + + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey] = [], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } +} + +extension _URLEncodedFormEncoder: Encoder { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { + _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func singleValueContainer() -> SingleValueEncodingContainer { + _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +final class URLEncodedFormContext { + var component: URLEncodedFormComponent + + init(_ component: URLEncodedFormComponent) { + self.component = component + } +} + +enum URLEncodedFormComponent { + typealias Object = [(key: String, value: URLEncodedFormComponent)] + + case string(String) + case array([URLEncodedFormComponent]) + case object(Object) + + /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible. + var array: [URLEncodedFormComponent]? { + switch self { + case let .array(array): return array + default: return nil + } + } + + /// Converts self to an `Object` or returns `nil` if not convertible. + var object: Object? { + switch self { + case let .object(object): return object + default: return nil + } + } + + /// Sets self to the supplied value at a given path. + /// + /// data.set(to: "hello", at: ["path", "to", "value"]) + /// + /// - parameters: + /// - value: Value of `Self` to set at the supplied path. + /// - path: `CodingKey` path to update with the supplied value. + public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) { + set(&self, to: value, at: path) + } + + /// Recursive backing method to `set(to:at:)`. + private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) { + guard !path.isEmpty else { + context = value + return + } + + let end = path[0] + var child: URLEncodedFormComponent + switch path.count { + case 1: + child = value + case 2...: + if let index = end.intValue { + let array = context.array ?? [] + if array.count > index { + child = array[index] + } else { + child = .array([]) + } + set(&child, to: value, at: Array(path[1...])) + } else { + child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init()) + set(&child, to: value, at: Array(path[1...])) + } + default: fatalError("Unreachable") + } + + if let index = end.intValue { + if var array = context.array { + if array.count > index { + array[index] = child + } else { + array.append(child) + } + context = .array(array) + } else { + context = .array([child]) + } + } else { + if var object = context.object { + if let index = object.firstIndex(where: { $0.key == end.stringValue }) { + object[index] = (key: end.stringValue, value: child) + } else { + object.append((key: end.stringValue, value: child)) + } + context = .object(object) + } else { + context = .object([(key: end.stringValue, value: child)]) + } + } + } +} + +struct AnyCodingKey: CodingKey, Hashable { + let stringValue: String + let intValue: Int? + + init?(stringValue: String) { + self.stringValue = stringValue + intValue = nil + } + + init?(intValue: Int) { + stringValue = "\(intValue)" + self.intValue = intValue + } + + init(_ base: Key) where Key: CodingKey { + if let intValue = base.intValue { + self.init(intValue: intValue)! + } else { + self.init(stringValue: base.stringValue)! + } + } +} + +extension _URLEncodedFormEncoder { + final class KeyedContainer where Key: CodingKey { + var codingPath: [CodingKey] + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + + private func nestedCodingPath(for key: CodingKey) -> [CodingKey] { + codingPath + [key] + } + } +} + +extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol { + func encodeNil(forKey key: Key) throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue, forKey: key) + } + + func encode(_ value: T, forKey key: Key) throws where T: Encodable { + var container = nestedSingleValueEncoder(for: key) + try container.encode(value) + } + + func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer { + let container = _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return container + } + + func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { + let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return container + } + + func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return KeyedEncodingContainer(container) + } + + func superEncoder() -> Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func superEncoder(forKey key: Key) -> Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +extension _URLEncodedFormEncoder { + final class SingleValueContainer { + var codingPath: [CodingKey] + + private var canEncodeNewValue = true + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + + private func checkCanEncode(value: Any?) throws { + guard canEncodeNewValue else { + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "Attempt to encode value through single value container when previously value already encoded.") + throw EncodingError.invalidValue(value as Any, context) + } + } + } +} + +extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer { + func encodeNil() throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue) + } + + func encode(_ value: Bool) throws { + try encode(value, as: String(boolEncoding.encode(value))) + } + + func encode(_ value: String) throws { + try encode(value, as: value) + } + + func encode(_ value: Double) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Float) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int64) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt64) throws { + try encode(value, as: String(value)) + } + + private func encode(_ value: T, as string: String) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + context.component.set(to: .string(string), at: codingPath) + } + + func encode(_ value: T) throws where T: Encodable { + switch value { + case let date as Date: + guard let string = try dateEncoding.encode(date) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + case let data as Data: + guard let string = try dataEncoding.encode(data) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + case let decimal as Decimal: + // Decimal's `Encodable` implementation returns an object, not a single value, so override it. + try encode(value, as: String(describing: decimal)) + default: + try attemptToEncode(value) + } + } + + private func attemptToEncode(_ value: T) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + let encoder = _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + try value.encode(to: encoder) + } +} + +extension _URLEncodedFormEncoder { + final class UnkeyedContainer { + var codingPath: [CodingKey] + + var count = 0 + var nestedCodingPath: [CodingKey] { + codingPath + [AnyCodingKey(intValue: count)!] + } + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + } +} + +extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer { + func encodeNil() throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue) + } + + func encode(_ value: T) throws where T: Encodable { + var container = nestedSingleValueContainer() + try container.encode(value) + } + + func nestedSingleValueContainer() -> SingleValueEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey: CodingKey { + defer { count += 1 } + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return KeyedEncodingContainer(container) + } + + func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func superEncoder() -> Encoder { + defer { count += 1 } + + return _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +final class URLEncodedFormSerializer { + private let alphabetizeKeyValuePairs: Bool + private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding + private let keyEncoding: URLEncodedFormEncoder.KeyEncoding + private let keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding + private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding + private let allowedCharacters: CharacterSet + + init(alphabetizeKeyValuePairs: Bool, + arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, + keyEncoding: URLEncodedFormEncoder.KeyEncoding, + keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding, + spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, + allowedCharacters: CharacterSet) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.keyEncoding = keyEncoding + self.keyPathEncoding = keyPathEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func serialize(_ object: URLEncodedFormComponent.Object) -> String { + var output: [String] = [] + for (key, component) in object { + let value = serialize(component, forKey: key) + output.append(value) + } + output = alphabetizeKeyValuePairs ? output.sorted() : output + + return output.joinedWithAmpersands() + } + + func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { + switch component { + case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))" + case let .array(array): return serialize(array, forKey: key) + case let .object(object): return serialize(object, forKey: key) + } + } + + func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String { + var segments: [String] = object.map { subKey, value in + let keyPath = keyPathEncoding.encodeKeyPath(subKey) + return serialize(value, forKey: key + keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { + var segments: [String] = array.enumerated().map { index, component in + let keyPath = arrayEncoding.encode(key, atIndex: index) + return serialize(component, forKey: keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func escape(_ query: String) -> String { + var allowedCharactersWithSpace = allowedCharacters + allowedCharactersWithSpace.insert(charactersIn: " ") + let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query + let spaceEncodedQuery = spaceEncoding.encode(escapedQuery) + + return spaceEncodedQuery + } +} + +extension Array where Element == String { + func joinedWithAmpersands() -> String { + joined(separator: "&") + } +} + +extension CharacterSet { + /// Creates a CharacterSet from RFC 3986 allowed characters. + /// + /// RFC 3986 states that the following characters are "reserved" characters. + /// + /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// + /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + /// should be percent-escaped in the query string. + public static let afURLQueryAllowed: CharacterSet = { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters) + }() +} diff --git a/Pods/Alamofire/Source/URLRequest+Alamofire.swift b/Pods/Alamofire/Source/URLRequest+Alamofire.swift new file mode 100644 index 0000000..ab72fb5 --- /dev/null +++ b/Pods/Alamofire/Source/URLRequest+Alamofire.swift @@ -0,0 +1,39 @@ +// +// URLRequest+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension URLRequest { + /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type. + public var method: HTTPMethod? { + get { httpMethod.map(HTTPMethod.init) } + set { httpMethod = newValue?.rawValue } + } + + public func validate() throws { + if method == .get, let bodyData = httpBody { + throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData)) + } + } +} diff --git a/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift b/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift new file mode 100644 index 0000000..292a8fe --- /dev/null +++ b/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift @@ -0,0 +1,46 @@ +// +// URLSessionConfiguration+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension URLSessionConfiguration: AlamofireExtended {} +extension AlamofireExtension where ExtendedType: URLSessionConfiguration { + /// Alamofire's default configuration. Same as `URLSessionConfiguration.default` but adds Alamofire default + /// `Accept-Language`, `Accept-Encoding`, and `User-Agent` headers. + public static var `default`: URLSessionConfiguration { + let configuration = URLSessionConfiguration.default + configuration.headers = .default + + return configuration + } + + /// `.ephemeral` configuration with Alamofire's default `Accept-Language`, `Accept-Encoding`, and `User-Agent` + /// headers. + public static var ephemeral: URLSessionConfiguration { + let configuration = URLSessionConfiguration.ephemeral + configuration.headers = .default + + return configuration + } +} diff --git a/Pods/Alamofire/Source/Validation.swift b/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..2cf23fb --- /dev/null +++ b/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,302 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// Used to represent whether a validation succeeded or failed. + public typealias ValidationResult = Result + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] + + return split.components(separatedBy: "/") + }() + + if let type = components.first, let subtype = components.last { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(_ mime: MIMEType) -> Bool { + switch (type, subtype) { + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: Range { 200..<300 } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate(statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int { + if acceptableStatusCodes.contains(response.statusCode) { + return .success(()) + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate(contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String { + guard let data = data, !data.isEmpty else { return .success(()) } + + return validate(contentType: acceptableContentTypes, response: response) + } + + fileprivate func validate(contentType acceptableContentTypes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == String { + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success(()) + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: acceptableContentTypes.sorted()) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success(()) + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: acceptableContentTypes.sorted(), + responseContentType: responseContentType) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + validate { [unowned self] _, response, _ in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + validate { [unowned self] _, response, data in + self.validate(contentType: acceptableContentTypes(), response: response, data: data) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + let contentTypes: () -> [String] = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} + +extension DataStreamRequest { + /// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the + /// request was valid. + public typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + validate { [unowned self] _, response in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + validate { [unowned self] _, response in + self.validate(contentType: acceptableContentTypes(), response: response) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Returns: The instance. + @discardableResult + public func validate() -> Self { + let contentTypes: () -> [String] = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = (_ request: URLRequest?, + _ response: HTTPURLResponse, + _ fileURL: URL?) + -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + validate { [unowned self] _, response, _ in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + validate { [unowned self] _, response, fileURL in + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes(), response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + let contentTypes = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000..eea3d86 --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,20 @@ +PODS: + - Alamofire (5.8.0) + - SwiftyJSON (5.0.1) + +DEPENDENCIES: + - Alamofire (~> 5.2) + - SwiftyJSON (~> 5.0) + +SPEC REPOS: + trunk: + - Alamofire + - SwiftyJSON + +SPEC CHECKSUMS: + Alamofire: 0e92e751b3e9e66d7982db43919d01f313b8eb91 + SwiftyJSON: 2f33a42c6fbc52764d96f13368585094bfd8aa5e + +PODFILE CHECKSUM: 5e61afd8812c9454d63f39ebb91e91b56a2d87b4 + +COCOAPODS: 1.12.1 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..9f704b8 --- /dev/null +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,939 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 55; + objects = { + +/* Begin PBXBuildFile section */ + 04A8430BFC619C34E5F4D3878D094380 /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80E500F0F145B765C8790D12014D5762 /* CachedResponseHandler.swift */; }; + 079F0820555C5B86C9FBD5EC6344137F /* Protected.swift in Sources */ = {isa = PBXBuildFile; fileRef = 136D69898625D4CE7169E6FC93CC5B3B /* Protected.swift */; }; + 11CCD832BD537718892C6A216A38490A /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D31DB1760C5695EE9B439DD62108846 /* URLRequest+Alamofire.swift */; }; + 197457852FC83E905248660B0F930452 /* AuthenticationInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DFBA534907823891A87B63D3CF1314 /* AuthenticationInterceptor.swift */; }; + 1AFD57838680DF58184FF94D14C7F3FF /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1895CFA307AEA25985B669A053E29D /* RequestInterceptor.swift */; }; + 282FCD4EA8B05830E9108690B8CD336B /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1121250A1C77343D21882F241A51679 /* Session.swift */; }; + 2F89511EA6BE9B4E192272E9060674A7 /* Pods-DiaryApp-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 45EC6EEE1BE9C1F9BCA56EDF3650F910 /* Pods-DiaryApp-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 320C0D7A88AA812EFB20016BA1F5D7AE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A11577B72AA4553089ABB084F728B215 /* AFError.swift */; }; + 325CCDB295FFA016638075B5D2CEDD5C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + 385BC4B250B6A6DB8AAAEA77D5B7A46F /* Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3078E923BB50C0CBFFAFCBF33A1D5A7B /* Combine.swift */; }; + 3A59D8FBAF9A54906E3644AC80465AFB /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD82A81AA05DD999D73E18F84E60D42E /* Notifications.swift */; }; + 3FA127A261BB563409868A0DC21807B2 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C199D0E86CE0A8AAD5CF013719B559E /* ResponseSerialization.swift */; }; + 482B74C0548970BB9C095E2D8530E421 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE95150D59D402944D22D64270CC596 /* ParameterEncoding.swift */; }; + 529173B31EFCD3D199E79866AFBEC86C /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBCEFF14802034F762E9D9AEBCE2911E /* HTTPHeaders.swift */; }; + 5B92A66A66BD639411C3D839A0F87B0C /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B697EA074391CA1E5281F6C42FEC222 /* Request.swift */; }; + 5E363952D297EEBFDC960AF93D5C1090 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + 5FA526557719FDBE81B1974B113CF600 /* SwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B5D675CC25C04904109F8207299DFED0 /* SwiftyJSON-dummy.m */; }; + 643A7AFFB7AEB70B2B9B7E0926055023 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE519701FB770D29ACC8A8D8231EDE60 /* RetryPolicy.swift */; }; + 67B10FEAA3B7E5387D20E76B1085E94D /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6B65762324B6D2294DFE96F6546298A /* URLSessionConfiguration+Alamofire.swift */; }; + 6CB17C9753A4EAD270D129B366F9FEC5 /* Pods-DiaryApp-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D73D7B0EEC2266B6A2CB0C66355A76FA /* Pods-DiaryApp-dummy.m */; }; + 732C29255F73EF3D83D49BD4F8FEAA8F /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5190045555EB63C0CE433336B62F1EFE /* MultipartUpload.swift */; }; + 737747B9A98257DB58112C3A23686669 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A6AB9F7BED5CEAD6061F8E84B98A9AA /* MultipartFormData.swift */; }; + 77AB6AF4BFC6DE016DA7C057B5799C84 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55AC0B3E5EFE171CF2531104772E1A19 /* ServerTrustEvaluation.swift */; }; + 78B1DD1219182494A6AFAD26AAB20AA6 /* Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30A33AEB1ECAC7269C4B74174CF55AEC /* Concurrency.swift */; }; + 7D64BC3E6CAA4AB54EAC0AAADE93F578 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = D51D195FCE9098E02B61633008659F56 /* OperationQueue+Alamofire.swift */; }; + 81E6A0FF7F286008345ECFA3A2103FA8 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30C7AB0C34B2F81D314EF29DB2479728 /* Alamofire.swift */; }; + 82FD97FBBEFE51E2D3B434AF4954FC93 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC533D2C2706EF4D05C39CB8608073C0 /* EventMonitor.swift */; }; + 8E698F134A953250D5834C8B83CDAD34 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA9F3FE74C26CA6150E487EC73B4C6CF /* DispatchQueue+Alamofire.swift */; }; + 8E85763AE29BEF0A46EE875B8F069E8E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + A115142039C23F91827E6961CC479F05 /* SwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = FC6755DCDD561DDF29441E07C4A243D9 /* SwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A3CEE8324948497036C4E123B21CBC59 /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7B2B42AD4CEF88F4CCC378D6688B7CC /* SwiftyJSON.swift */; }; + A523488C60BF961290D0B1ABB9ADACEC /* RequestCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B55A86AD74401D249D77D562AB87E21 /* RequestCompression.swift */; }; + AA721ECC2B36AFB7D9FE70C83E6D63F9 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED8C6118D389689E913B1D9A16AE20E4 /* Response.swift */; }; + B17D933C8F8BC6A4F91AA620D7D7A870 /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75F57608866ED7F1B0AECAAD3E8D1480 /* ParameterEncoder.swift */; }; + BAB17A1C6CAD14B3788973EAF8466C93 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC95874ACDA952F59C68A1E198C45E6D /* NetworkReachabilityManager.swift */; }; + C04739CBCEE445B66192BFA708655EDF /* StringEncoding+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 501AA2DD4A61A385DAAA2B5D51AFFAA4 /* StringEncoding+Alamofire.swift */; }; + C8269B42DED12AB1F275648D0BD32E45 /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A08D0CF6B90AA621D958AD039F7F545 /* URLEncodedFormEncoder.swift */; }; + D0560E8E2E5EB407B5D8E0381BF453FA /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AD70DF61CE4EBB95681B2CB1D677753 /* URLConvertible+URLRequestConvertible.swift */; }; + D09FBBADAF7C5C757AA5AB5DFE54BD25 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A99447FC5354951E2B4EE89B31510C70 /* Alamofire-dummy.m */; }; + D368E6F70C5E6998548A72E65F92432D /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74391BDD82CE581AF8EEB0CA18A048B1 /* Validation.swift */; }; + D7BCBE1EB4A638403C265CE2199EFF1B /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D3D57353834825F7B52B816066B7789 /* CFNetwork.framework */; }; + E6251F02EE12804D1B66AE32E716E664 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18D1E41CFC45E859349C7E0368EE9DF1 /* SessionDelegate.swift */; }; + ECE6F23823454A8FDB3F97CE1A7CD182 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3BE26BD10803C330C2253D9B9BB3998 /* RedirectHandler.swift */; }; + ECF2F956B37A4C28B228BC291A57AD6E /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9D1F9ED142F768BE9209BE2650C151C /* RequestTaskMap.swift */; }; + F038D81F7ABAA15CF03246AD4BF334F7 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A08F78C71A4CC559CCAC71F103EB26F /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F2415AE8678DE2698B7AD7D88B1A5C0F /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91302FA166B81FAAA21B862AE8C809AE /* AlamofireExtended.swift */; }; + F66CC47AD425C8D57BD149AFD09C2AFE /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6122F7837BC3657FB979A4B70F075644 /* HTTPMethod.swift */; }; + F6E94E8EE1CE35F49B9091BE8748587B /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBF6EFE675654E66327281E6A7801356 /* Result+Alamofire.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 25EE24530F5DE77C2138C3C848364587 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + 9A946D9941B776AE87D1C60FE7A1CA37 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = D118A6A04828FD3CDA8640CD2B6796D2; + remoteInfo = SwiftyJSON; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 08D72F04F55B8DAC1106A210D8946EC8 /* SwiftyJSON.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.debug.xcconfig; sourceTree = ""; }; + 0A08F78C71A4CC559CCAC71F103EB26F /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 136D69898625D4CE7169E6FC93CC5B3B /* Protected.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Protected.swift; path = Source/Protected.swift; sourceTree = ""; }; + 14AAF947BF52795074BC4C048D87CBF2 /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; + 18D1E41CFC45E859349C7E0368EE9DF1 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + 1BF9CC04B4FD0CD457FA84A78FF7568A /* Pods-DiaryApp.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-DiaryApp.release.xcconfig"; sourceTree = ""; }; + 1C199D0E86CE0A8AAD5CF013719B559E /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 2A6AB9F7BED5CEAD6061F8E84B98A9AA /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 2CE95150D59D402944D22D64270CC596 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 2E0ECA398B6DC3827602F405677B2C28 /* SwiftyJSON.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.release.xcconfig; sourceTree = ""; }; + 3078E923BB50C0CBFFAFCBF33A1D5A7B /* Combine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Combine.swift; path = Source/Combine.swift; sourceTree = ""; }; + 30A33AEB1ECAC7269C4B74174CF55AEC /* Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concurrency.swift; path = Source/Concurrency.swift; sourceTree = ""; }; + 30C7AB0C34B2F81D314EF29DB2479728 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 3B697EA074391CA1E5281F6C42FEC222 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 40A2EBF5257D2162748FB0D6BAAC62BE /* Alamofire.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.release.xcconfig; sourceTree = ""; }; + 45EC6EEE1BE9C1F9BCA56EDF3650F910 /* Pods-DiaryApp-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-DiaryApp-umbrella.h"; sourceTree = ""; }; + 4B55A86AD74401D249D77D562AB87E21 /* RequestCompression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestCompression.swift; path = Source/RequestCompression.swift; sourceTree = ""; }; + 501AA2DD4A61A385DAAA2B5D51AFFAA4 /* StringEncoding+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "StringEncoding+Alamofire.swift"; path = "Source/StringEncoding+Alamofire.swift"; sourceTree = ""; }; + 5190045555EB63C0CE433336B62F1EFE /* MultipartUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartUpload.swift; path = Source/MultipartUpload.swift; sourceTree = ""; }; + 528324114E67C28E10AD71BF531E9A0E /* SwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SwiftyJSON.modulemap; sourceTree = ""; }; + 55AC0B3E5EFE171CF2531104772E1A19 /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustEvaluation.swift; path = Source/ServerTrustEvaluation.swift; sourceTree = ""; }; + 571EB0F4A1903700A7631F3C8D497307 /* Pods-DiaryApp-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-DiaryApp-acknowledgements.plist"; sourceTree = ""; }; + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5F9C2818D0015901A6056D4A5F086DD3 /* Pods-DiaryApp */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-DiaryApp"; path = Pods_DiaryApp.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6122F7837BC3657FB979A4B70F075644 /* HTTPMethod.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPMethod.swift; path = Source/HTTPMethod.swift; sourceTree = ""; }; + 74391BDD82CE581AF8EEB0CA18A048B1 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 75F57608866ED7F1B0AECAAD3E8D1480 /* ParameterEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoder.swift; path = Source/ParameterEncoder.swift; sourceTree = ""; }; + 75F5B7EF640D4B1A9C333EADBD359F47 /* SwiftyJSON-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SwiftyJSON-Info.plist"; sourceTree = ""; }; + 7A08D0CF6B90AA621D958AD039F7F545 /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLEncodedFormEncoder.swift; path = Source/URLEncodedFormEncoder.swift; sourceTree = ""; }; + 7A1895CFA307AEA25985B669A053E29D /* RequestInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestInterceptor.swift; path = Source/RequestInterceptor.swift; sourceTree = ""; }; + 80E500F0F145B765C8790D12014D5762 /* CachedResponseHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CachedResponseHandler.swift; path = Source/CachedResponseHandler.swift; sourceTree = ""; }; + 8AD70DF61CE4EBB95681B2CB1D677753 /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLConvertible+URLRequestConvertible.swift"; path = "Source/URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; + 8D3D57353834825F7B52B816066B7789 /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + 91302FA166B81FAAA21B862AE8C809AE /* AlamofireExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireExtended.swift; path = Source/AlamofireExtended.swift; sourceTree = ""; }; + 9D31DB1760C5695EE9B439DD62108846 /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Alamofire.swift"; path = "Source/URLRequest+Alamofire.swift"; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9DEFECFEAF0C978DF44C124E0BD594E7 /* SwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-prefix.pch"; sourceTree = ""; }; + A11577B72AA4553089ABB084F728B215 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + A15528F1A1F70BECF6479F15B930BB57 /* Pods-DiaryApp-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-DiaryApp-frameworks.sh"; sourceTree = ""; }; + A249A2B83CC3ECEF2DA592160DFE283D /* Pods-DiaryApp.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-DiaryApp.debug.xcconfig"; sourceTree = ""; }; + A7B2B42AD4CEF88F4CCC378D6688B7CC /* SwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftyJSON.swift; path = Source/SwiftyJSON/SwiftyJSON.swift; sourceTree = ""; }; + A99447FC5354951E2B4EE89B31510C70 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + B4E635F2092C404FC9100DA1B41920FA /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + B5D675CC25C04904109F8207299DFED0 /* SwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftyJSON-dummy.m"; sourceTree = ""; }; + BA9F3FE74C26CA6150E487EC73B4C6CF /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + BBCEFF14802034F762E9D9AEBCE2911E /* HTTPHeaders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHeaders.swift; path = Source/HTTPHeaders.swift; sourceTree = ""; }; + C0DFBA534907823891A87B63D3CF1314 /* AuthenticationInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AuthenticationInterceptor.swift; path = Source/AuthenticationInterceptor.swift; sourceTree = ""; }; + C77EAAD4714B2D83B1C0661732B06E6A /* Pods-DiaryApp.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-DiaryApp.modulemap"; sourceTree = ""; }; + CB489F9A2BACE59A9F683A85F52505C3 /* Pods-DiaryApp-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-DiaryApp-acknowledgements.markdown"; sourceTree = ""; }; + CC533D2C2706EF4D05C39CB8608073C0 /* EventMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventMonitor.swift; path = Source/EventMonitor.swift; sourceTree = ""; }; + CC95874ACDA952F59C68A1E198C45E6D /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + CD79008838AE61E32FFD1716929AC2F1 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + D51D195FCE9098E02B61633008659F56 /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "OperationQueue+Alamofire.swift"; path = "Source/OperationQueue+Alamofire.swift"; sourceTree = ""; }; + D73D7B0EEC2266B6A2CB0C66355A76FA /* Pods-DiaryApp-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-DiaryApp-dummy.m"; sourceTree = ""; }; + D9D1F9ED142F768BE9209BE2650C151C /* RequestTaskMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTaskMap.swift; path = Source/RequestTaskMap.swift; sourceTree = ""; }; + DBF6EFE675654E66327281E6A7801356 /* Result+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Result+Alamofire.swift"; path = "Source/Result+Alamofire.swift"; sourceTree = ""; }; + DE519701FB770D29ACC8A8D8231EDE60 /* RetryPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryPolicy.swift; path = Source/RetryPolicy.swift; sourceTree = ""; }; + E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SwiftyJSON; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E3BE26BD10803C330C2253D9B9BB3998 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Source/RedirectHandler.swift; sourceTree = ""; }; + ED527FF867A54B900D1EA2E8F4AD4E2D /* Alamofire.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.debug.xcconfig; sourceTree = ""; }; + ED8C6118D389689E913B1D9A16AE20E4 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + F1121250A1C77343D21882F241A51679 /* Session.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Session.swift; path = Source/Session.swift; sourceTree = ""; }; + F6B65762324B6D2294DFE96F6546298A /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSessionConfiguration+Alamofire.swift"; path = "Source/URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; + FAF0D15D79312C1EC4B0AF3B4C81C1A3 /* Pods-DiaryApp-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-DiaryApp-Info.plist"; sourceTree = ""; }; + FC6755DCDD561DDF29441E07C4A243D9 /* SwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-umbrella.h"; sourceTree = ""; }; + FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + FD82A81AA05DD999D73E18F84E60D42E /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 3977393A21672F0FBC6F1193739E0D15 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 325CCDB295FFA016638075B5D2CEDD5C /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5BF6E64D3157435E5797A5278584A4DC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D7BCBE1EB4A638403C265CE2199EFF1B /* CFNetwork.framework in Frameworks */, + 8E85763AE29BEF0A46EE875B8F069E8E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FBF275D03B0C8D171A97F34D1C197333 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 5E363952D297EEBFDC960AF93D5C1090 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 61C8CC330A5CA84DA2F5F1D32AB07069 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 343C4D5B9441A9C8A9F89904AABAABC2 /* Support Files */ = { + isa = PBXGroup; + children = ( + CD79008838AE61E32FFD1716929AC2F1 /* Alamofire.modulemap */, + A99447FC5354951E2B4EE89B31510C70 /* Alamofire-dummy.m */, + 14AAF947BF52795074BC4C048D87CBF2 /* Alamofire-Info.plist */, + B4E635F2092C404FC9100DA1B41920FA /* Alamofire-prefix.pch */, + 0A08F78C71A4CC559CCAC71F103EB26F /* Alamofire-umbrella.h */, + ED527FF867A54B900D1EA2E8F4AD4E2D /* Alamofire.debug.xcconfig */, + 40A2EBF5257D2162748FB0D6BAAC62BE /* Alamofire.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 3B5B2CDDC9ACCECC65D4DE3D945692E1 /* SwiftyJSON */ = { + isa = PBXGroup; + children = ( + A7B2B42AD4CEF88F4CCC378D6688B7CC /* SwiftyJSON.swift */, + CAEE96DC76CF535AA181B64994201BD7 /* Support Files */, + ); + name = SwiftyJSON; + path = SwiftyJSON; + sourceTree = ""; + }; + 4AFF7588B551EF7D5C39DD2A317F5DD2 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 6F944C129BBA621F70B917C4A53D1419 /* Pods-DiaryApp */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 61C8CC330A5CA84DA2F5F1D32AB07069 /* iOS */ = { + isa = PBXGroup; + children = ( + 8D3D57353834825F7B52B816066B7789 /* CFNetwork.framework */, + FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 6F944C129BBA621F70B917C4A53D1419 /* Pods-DiaryApp */ = { + isa = PBXGroup; + children = ( + C77EAAD4714B2D83B1C0661732B06E6A /* Pods-DiaryApp.modulemap */, + CB489F9A2BACE59A9F683A85F52505C3 /* Pods-DiaryApp-acknowledgements.markdown */, + 571EB0F4A1903700A7631F3C8D497307 /* Pods-DiaryApp-acknowledgements.plist */, + D73D7B0EEC2266B6A2CB0C66355A76FA /* Pods-DiaryApp-dummy.m */, + A15528F1A1F70BECF6479F15B930BB57 /* Pods-DiaryApp-frameworks.sh */, + FAF0D15D79312C1EC4B0AF3B4C81C1A3 /* Pods-DiaryApp-Info.plist */, + 45EC6EEE1BE9C1F9BCA56EDF3650F910 /* Pods-DiaryApp-umbrella.h */, + A249A2B83CC3ECEF2DA592160DFE283D /* Pods-DiaryApp.debug.xcconfig */, + 1BF9CC04B4FD0CD457FA84A78FF7568A /* Pods-DiaryApp.release.xcconfig */, + ); + name = "Pods-DiaryApp"; + path = "Target Support Files/Pods-DiaryApp"; + sourceTree = ""; + }; + 8F75D8B612FBB879D9C90143AFCEFF25 /* Products */ = { + isa = PBXGroup; + children = ( + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */, + 5F9C2818D0015901A6056D4A5F086DD3 /* Pods-DiaryApp */, + E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON */, + ); + name = Products; + sourceTree = ""; + }; + A432C0D0F76CDD71F8C45F1970C7EA89 /* Pods */ = { + isa = PBXGroup; + children = ( + E866D9E518011326A7ABF952D1B92E1A /* Alamofire */, + 3B5B2CDDC9ACCECC65D4DE3D945692E1 /* SwiftyJSON */, + ); + name = Pods; + sourceTree = ""; + }; + CAEE96DC76CF535AA181B64994201BD7 /* Support Files */ = { + isa = PBXGroup; + children = ( + 528324114E67C28E10AD71BF531E9A0E /* SwiftyJSON.modulemap */, + B5D675CC25C04904109F8207299DFED0 /* SwiftyJSON-dummy.m */, + 75F5B7EF640D4B1A9C333EADBD359F47 /* SwiftyJSON-Info.plist */, + 9DEFECFEAF0C978DF44C124E0BD594E7 /* SwiftyJSON-prefix.pch */, + FC6755DCDD561DDF29441E07C4A243D9 /* SwiftyJSON-umbrella.h */, + 08D72F04F55B8DAC1106A210D8946EC8 /* SwiftyJSON.debug.xcconfig */, + 2E0ECA398B6DC3827602F405677B2C28 /* SwiftyJSON.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/SwiftyJSON"; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */, + A432C0D0F76CDD71F8C45F1970C7EA89 /* Pods */, + 8F75D8B612FBB879D9C90143AFCEFF25 /* Products */, + 4AFF7588B551EF7D5C39DD2A317F5DD2 /* Targets Support Files */, + ); + sourceTree = ""; + }; + E866D9E518011326A7ABF952D1B92E1A /* Alamofire */ = { + isa = PBXGroup; + children = ( + A11577B72AA4553089ABB084F728B215 /* AFError.swift */, + 30C7AB0C34B2F81D314EF29DB2479728 /* Alamofire.swift */, + 91302FA166B81FAAA21B862AE8C809AE /* AlamofireExtended.swift */, + C0DFBA534907823891A87B63D3CF1314 /* AuthenticationInterceptor.swift */, + 80E500F0F145B765C8790D12014D5762 /* CachedResponseHandler.swift */, + 3078E923BB50C0CBFFAFCBF33A1D5A7B /* Combine.swift */, + 30A33AEB1ECAC7269C4B74174CF55AEC /* Concurrency.swift */, + BA9F3FE74C26CA6150E487EC73B4C6CF /* DispatchQueue+Alamofire.swift */, + CC533D2C2706EF4D05C39CB8608073C0 /* EventMonitor.swift */, + BBCEFF14802034F762E9D9AEBCE2911E /* HTTPHeaders.swift */, + 6122F7837BC3657FB979A4B70F075644 /* HTTPMethod.swift */, + 2A6AB9F7BED5CEAD6061F8E84B98A9AA /* MultipartFormData.swift */, + 5190045555EB63C0CE433336B62F1EFE /* MultipartUpload.swift */, + CC95874ACDA952F59C68A1E198C45E6D /* NetworkReachabilityManager.swift */, + FD82A81AA05DD999D73E18F84E60D42E /* Notifications.swift */, + D51D195FCE9098E02B61633008659F56 /* OperationQueue+Alamofire.swift */, + 75F57608866ED7F1B0AECAAD3E8D1480 /* ParameterEncoder.swift */, + 2CE95150D59D402944D22D64270CC596 /* ParameterEncoding.swift */, + 136D69898625D4CE7169E6FC93CC5B3B /* Protected.swift */, + E3BE26BD10803C330C2253D9B9BB3998 /* RedirectHandler.swift */, + 3B697EA074391CA1E5281F6C42FEC222 /* Request.swift */, + 4B55A86AD74401D249D77D562AB87E21 /* RequestCompression.swift */, + 7A1895CFA307AEA25985B669A053E29D /* RequestInterceptor.swift */, + D9D1F9ED142F768BE9209BE2650C151C /* RequestTaskMap.swift */, + ED8C6118D389689E913B1D9A16AE20E4 /* Response.swift */, + 1C199D0E86CE0A8AAD5CF013719B559E /* ResponseSerialization.swift */, + DBF6EFE675654E66327281E6A7801356 /* Result+Alamofire.swift */, + DE519701FB770D29ACC8A8D8231EDE60 /* RetryPolicy.swift */, + 55AC0B3E5EFE171CF2531104772E1A19 /* ServerTrustEvaluation.swift */, + F1121250A1C77343D21882F241A51679 /* Session.swift */, + 18D1E41CFC45E859349C7E0368EE9DF1 /* SessionDelegate.swift */, + 501AA2DD4A61A385DAAA2B5D51AFFAA4 /* StringEncoding+Alamofire.swift */, + 8AD70DF61CE4EBB95681B2CB1D677753 /* URLConvertible+URLRequestConvertible.swift */, + 7A08D0CF6B90AA621D958AD039F7F545 /* URLEncodedFormEncoder.swift */, + 9D31DB1760C5695EE9B439DD62108846 /* URLRequest+Alamofire.swift */, + F6B65762324B6D2294DFE96F6546298A /* URLSessionConfiguration+Alamofire.swift */, + 74391BDD82CE581AF8EEB0CA18A048B1 /* Validation.swift */, + 343C4D5B9441A9C8A9F89904AABAABC2 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 37AF420EAACFD30FC53913AC89710C00 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 2F89511EA6BE9B4E192272E9060674A7 /* Pods-DiaryApp-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 41145698F7DF35B05606D01197454CFC /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + A115142039C23F91827E6961CC479F05 /* SwiftyJSON-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ED12AA7015568FEE3FAA009FC97DAAD5 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + F038D81F7ABAA15CF03246AD4BF334F7 /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + CC9775904631956189536A37F63CE37E /* Pods-DiaryApp */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7B5018230A2DA353B0B36C08868324D1 /* Build configuration list for PBXNativeTarget "Pods-DiaryApp" */; + buildPhases = ( + 37AF420EAACFD30FC53913AC89710C00 /* Headers */, + 6681F71DB2F5634633FADB4DEB4719E7 /* Sources */, + FBF275D03B0C8D171A97F34D1C197333 /* Frameworks */, + D4122CB0EB090487D805F048E3000178 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 8F3650EC1DC9D8FAC97DBF6DAFF86B24 /* PBXTargetDependency */, + 8551393011A629CD25638D28ED437E0D /* PBXTargetDependency */, + ); + name = "Pods-DiaryApp"; + productName = Pods_DiaryApp; + productReference = 5F9C2818D0015901A6056D4A5F086DD3 /* Pods-DiaryApp */; + productType = "com.apple.product-type.framework"; + }; + D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2490E828D479276A7E0AFBA515DD77FA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */; + buildPhases = ( + 41145698F7DF35B05606D01197454CFC /* Headers */, + 7B5BEB32F210EFE38F7D58FF8A1CC2DE /* Sources */, + 3977393A21672F0FBC6F1193739E0D15 /* Frameworks */, + B05597C458D738E12F170EAC515F8483 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwiftyJSON; + productName = SwiftyJSON; + productReference = E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON */; + productType = "com.apple.product-type.framework"; + }; + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = D7761A54AFA2998F27E0BC2FACC2EB53 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + ED12AA7015568FEE3FAA009FC97DAAD5 /* Headers */, + 277C3B3F937C6D40D2B777A164FAB89D /* Sources */, + 5BF6E64D3157435E5797A5278584A4DC /* Frameworks */, + 565FD2058706F22D2347B30C65280F30 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1300; + LastUpgradeCheck = 1300; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 13.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + Base, + en, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = 8F75D8B612FBB879D9C90143AFCEFF25 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */, + CC9775904631956189536A37F63CE37E /* Pods-DiaryApp */, + D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 565FD2058706F22D2347B30C65280F30 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B05597C458D738E12F170EAC515F8483 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D4122CB0EB090487D805F048E3000178 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 277C3B3F937C6D40D2B777A164FAB89D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 320C0D7A88AA812EFB20016BA1F5D7AE /* AFError.swift in Sources */, + 81E6A0FF7F286008345ECFA3A2103FA8 /* Alamofire.swift in Sources */, + D09FBBADAF7C5C757AA5AB5DFE54BD25 /* Alamofire-dummy.m in Sources */, + F2415AE8678DE2698B7AD7D88B1A5C0F /* AlamofireExtended.swift in Sources */, + 197457852FC83E905248660B0F930452 /* AuthenticationInterceptor.swift in Sources */, + 04A8430BFC619C34E5F4D3878D094380 /* CachedResponseHandler.swift in Sources */, + 385BC4B250B6A6DB8AAAEA77D5B7A46F /* Combine.swift in Sources */, + 78B1DD1219182494A6AFAD26AAB20AA6 /* Concurrency.swift in Sources */, + 8E698F134A953250D5834C8B83CDAD34 /* DispatchQueue+Alamofire.swift in Sources */, + 82FD97FBBEFE51E2D3B434AF4954FC93 /* EventMonitor.swift in Sources */, + 529173B31EFCD3D199E79866AFBEC86C /* HTTPHeaders.swift in Sources */, + F66CC47AD425C8D57BD149AFD09C2AFE /* HTTPMethod.swift in Sources */, + 737747B9A98257DB58112C3A23686669 /* MultipartFormData.swift in Sources */, + 732C29255F73EF3D83D49BD4F8FEAA8F /* MultipartUpload.swift in Sources */, + BAB17A1C6CAD14B3788973EAF8466C93 /* NetworkReachabilityManager.swift in Sources */, + 3A59D8FBAF9A54906E3644AC80465AFB /* Notifications.swift in Sources */, + 7D64BC3E6CAA4AB54EAC0AAADE93F578 /* OperationQueue+Alamofire.swift in Sources */, + B17D933C8F8BC6A4F91AA620D7D7A870 /* ParameterEncoder.swift in Sources */, + 482B74C0548970BB9C095E2D8530E421 /* ParameterEncoding.swift in Sources */, + 079F0820555C5B86C9FBD5EC6344137F /* Protected.swift in Sources */, + ECE6F23823454A8FDB3F97CE1A7CD182 /* RedirectHandler.swift in Sources */, + 5B92A66A66BD639411C3D839A0F87B0C /* Request.swift in Sources */, + A523488C60BF961290D0B1ABB9ADACEC /* RequestCompression.swift in Sources */, + 1AFD57838680DF58184FF94D14C7F3FF /* RequestInterceptor.swift in Sources */, + ECF2F956B37A4C28B228BC291A57AD6E /* RequestTaskMap.swift in Sources */, + AA721ECC2B36AFB7D9FE70C83E6D63F9 /* Response.swift in Sources */, + 3FA127A261BB563409868A0DC21807B2 /* ResponseSerialization.swift in Sources */, + F6E94E8EE1CE35F49B9091BE8748587B /* Result+Alamofire.swift in Sources */, + 643A7AFFB7AEB70B2B9B7E0926055023 /* RetryPolicy.swift in Sources */, + 77AB6AF4BFC6DE016DA7C057B5799C84 /* ServerTrustEvaluation.swift in Sources */, + 282FCD4EA8B05830E9108690B8CD336B /* Session.swift in Sources */, + E6251F02EE12804D1B66AE32E716E664 /* SessionDelegate.swift in Sources */, + C04739CBCEE445B66192BFA708655EDF /* StringEncoding+Alamofire.swift in Sources */, + D0560E8E2E5EB407B5D8E0381BF453FA /* URLConvertible+URLRequestConvertible.swift in Sources */, + C8269B42DED12AB1F275648D0BD32E45 /* URLEncodedFormEncoder.swift in Sources */, + 11CCD832BD537718892C6A216A38490A /* URLRequest+Alamofire.swift in Sources */, + 67B10FEAA3B7E5387D20E76B1085E94D /* URLSessionConfiguration+Alamofire.swift in Sources */, + D368E6F70C5E6998548A72E65F92432D /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6681F71DB2F5634633FADB4DEB4719E7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6CB17C9753A4EAD270D129B366F9FEC5 /* Pods-DiaryApp-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7B5BEB32F210EFE38F7D58FF8A1CC2DE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A3CEE8324948497036C4E123B21CBC59 /* SwiftyJSON.swift in Sources */, + 5FA526557719FDBE81B1974B113CF600 /* SwiftyJSON-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 8551393011A629CD25638D28ED437E0D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SwiftyJSON; + target = D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */; + targetProxy = 9A946D9941B776AE87D1C60FE7A1CA37 /* PBXContainerItemProxy */; + }; + 8F3650EC1DC9D8FAC97DBF6DAFF86B24 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 25EE24530F5DE77C2138C3C848364587 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 61C156878AA0F739377C03E2D20A62BF /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A249A2B83CC3ECEF2DA592160DFE283D /* Pods-DiaryApp.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 8DE5143C03248BB6CD542DE3963D6F3A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 9E406C6AAF85E580207CD97B0044DEAB /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + A9EEBF12B0E3733A640B1F7870912751 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2E0ECA398B6DC3827602F405677B2C28 /* SwiftyJSON.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; + PRODUCT_MODULE_NAME = SwiftyJSON; + PRODUCT_NAME = SwiftyJSON; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + B7D9E7CD650F798EC835C67DACFEBC4F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = ED527FF867A54B900D1EA2E8F4AD4E2D /* Alamofire.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + BD0E5E3EFB0F4CCE246B60BB04FAB85B /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 08D72F04F55B8DAC1106A210D8946EC8 /* SwiftyJSON.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; + PRODUCT_MODULE_NAME = SwiftyJSON; + PRODUCT_NAME = SwiftyJSON; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + ED4DC8D666B2B63C25FA4E972D98AD8B /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1BF9CC04B4FD0CD457FA84A78FF7568A /* Pods-DiaryApp.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + F5F3306F2C09AB4B623C805497E28D51 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 40A2EBF5257D2162748FB0D6BAAC62BE /* Alamofire.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2490E828D479276A7E0AFBA515DD77FA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BD0E5E3EFB0F4CCE246B60BB04FAB85B /* Debug */, + A9EEBF12B0E3733A640B1F7870912751 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8DE5143C03248BB6CD542DE3963D6F3A /* Debug */, + 9E406C6AAF85E580207CD97B0044DEAB /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7B5018230A2DA353B0B36C08868324D1 /* Build configuration list for PBXNativeTarget "Pods-DiaryApp" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 61C156878AA0F739377C03E2D20A62BF /* Debug */, + ED4DC8D666B2B63C25FA4E972D98AD8B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + D7761A54AFA2998F27E0BC2FACC2EB53 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B7D9E7CD650F798EC835C67DACFEBC4F /* Debug */, + F5F3306F2C09AB4B623C805497E28D51 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/Pods/SwiftyJSON/LICENSE b/Pods/SwiftyJSON/LICENSE new file mode 100644 index 0000000..68e3fd7 --- /dev/null +++ b/Pods/SwiftyJSON/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Ruoyu Fu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/SwiftyJSON/README.md b/Pods/SwiftyJSON/README.md new file mode 100644 index 0000000..2465415 --- /dev/null +++ b/Pods/SwiftyJSON/README.md @@ -0,0 +1,560 @@ +# SwiftyJSON + +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com) + +SwiftyJSON makes it easy to deal with JSON data in Swift. + +Platform | Build Status +---------| --------------| +*OS | [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) | +[Linux](https://github.com/IBM-Swift/SwiftyJSON) | [![Build Status](https://travis-ci.org/IBM-Swift/SwiftyJSON.svg?branch=master)](https://travis-ci.org/IBM-Swift/SwiftyJSON) | + + +1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) +2. [Requirements](#requirements) +3. [Integration](#integration) +4. [Usage](#usage) + - [Initialization](#initialization) + - [Subscript](#subscript) + - [Loop](#loop) + - [Error](#error) + - [Optional getter](#optional-getter) + - [Non-optional getter](#non-optional-getter) + - [Setter](#setter) + - [Raw object](#raw-object) + - [Literal convertibles](#literal-convertibles) + - [Merging](#merging) +5. [Work with Alamofire](#work-with-alamofire) +6. [Work with Moya](#work-with-moya) +7. [SwiftyJSON Model Generator](#swiftyjson-model-generator) + + +## Why is the typical JSON handling in Swift NOT good? + +Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. + +Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to [Twitter's API](https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline)). + +The code would look like this: + +```swift +if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], + let user = statusesArray[0]["user"] as? [String: Any], + let username = user["name"] as? String { + // Finally we got the username +} +``` + +It's not good. + +Even if we use optional chaining, it would be messy: + +```swift +if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], + let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String { + // There's our username +} +``` + +An unreadable mess--for something that should really be simple! + +With SwiftyJSON all you have to do is: + +```swift +let json = JSON(data: dataFromNetworking) +if let userName = json[0]["user"]["name"].string { + //Now you got your value +} +``` + +And don't worry about the Optional Wrapping thing. It's done for you automatically. + +```swift +let json = JSON(data: dataFromNetworking) +let result = json[999999]["wrong_key"]["wrong_name"] +if let userName = result.string { + //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety +} else { + //Print the error + print(result.error) +} +``` + +## Requirements + +- iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+ +- Xcode 8 + +## Integration + +#### CocoaPods (iOS 8+, OS X 10.9+) + +You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON` by adding it to your `Podfile`: + +```ruby +platform :ios, '8.0' +use_frameworks! + +target 'MyApp' do + pod 'SwiftyJSON', '~> 4.0' +end +``` + +#### Carthage (iOS 8+, OS X 10.9+) + +You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: + +``` +github "SwiftyJSON/SwiftyJSON" ~> 4.0 +``` + +If you use Carthage to build your dependencies, make sure you have added `SwiftyJSON.framework` to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase. + +#### Swift Package Manager + +You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: + +```swift +// swift-tools-version:4.0 +import PackageDescription + +let package = Package( + name: "YOUR_PROJECT_NAME", + dependencies: [ + .package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", from: "4.0.0"), + ] +) +``` +Then run `swift build` whenever you get prepared. + +#### Manually (iOS 7+, OS X 10.9+) + +To use this library in your project manually you may: + +1. for Projects, just drag SwiftyJSON.swift to the project tree +2. for Workspaces, include the whole SwiftyJSON.xcodeproj + +## Usage + +#### Initialization + +```swift +import SwiftyJSON +``` + +```swift +let json = JSON(data: dataFromNetworking) +``` +Or + +```swift +let json = JSON(jsonObject) +``` +Or + +```swift +if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) { + let json = JSON(data: dataFromString) +} +``` + +#### Subscript + +```swift +// Getting a double from a JSON Array +let name = json[0].double +``` + +```swift +// Getting an array of string from a JSON Array +let arrayNames = json["users"].arrayValue.map {$0["name"].stringValue} +``` + +```swift +// Getting a string from a JSON Dictionary +let name = json["name"].stringValue +``` + +```swift +// Getting a string using a path to the element +let path: [JSONSubscriptType] = [1,"list",2,"name"] +let name = json[path].string +// Just the same +let name = json[1]["list"][2]["name"].string +// Alternatively +let name = json[1,"list",2,"name"].string +``` + +```swift +// With a hard way +let name = json[].string +``` + +```swift +// With a custom way +let keys:[JSONSubscriptType] = [1,"list",2,"name"] +let name = json[keys].string +``` + +#### Loop + +```swift +// If json is .Dictionary +for (key,subJson):(String, JSON) in json { + // Do something you want +} +``` + +*The first element is always a String, even if the JSON is an Array* + +```swift +// If json is .Array +// The `index` is 0.. = json["list"].arrayValue +``` + +```swift +// If not a Dictionary or nil, return [:] +let user: Dictionary = json["user"].dictionaryValue +``` + +#### Setter + +```swift +json["name"] = JSON("new-name") +json[0] = JSON(1) +``` + +```swift +json["id"].int = 1234567890 +json["coordinate"].double = 8766.766 +json["name"].string = "Jack" +json.arrayObject = [1,2,3,4] +json.dictionaryObject = ["name":"Jack", "age":25] +``` + +#### Raw object + +```swift +let rawObject: Any = json.object +``` + +```swift +let rawValue: Any = json.rawValue +``` + +```swift +//convert the JSON to raw NSData +do { + let rawData = try json.rawData() + //Do something you want +} catch { + print("Error \(error)") +} +``` + +```swift +//convert the JSON to a raw String +if let rawString = json.rawString() { + //Do something you want +} else { + print("json.rawString is nil") +} +``` + +#### Existence + +```swift +// shows you whether value specified in JSON or not +if json["name"].exists() +``` + +#### Literal convertibles + +For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) + +```swift +// StringLiteralConvertible +let json: JSON = "I'm a json" +``` + +```swift +/ /IntegerLiteralConvertible +let json: JSON = 12345 +``` + +```swift +// BooleanLiteralConvertible +let json: JSON = true +``` + +```swift +// FloatLiteralConvertible +let json: JSON = 2.8765 +``` + +```swift +// DictionaryLiteralConvertible +let json: JSON = ["I":"am", "a":"json"] +``` + +```swift +// ArrayLiteralConvertible +let json: JSON = ["I", "am", "a", "json"] +``` + +```swift +// With subscript in array +var json: JSON = [1,2,3] +json[0] = 100 +json[1] = 200 +json[2] = 300 +json[999] = 300 // Don't worry, nothing will happen +``` + +```swift +// With subscript in dictionary +var json: JSON = ["name": "Jack", "age": 25] +json["name"] = "Mike" +json["age"] = "25" // It's OK to set String +json["address"] = "L.A." // Add the "address": "L.A." in json +``` + +```swift +// Array & Dictionary +var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] +json["list"][3]["what"] = "that" +json["list",3,"what"] = "that" +let path: [JSONSubscriptType] = ["list",3,"what"] +json[path] = "that" +``` + +```swift +// With other JSON objects +let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] +let auth: JSON = [ + "user": user.object, // use user.object instead of just user + "apikey": "supersecretapitoken" +] +``` + +#### Merging + +It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the `other` JSON. + +If both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment: + +- In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. +- In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. + +In a case where two fields in a JSON have different types, the value will get always overwritten. + +There are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy. + +```swift +let original: JSON = [ + "first_name": "John", + "age": 20, + "skills": ["Coding", "Reading"], + "address": [ + "street": "Front St", + "zip": "12345", + ] +] + +let update: JSON = [ + "last_name": "Doe", + "age": 21, + "skills": ["Writing"], + "address": [ + "zip": "12342", + "city": "New York City" + ] +] + +let updated = original.merge(with: update) +// [ +// "first_name": "John", +// "last_name": "Doe", +// "age": 21, +// "skills": ["Coding", "Reading", "Writing"], +// "address": [ +// "street": "Front St", +// "zip": "12342", +// "city": "New York City" +// ] +// ] +``` + +## String representation +There are two options available: +- use the default Swift one +- use a custom one that will handle optionals well and represent `nil` as `"null"`: +```swift +let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] +let json = JSON(dict) +let representation = json.rawString(options: [.castNilToNSNull: true]) +// representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} +``` + +## Work with [Alamofire](https://github.com/Alamofire/Alamofire) + +SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: + +```swift +Alamofire.request(url, method: .get).validate().responseJSON { response in + switch response.result { + case .success(let value): + let json = JSON(value) + print("JSON: \(json)") + case .failure(let error): + print(error) + } +} +``` + +We also provide an extension of Alamofire for serializing NSData to SwiftyJSON's JSON. + +See: [Alamofire-SwiftyJSON](https://github.com/SwiftyJSON/Alamofire-SwiftyJSON) + + +## Work with [Moya](https://github.com/Moya/Moya) + +SwiftyJSON parse data to JSON: + +```swift +let provider = MoyaProvider() +provider.request(.showProducts) { result in + switch result { + case let .success(moyaResponse): + let data = moyaResponse.data + let json = JSON(data: data) // convert network data to json + print(json) + case let .failure(error): + print("error: \(error)") + } +} + +``` + +## SwiftyJSON Model Generator +Tools to generate SwiftyJSON Models +* [JSON Cafe](http://www.jsoncafe.com/) +* [JSON Export](https://github.com/Ahmed-Ali/JSONExport) diff --git a/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift b/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift new file mode 100644 index 0000000..f7a3f08 --- /dev/null +++ b/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift @@ -0,0 +1,1401 @@ +// SwiftyJSON.swift +// +// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// MARK: - Error +// swiftlint:disable line_length +public enum SwiftyJSONError: Int, Swift.Error { + case unsupportedType = 999 + case indexOutOfBounds = 900 + case elementTooDeep = 902 + case wrongType = 901 + case notExist = 500 + case invalidJSON = 490 +} + +extension SwiftyJSONError: CustomNSError { + + /// return the error domain of SwiftyJSONError + public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" } + + /// return the error code of SwiftyJSONError + public var errorCode: Int { return self.rawValue } + + /// return the userInfo of SwiftyJSONError + public var errorUserInfo: [String: Any] { + switch self { + case .unsupportedType: + return [NSLocalizedDescriptionKey: "It is an unsupported type."] + case .indexOutOfBounds: + return [NSLocalizedDescriptionKey: "Array Index is out of bounds."] + case .wrongType: + return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."] + case .notExist: + return [NSLocalizedDescriptionKey: "Dictionary key does not exist."] + case .invalidJSON: + return [NSLocalizedDescriptionKey: "JSON is invalid."] + case .elementTooDeep: + return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."] + } + } +} + +// MARK: - JSON Type + +/** +JSON's type definitions. + +See http://www.json.org +*/ +public enum Type: Int { + case number + case string + case bool + case array + case dictionary + case null + case unknown +} + +// MARK: - JSON Base + +public struct JSON { + + /** + Creates a JSON using the data. + + - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary + - parameter opt: The JSON serialization reading options. `[]` by default. + + - returns: The created JSON + */ + public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { + let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) + self.init(jsonObject: object) + } + + /** + Creates a JSON object + - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` + + - parameter object: the object + + - returns: the created JSON object + */ + public init(_ object: Any) { + switch object { + case let object as Data: + do { + try self.init(data: object) + } catch { + self.init(jsonObject: NSNull()) + } + default: + self.init(jsonObject: object) + } + } + + /** + Parses the JSON string into a JSON object + + - parameter json: the JSON string + + - returns: the created JSON object + */ + public init(parseJSON jsonString: String) { + if let data = jsonString.data(using: .utf8) { + self.init(data) + } else { + self.init(NSNull()) + } + } + + /** + Creates a JSON using the object. + + - parameter jsonObject: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. + + - returns: The created JSON + */ + fileprivate init(jsonObject: Any) { + object = jsonObject + } + + /** + Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. + + - parameter other: The JSON which gets merged into this JSON + + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. + */ + public mutating func merge(with other: JSON) throws { + try self.merge(with: other, typecheck: true) + } + + /** + Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, + present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. + + - parameter other: The JSON which gets merged into this JSON + + - throws `ErrorWrongType` if the other JSONs differs in type on the top level. + + - returns: New merged JSON + */ + public func merged(with other: JSON) throws -> JSON { + var merged = self + try merged.merge(with: other, typecheck: true) + return merged + } + + /** + Private woker function which does the actual merging + Typecheck is set to true for the first recursion level to prevent total override of the source JSON + */ + fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { + if type == other.type { + switch type { + case .dictionary: + for (key, _) in other { + try self[key].merge(with: other[key], typecheck: false) + } + case .array: + self = JSON(arrayValue + other.arrayValue) + default: + self = other + } + } else { + if typecheck { + throw SwiftyJSONError.wrongType + } else { + self = other + } + } + } + + /// Private object + fileprivate var rawArray: [Any] = [] + fileprivate var rawDictionary: [String: Any] = [:] + fileprivate var rawString: String = "" + fileprivate var rawNumber: NSNumber = 0 + fileprivate var rawNull: NSNull = NSNull() + fileprivate var rawBool: Bool = false + + /// JSON type, fileprivate setter + public fileprivate(set) var type: Type = .null + + /// Error in JSON, fileprivate setter + public fileprivate(set) var error: SwiftyJSONError? + + /// Object in JSON + public var object: Any { + get { + switch type { + case .array: return rawArray + case .dictionary: return rawDictionary + case .string: return rawString + case .number: return rawNumber + case .bool: return rawBool + default: return rawNull + } + } + set { + error = nil + switch unwrap(newValue) { + case let number as NSNumber: + if number.isBool { + type = .bool + rawBool = number.boolValue + } else { + type = .number + rawNumber = number + } + case let string as String: + type = .string + rawString = string + case _ as NSNull: + type = .null + case nil: + type = .null + case let array as [Any]: + type = .array + rawArray = array + case let dictionary as [String: Any]: + type = .dictionary + rawDictionary = dictionary + default: + type = .unknown + error = SwiftyJSONError.unsupportedType + } + } + } + + /// The static null JSON + @available(*, unavailable, renamed:"null") + public static var nullJSON: JSON { return null } + public static var null: JSON { return JSON(NSNull()) } +} + +/// Private method to unwarp an object recursively +private func unwrap(_ object: Any) -> Any { + switch object { + case let json as JSON: + return unwrap(json.object) + case let array as [Any]: + return array.map(unwrap) + case let dictionary as [String: Any]: + var d = dictionary + dictionary.forEach { pair in + d[pair.key] = unwrap(pair.value) + } + return d + default: + return object + } +} + +public enum Index: Comparable { + case array(Int) + case dictionary(DictionaryIndex) + case null + + static public func == (lhs: Index, rhs: Index) -> Bool { + switch (lhs, rhs) { + case (.array(let left), .array(let right)): return left == right + case (.dictionary(let left), .dictionary(let right)): return left == right + case (.null, .null): return true + default: return false + } + } + + static public func < (lhs: Index, rhs: Index) -> Bool { + switch (lhs, rhs) { + case (.array(let left), .array(let right)): return left < right + case (.dictionary(let left), .dictionary(let right)): return left < right + default: return false + } + } +} + +public typealias JSONIndex = Index +public typealias JSONRawIndex = Index + +extension JSON: Swift.Collection { + + public typealias Index = JSONRawIndex + + public var startIndex: Index { + switch type { + case .array: return .array(rawArray.startIndex) + case .dictionary: return .dictionary(rawDictionary.startIndex) + default: return .null + } + } + + public var endIndex: Index { + switch type { + case .array: return .array(rawArray.endIndex) + case .dictionary: return .dictionary(rawDictionary.endIndex) + default: return .null + } + } + + public func index(after i: Index) -> Index { + switch i { + case .array(let idx): return .array(rawArray.index(after: idx)) + case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) + default: return .null + } + } + + public subscript (position: Index) -> (String, JSON) { + switch position { + case .array(let idx): return (String(idx), JSON(rawArray[idx])) + case .dictionary(let idx): return (rawDictionary[idx].key, JSON(rawDictionary[idx].value)) + default: return ("", JSON.null) + } + } +} + +// MARK: - Subscript + +/** + * To mark both String and Int can be used in subscript. + */ +public enum JSONKey { + case index(Int) + case key(String) +} + +public protocol JSONSubscriptType { + var jsonKey: JSONKey { get } +} + +extension Int: JSONSubscriptType { + public var jsonKey: JSONKey { + return JSONKey.index(self) + } +} + +extension String: JSONSubscriptType { + public var jsonKey: JSONKey { + return JSONKey.key(self) + } +} + +extension JSON { + + /// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error. + fileprivate subscript(index index: Int) -> JSON { + get { + if type != .array { + var r = JSON.null + r.error = self.error ?? SwiftyJSONError.wrongType + return r + } else if rawArray.indices.contains(index) { + return JSON(rawArray[index]) + } else { + var r = JSON.null + r.error = SwiftyJSONError.indexOutOfBounds + return r + } + } + set { + if type == .array && + rawArray.indices.contains(index) && + newValue.error == nil { + rawArray[index] = newValue.object + } + } + } + + /// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. + fileprivate subscript(key key: String) -> JSON { + get { + var r = JSON.null + if type == .dictionary { + if let o = rawDictionary[key] { + r = JSON(o) + } else { + r.error = SwiftyJSONError.notExist + } + } else { + r.error = self.error ?? SwiftyJSONError.wrongType + } + return r + } + set { + if type == .dictionary && newValue.error == nil { + rawDictionary[key] = newValue.object + } + } + } + + /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. + fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { + get { + switch sub.jsonKey { + case .index(let index): return self[index: index] + case .key(let key): return self[key: key] + } + } + set { + switch sub.jsonKey { + case .index(let index): self[index: index] = newValue + case .key(let key): self[key: key] = newValue + } + } + } + + /** + Find a json in the complex data structures by using array of Int and/or String as path. + + Example: + + ``` + let json = JSON[data] + let path = [9,"list","person","name"] + let name = json[path] + ``` + + The same as: let name = json[9]["list"]["person"]["name"] + + - parameter path: The target json's path. + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: [JSONSubscriptType]) -> JSON { + get { + return path.reduce(self) { $0[sub: $1] } + } + set { + switch path.count { + case 0: return + case 1: self[sub:path[0]].object = newValue.object + default: + var aPath = path + aPath.remove(at: 0) + var nextJSON = self[sub: path[0]] + nextJSON[aPath] = newValue + self[sub: path[0]] = nextJSON + } + } + } + + /** + Find a json in the complex data structures by using array of Int and/or String as path. + + - parameter path: The target json's path. Example: + + let name = json[9,"list","person","name"] + + The same as: let name = json[9]["list"]["person"]["name"] + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: JSONSubscriptType...) -> JSON { + get { + return self[path] + } + set { + self[path] = newValue + } + } +} + +// MARK: - LiteralConvertible + +extension JSON: Swift.ExpressibleByStringLiteral { + + public init(stringLiteral value: StringLiteralType) { + self.init(value) + } + + public init(extendedGraphemeClusterLiteral value: StringLiteralType) { + self.init(value) + } + + public init(unicodeScalarLiteral value: StringLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByIntegerLiteral { + + public init(integerLiteral value: IntegerLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByBooleanLiteral { + + public init(booleanLiteral value: BooleanLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByFloatLiteral { + + public init(floatLiteral value: FloatLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, Any)...) { + let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1}) + self.init(dictionary) + } +} + +extension JSON: Swift.ExpressibleByArrayLiteral { + + public init(arrayLiteral elements: Any...) { + self.init(elements) + } +} + +// MARK: - Raw + +extension JSON: Swift.RawRepresentable { + + public init?(rawValue: Any) { + if JSON(rawValue).type == .unknown { + return nil + } else { + self.init(rawValue) + } + } + + public var rawValue: Any { + return object + } + + public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { + guard JSONSerialization.isValidJSONObject(object) else { + throw SwiftyJSONError.invalidJSON + } + + return try JSONSerialization.data(withJSONObject: object, options: opt) + } + + public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { + do { + return try _rawString(encoding, options: [.jsonSerialization: opt]) + } catch { + print("Could not serialize object to JSON because:", error.localizedDescription) + return nil + } + } + + public func rawString(_ options: [writingOptionsKeys: Any]) -> String? { + let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 + let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 + do { + return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) + } catch { + print("Could not serialize object to JSON because:", error.localizedDescription) + return nil + } + } + + fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { + guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON } + switch type { + case .dictionary: + do { + if !(options[.castNilToNSNull] as? Bool ?? false) { + let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted + let data = try rawData(options: jsonOption) + return String(data: data, encoding: encoding) + } + + guard let dict = object as? [String: Any?] else { + return nil + } + let body = try dict.keys.map { key throws -> String in + guard let value = dict[key] else { + return "\"\(key)\": null" + } + guard let unwrappedValue = value else { + return "\"\(key)\": null" + } + + let nestedValue = JSON(unwrappedValue) + guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { + throw SwiftyJSONError.elementTooDeep + } + if nestedValue.type == .string { + return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" + } else { + return "\"\(key)\": \(nestedString)" + } + } + + return "{\(body.joined(separator: ","))}" + } catch _ { + return nil + } + case .array: + do { + if !(options[.castNilToNSNull] as? Bool ?? false) { + let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted + let data = try rawData(options: jsonOption) + return String(data: data, encoding: encoding) + } + + guard let array = object as? [Any?] else { + return nil + } + let body = try array.map { value throws -> String in + guard let unwrappedValue = value else { + return "null" + } + + let nestedValue = JSON(unwrappedValue) + guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { + throw SwiftyJSONError.invalidJSON + } + if nestedValue.type == .string { + return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" + } else { + return nestedString + } + } + + return "[\(body.joined(separator: ","))]" + } catch _ { + return nil + } + case .string: return rawString + case .number: return rawNumber.stringValue + case .bool: return rawBool.description + case .null: return "null" + default: return nil + } + } +} + +// MARK: - Printable, DebugPrintable + +extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { + + public var description: String { + return rawString(options: .prettyPrinted) ?? "unknown" + } + + public var debugDescription: String { + return description + } +} + +// MARK: - Array + +extension JSON { + + //Optional [JSON] + public var array: [JSON]? { + return type == .array ? rawArray.map { JSON($0) } : nil + } + + //Non-optional [JSON] + public var arrayValue: [JSON] { + return self.array ?? [] + } + + //Optional [Any] + public var arrayObject: [Any]? { + get { + switch type { + case .array: return rawArray + default: return nil + } + } + set { + self.object = newValue ?? NSNull() + } + } +} + +// MARK: - Dictionary + +extension JSON { + + //Optional [String : JSON] + public var dictionary: [String: JSON]? { + if type == .dictionary { + var d = [String: JSON](minimumCapacity: rawDictionary.count) + rawDictionary.forEach { pair in + d[pair.key] = JSON(pair.value) + } + return d + } else { + return nil + } + } + + //Non-optional [String : JSON] + public var dictionaryValue: [String: JSON] { + return dictionary ?? [:] + } + + //Optional [String : Any] + + public var dictionaryObject: [String: Any]? { + get { + switch type { + case .dictionary: return rawDictionary + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } +} + +// MARK: - Bool + +extension JSON { // : Swift.Bool + + //Optional bool + public var bool: Bool? { + get { + switch type { + case .bool: return rawBool + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } + + //Non-optional bool + public var boolValue: Bool { + get { + switch type { + case .bool: return rawBool + case .number: return rawNumber.boolValue + case .string: return ["true", "y", "t", "yes", "1"].contains { rawString.caseInsensitiveCompare($0) == .orderedSame } + default: return false + } + } + set { + object = newValue + } + } +} + +// MARK: - String + +extension JSON { + + //Optional string + public var string: String? { + get { + switch type { + case .string: return object as? String + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } + + //Non-optional string + public var stringValue: String { + get { + switch type { + case .string: return object as? String ?? "" + case .number: return rawNumber.stringValue + case .bool: return (object as? Bool).map { String($0) } ?? "" + default: return "" + } + } + set { + object = newValue + } + } +} + +// MARK: - Number + +extension JSON { + + //Optional number + public var number: NSNumber? { + get { + switch type { + case .number: return rawNumber + case .bool: return NSNumber(value: rawBool ? 1 : 0) + default: return nil + } + } + set { + object = newValue ?? NSNull() + } + } + + //Non-optional number + public var numberValue: NSNumber { + get { + switch type { + case .string: + let decimal = NSDecimalNumber(string: object as? String) + return decimal == .notANumber ? .zero : decimal + case .number: return object as? NSNumber ?? NSNumber(value: 0) + case .bool: return NSNumber(value: rawBool ? 1 : 0) + default: return NSNumber(value: 0.0) + } + } + set { + object = newValue + } + } +} + +// MARK: - Null + +extension JSON { + + public var null: NSNull? { + set { + object = NSNull() + } + get { + switch type { + case .null: return rawNull + default: return nil + } + } + } + public func exists() -> Bool { + if let errorValue = error, (400...1000).contains(errorValue.errorCode) { + return false + } + return true + } +} + +// MARK: - URL + +extension JSON { + + //Optional URL + public var url: URL? { + get { + switch type { + case .string: + // Check for existing percent escapes first to prevent double-escaping of % character + if rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { + return Foundation.URL(string: rawString) + } else if let encodedString_ = rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { + // We have to use `Foundation.URL` otherwise it conflicts with the variable name. + return Foundation.URL(string: encodedString_) + } else { + return nil + } + default: + return nil + } + } + set { + object = newValue?.absoluteString ?? NSNull() + } + } +} + +// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 + +extension JSON { + + public var double: Double? { + get { + return number?.doubleValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var doubleValue: Double { + get { + return numberValue.doubleValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var float: Float? { + get { + return number?.floatValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var floatValue: Float { + get { + return numberValue.floatValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var int: Int? { + get { + return number?.intValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var intValue: Int { + get { + return numberValue.intValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt: UInt? { + get { + return number?.uintValue + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uIntValue: UInt { + get { + return numberValue.uintValue + } + set { + object = NSNumber(value: newValue) + } + } + + public var int8: Int8? { + get { + return number?.int8Value + } + set { + if let newValue = newValue { + object = NSNumber(value: Int(newValue)) + } else { + object = NSNull() + } + } + } + + public var int8Value: Int8 { + get { + return numberValue.int8Value + } + set { + object = NSNumber(value: Int(newValue)) + } + } + + public var uInt8: UInt8? { + get { + return number?.uint8Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt8Value: UInt8 { + get { + return numberValue.uint8Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var int16: Int16? { + get { + return number?.int16Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var int16Value: Int16 { + get { + return numberValue.int16Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt16: UInt16? { + get { + return number?.uint16Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt16Value: UInt16 { + get { + return numberValue.uint16Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var int32: Int32? { + get { + return number?.int32Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var int32Value: Int32 { + get { + return numberValue.int32Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt32: UInt32? { + get { + return number?.uint32Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt32Value: UInt32 { + get { + return numberValue.uint32Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var int64: Int64? { + get { + return number?.int64Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var int64Value: Int64 { + get { + return numberValue.int64Value + } + set { + object = NSNumber(value: newValue) + } + } + + public var uInt64: UInt64? { + get { + return number?.uint64Value + } + set { + if let newValue = newValue { + object = NSNumber(value: newValue) + } else { + object = NSNull() + } + } + } + + public var uInt64Value: UInt64 { + get { + return numberValue.uint64Value + } + set { + object = NSNumber(value: newValue) + } + } +} + +// MARK: - Comparable + +extension JSON: Swift.Comparable {} + +public func == (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber == rhs.rawNumber + case (.string, .string): return lhs.rawString == rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false + } +} + +public func <= (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber <= rhs.rawNumber + case (.string, .string): return lhs.rawString <= rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false + } +} + +public func >= (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber >= rhs.rawNumber + case (.string, .string): return lhs.rawString >= rhs.rawString + case (.bool, .bool): return lhs.rawBool == rhs.rawBool + case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.null, .null): return true + default: return false + } +} + +public func > (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber > rhs.rawNumber + case (.string, .string): return lhs.rawString > rhs.rawString + default: return false + } +} + +public func < (lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.number, .number): return lhs.rawNumber < rhs.rawNumber + case (.string, .string): return lhs.rawString < rhs.rawString + default: return false + } +} + +private let trueNumber = NSNumber(value: true) +private let falseNumber = NSNumber(value: false) +private let trueObjCType = String(cString: trueNumber.objCType) +private let falseObjCType = String(cString: falseNumber.objCType) + +// MARK: - NSNumber: Comparable + +extension NSNumber { + fileprivate var isBool: Bool { + let objCType = String(cString: self.objCType) + if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { + return true + } else { + return false + } + } +} + +func == (lhs: NSNumber, rhs: NSNumber) -> Bool { + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == .orderedSame + } +} + +func != (lhs: NSNumber, rhs: NSNumber) -> Bool { + return !(lhs == rhs) +} + +func < (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == .orderedAscending + } +} + +func > (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) == ComparisonResult.orderedDescending + } +} + +func <= (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) != .orderedDescending + } +} + +func >= (lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): return false + case (true, false): return false + default: return lhs.compare(rhs) != .orderedAscending + } +} + +public enum writingOptionsKeys { + case jsonSerialization + case castNilToNSNull + case maxObjextDepth + case encoding +} + +// MARK: - JSON: Codable +extension JSON: Codable { + private static var codableTypes: [Codable.Type] { + return [ + Bool.self, + Int.self, + Int8.self, + Int16.self, + Int32.self, + Int64.self, + UInt.self, + UInt8.self, + UInt16.self, + UInt32.self, + UInt64.self, + Double.self, + String.self, + [JSON].self, + [String: JSON].self + ] + } + public init(from decoder: Decoder) throws { + var object: Any? + + if let container = try? decoder.singleValueContainer(), !container.decodeNil() { + for type in JSON.codableTypes { + if object != nil { + break + } + // try to decode value + switch type { + case let boolType as Bool.Type: + object = try? container.decode(boolType) + case let intType as Int.Type: + object = try? container.decode(intType) + case let int8Type as Int8.Type: + object = try? container.decode(int8Type) + case let int32Type as Int32.Type: + object = try? container.decode(int32Type) + case let int64Type as Int64.Type: + object = try? container.decode(int64Type) + case let uintType as UInt.Type: + object = try? container.decode(uintType) + case let uint8Type as UInt8.Type: + object = try? container.decode(uint8Type) + case let uint16Type as UInt16.Type: + object = try? container.decode(uint16Type) + case let uint32Type as UInt32.Type: + object = try? container.decode(uint32Type) + case let uint64Type as UInt64.Type: + object = try? container.decode(uint64Type) + case let doubleType as Double.Type: + object = try? container.decode(doubleType) + case let stringType as String.Type: + object = try? container.decode(stringType) + case let jsonValueArrayType as [JSON].Type: + object = try? container.decode(jsonValueArrayType) + case let jsonValueDictType as [String: JSON].Type: + object = try? container.decode(jsonValueDictType) + default: + break + } + } + } + self.init(object ?? NSNull()) + } + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + if object is NSNull { + try container.encodeNil() + return + } + switch object { + case let intValue as Int: + try container.encode(intValue) + case let int8Value as Int8: + try container.encode(int8Value) + case let int32Value as Int32: + try container.encode(int32Value) + case let int64Value as Int64: + try container.encode(int64Value) + case let uintValue as UInt: + try container.encode(uintValue) + case let uint8Value as UInt8: + try container.encode(uint8Value) + case let uint16Value as UInt16: + try container.encode(uint16Value) + case let uint32Value as UInt32: + try container.encode(uint32Value) + case let uint64Value as UInt64: + try container.encode(uint64Value) + case let doubleValue as Double: + try container.encode(doubleValue) + case let boolValue as Bool: + try container.encode(boolValue) + case let stringValue as String: + try container.encode(stringValue) + case is [Any]: + let jsonValueArray = array ?? [] + try container.encode(jsonValueArray) + case is [String: Any]: + let jsonValueDictValue = dictionary ?? [:] + try container.encode(jsonValueDictValue) + default: + break + } + } +} diff --git a/Pods/Target Support Files/Alamofire/Alamofire-Info.plist b/Pods/Target Support Files/Alamofire/Alamofire-Info.plist new file mode 100644 index 0000000..b22a6a3 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.8.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000..a6c4594 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000..00014e3 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig b/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig new file mode 100644 index 0000000..dbfd4d1 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "CFNetwork" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000..d1f125f --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig b/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig new file mode 100644 index 0000000..dbfd4d1 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "CFNetwork" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist new file mode 100644 index 0000000..19cf209 --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.markdown b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.markdown new file mode 100644 index 0000000..6c1dc97 --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.markdown @@ -0,0 +1,51 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## SwiftyJSON + +The MIT License (MIT) + +Copyright (c) 2017 Ruoyu Fu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.plist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.plist new file mode 100644 index 0000000..ab49857 --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.plist @@ -0,0 +1,89 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2017 Ruoyu Fu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + MIT + Title + SwiftyJSON + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-dummy.m b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-dummy.m new file mode 100644 index 0000000..dc0a239 --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_DiaryApp : NSObject +@end +@implementation PodsDummy_Pods_DiaryApp +@end diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-input-files.xcfilelist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-input-files.xcfilelist new file mode 100644 index 0000000..0b63d92 --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-input-files.xcfilelist @@ -0,0 +1,3 @@ +${PODS_ROOT}/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh +${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework +${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-output-files.xcfilelist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-output-files.xcfilelist new file mode 100644 index 0000000..65d4b8b --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-output-files.xcfilelist @@ -0,0 +1,2 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftyJSON.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-input-files.xcfilelist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-input-files.xcfilelist new file mode 100644 index 0000000..0b63d92 --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-input-files.xcfilelist @@ -0,0 +1,3 @@ +${PODS_ROOT}/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh +${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework +${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-output-files.xcfilelist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-output-files.xcfilelist new file mode 100644 index 0000000..65d4b8b --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-output-files.xcfilelist @@ -0,0 +1,2 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftyJSON.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh new file mode 100755 index 0000000..cf2dcd9 --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh @@ -0,0 +1,188 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +BCSYMBOLMAP_DIR="BCSymbolMaps" + + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink -f "${source}")" + fi + + if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then + # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied + find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do + echo "Installing $f" + install_bcsymbolmap "$f" "$destination" + rm "$f" + done + rmdir "${source}/${BCSYMBOLMAP_DIR}" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + warn_missing_arch=${2:-true} + if [ -r "$source" ]; then + # Copy the dSYM into the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .dSYM "$source")" + binary_name="$(ls "$source/Contents/Resources/DWARF")" + binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" + + # Strip invalid architectures from the dSYM. + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" "$warn_missing_arch" + fi + if [[ $STRIP_BINARY_RETVAL == 0 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + mkdir -p "${DWARF_DSYM_FOLDER_PATH}" + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" + fi + fi +} + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + warn_missing_arch=${2:-true} + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + if [[ "$warn_missing_arch" == "true" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + fi + STRIP_BINARY_RETVAL=1 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=0 +} + +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-umbrella.h b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-umbrella.h new file mode 100644 index 0000000..873fb43 --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_DiaryAppVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_DiaryAppVersionString[]; + diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.debug.xcconfig b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.debug.xcconfig new file mode 100644 index 0000000..83a54bd --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.debug.xcconfig @@ -0,0 +1,15 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON/SwiftyJSON.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "SwiftyJSON" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap new file mode 100644 index 0000000..0aeff01 --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap @@ -0,0 +1,6 @@ +framework module Pods_DiaryApp { + umbrella header "Pods-DiaryApp-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.release.xcconfig b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.release.xcconfig new file mode 100644 index 0000000..83a54bd --- /dev/null +++ b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.release.xcconfig @@ -0,0 +1,15 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON/SwiftyJSON.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "SwiftyJSON" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist new file mode 100644 index 0000000..8136e62 --- /dev/null +++ b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + ${PODS_DEVELOPMENT_LANGUAGE} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.0.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m new file mode 100644 index 0000000..3159bec --- /dev/null +++ b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SwiftyJSON : NSObject +@end +@implementation PodsDummy_SwiftyJSON +@end diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h new file mode 100644 index 0000000..b627dec --- /dev/null +++ b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double SwiftyJSONVersionNumber; +FOUNDATION_EXPORT const unsigned char SwiftyJSONVersionString[]; + diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig new file mode 100644 index 0000000..2ac300f --- /dev/null +++ b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftyJSON +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap new file mode 100644 index 0000000..6f41751 --- /dev/null +++ b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap @@ -0,0 +1,6 @@ +framework module SwiftyJSON { + umbrella header "SwiftyJSON-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig new file mode 100644 index 0000000..2ac300f --- /dev/null +++ b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftyJSON +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES From e91a0dca1e049e61450501297aa3b8aa966e7d8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=B5=E1=86=B7=E1=84=80=E1=85=B5=E1=84=92?= =?UTF-8?q?=E1=85=A7=E1=86=AB?= Date: Mon, 4 Sep 2023 01:36:11 +0900 Subject: [PATCH 42/42] [FIX] pod file remove --- .../Controllers/NewDiaryViewController.swift | 4 +- Podfile | 11 - Podfile.lock | 20 - Pods/Alamofire/LICENSE | 19 - Pods/Alamofire/README.md | 227 -- Pods/Alamofire/Source/AFError.swift | 874 ------- Pods/Alamofire/Source/Alamofire.swift | 40 - Pods/Alamofire/Source/AlamofireExtended.swift | 61 - .../Source/AuthenticationInterceptor.swift | 403 ---- .../Source/CachedResponseHandler.swift | 107 - Pods/Alamofire/Source/Combine.swift | 655 ------ Pods/Alamofire/Source/Concurrency.swift | 832 ------- .../Source/DispatchQueue+Alamofire.swift | 37 - Pods/Alamofire/Source/EventMonitor.swift | 907 -------- Pods/Alamofire/Source/HTTPHeaders.swift | 452 ---- Pods/Alamofire/Source/HTTPMethod.swift | 56 - Pods/Alamofire/Source/MultipartFormData.swift | 601 ----- Pods/Alamofire/Source/MultipartUpload.swift | 89 - .../Source/NetworkReachabilityManager.swift | 301 --- Pods/Alamofire/Source/Notifications.swift | 115 - .../Source/OperationQueue+Alamofire.swift | 49 - Pods/Alamofire/Source/ParameterEncoder.swift | 213 -- Pods/Alamofire/Source/ParameterEncoding.swift | 346 --- Pods/Alamofire/Source/Protected.swift | 161 -- Pods/Alamofire/Source/RedirectHandler.swift | 111 - Pods/Alamofire/Source/Request.swift | 2070 ----------------- .../Alamofire/Source/RequestCompression.swift | 153 -- .../Alamofire/Source/RequestInterceptor.swift | 351 --- Pods/Alamofire/Source/RequestTaskMap.swift | 149 -- Pods/Alamofire/Source/Response.swift | 453 ---- .../Source/ResponseSerialization.swift | 1270 ---------- Pods/Alamofire/Source/Result+Alamofire.swift | 120 - Pods/Alamofire/Source/RetryPolicy.swift | 430 ---- .../Source/ServerTrustEvaluation.swift | 772 ------ Pods/Alamofire/Source/Session.swift | 1264 ---------- Pods/Alamofire/Source/SessionDelegate.swift | 355 --- .../Source/StringEncoding+Alamofire.swift | 55 - ...URLConvertible+URLRequestConvertible.swift | 105 - .../Source/URLEncodedFormEncoder.swift | 1083 --------- .../Source/URLRequest+Alamofire.swift | 39 - .../URLSessionConfiguration+Alamofire.swift | 46 - Pods/Alamofire/Source/Validation.swift | 302 --- Pods/Manifest.lock | 20 - Pods/Pods.xcodeproj/project.pbxproj | 939 -------- Pods/SwiftyJSON/LICENSE | 21 - Pods/SwiftyJSON/README.md | 560 ----- .../Source/SwiftyJSON/SwiftyJSON.swift | 1401 ----------- .../Alamofire/Alamofire-Info.plist | 26 - .../Alamofire/Alamofire-dummy.m | 5 - .../Alamofire/Alamofire-prefix.pch | 12 - .../Alamofire/Alamofire-umbrella.h | 16 - .../Alamofire/Alamofire.debug.xcconfig | 15 - .../Alamofire/Alamofire.modulemap | 6 - .../Alamofire/Alamofire.release.xcconfig | 15 - .../Pods-DiaryApp/Pods-DiaryApp-Info.plist | 26 - .../Pods-DiaryApp-acknowledgements.markdown | 51 - .../Pods-DiaryApp-acknowledgements.plist | 89 - .../Pods-DiaryApp/Pods-DiaryApp-dummy.m | 5 - ...pp-frameworks-Debug-input-files.xcfilelist | 3 - ...p-frameworks-Debug-output-files.xcfilelist | 2 - ...-frameworks-Release-input-files.xcfilelist | 3 - ...frameworks-Release-output-files.xcfilelist | 2 - .../Pods-DiaryApp/Pods-DiaryApp-frameworks.sh | 188 -- .../Pods-DiaryApp/Pods-DiaryApp-umbrella.h | 16 - .../Pods-DiaryApp.debug.xcconfig | 15 - .../Pods-DiaryApp/Pods-DiaryApp.modulemap | 6 - .../Pods-DiaryApp.release.xcconfig | 15 - .../SwiftyJSON/SwiftyJSON-Info.plist | 26 - .../SwiftyJSON/SwiftyJSON-dummy.m | 5 - .../SwiftyJSON/SwiftyJSON-prefix.pch | 12 - .../SwiftyJSON/SwiftyJSON-umbrella.h | 16 - .../SwiftyJSON/SwiftyJSON.debug.xcconfig | 14 - .../SwiftyJSON/SwiftyJSON.modulemap | 6 - .../SwiftyJSON/SwiftyJSON.release.xcconfig | 14 - 74 files changed, 3 insertions(+), 19255 deletions(-) delete mode 100644 Podfile delete mode 100644 Podfile.lock delete mode 100644 Pods/Alamofire/LICENSE delete mode 100644 Pods/Alamofire/README.md delete mode 100644 Pods/Alamofire/Source/AFError.swift delete mode 100644 Pods/Alamofire/Source/Alamofire.swift delete mode 100644 Pods/Alamofire/Source/AlamofireExtended.swift delete mode 100644 Pods/Alamofire/Source/AuthenticationInterceptor.swift delete mode 100644 Pods/Alamofire/Source/CachedResponseHandler.swift delete mode 100644 Pods/Alamofire/Source/Combine.swift delete mode 100644 Pods/Alamofire/Source/Concurrency.swift delete mode 100644 Pods/Alamofire/Source/DispatchQueue+Alamofire.swift delete mode 100644 Pods/Alamofire/Source/EventMonitor.swift delete mode 100644 Pods/Alamofire/Source/HTTPHeaders.swift delete mode 100644 Pods/Alamofire/Source/HTTPMethod.swift delete mode 100644 Pods/Alamofire/Source/MultipartFormData.swift delete mode 100644 Pods/Alamofire/Source/MultipartUpload.swift delete mode 100644 Pods/Alamofire/Source/NetworkReachabilityManager.swift delete mode 100644 Pods/Alamofire/Source/Notifications.swift delete mode 100644 Pods/Alamofire/Source/OperationQueue+Alamofire.swift delete mode 100644 Pods/Alamofire/Source/ParameterEncoder.swift delete mode 100644 Pods/Alamofire/Source/ParameterEncoding.swift delete mode 100644 Pods/Alamofire/Source/Protected.swift delete mode 100644 Pods/Alamofire/Source/RedirectHandler.swift delete mode 100644 Pods/Alamofire/Source/Request.swift delete mode 100644 Pods/Alamofire/Source/RequestCompression.swift delete mode 100644 Pods/Alamofire/Source/RequestInterceptor.swift delete mode 100644 Pods/Alamofire/Source/RequestTaskMap.swift delete mode 100644 Pods/Alamofire/Source/Response.swift delete mode 100644 Pods/Alamofire/Source/ResponseSerialization.swift delete mode 100644 Pods/Alamofire/Source/Result+Alamofire.swift delete mode 100644 Pods/Alamofire/Source/RetryPolicy.swift delete mode 100644 Pods/Alamofire/Source/ServerTrustEvaluation.swift delete mode 100644 Pods/Alamofire/Source/Session.swift delete mode 100644 Pods/Alamofire/Source/SessionDelegate.swift delete mode 100644 Pods/Alamofire/Source/StringEncoding+Alamofire.swift delete mode 100644 Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift delete mode 100644 Pods/Alamofire/Source/URLEncodedFormEncoder.swift delete mode 100644 Pods/Alamofire/Source/URLRequest+Alamofire.swift delete mode 100644 Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift delete mode 100644 Pods/Alamofire/Source/Validation.swift delete mode 100644 Pods/Manifest.lock delete mode 100644 Pods/Pods.xcodeproj/project.pbxproj delete mode 100644 Pods/SwiftyJSON/LICENSE delete mode 100644 Pods/SwiftyJSON/README.md delete mode 100644 Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift delete mode 100644 Pods/Target Support Files/Alamofire/Alamofire-Info.plist delete mode 100644 Pods/Target Support Files/Alamofire/Alamofire-dummy.m delete mode 100644 Pods/Target Support Files/Alamofire/Alamofire-prefix.pch delete mode 100644 Pods/Target Support Files/Alamofire/Alamofire-umbrella.h delete mode 100644 Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig delete mode 100644 Pods/Target Support Files/Alamofire/Alamofire.modulemap delete mode 100644 Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.markdown delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.plist delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-dummy.m delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-input-files.xcfilelist delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-output-files.xcfilelist delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-input-files.xcfilelist delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-output-files.xcfilelist delete mode 100755 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-umbrella.h delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.debug.xcconfig delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap delete mode 100644 Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.release.xcconfig delete mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist delete mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m delete mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch delete mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h delete mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig delete mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap delete mode 100644 Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig diff --git a/DiaryApp/Controllers/NewDiaryViewController.swift b/DiaryApp/Controllers/NewDiaryViewController.swift index d5371d3..9e5ef18 100644 --- a/DiaryApp/Controllers/NewDiaryViewController.swift +++ b/DiaryApp/Controllers/NewDiaryViewController.swift @@ -196,7 +196,9 @@ class NewDiaryViewController: UIViewController { // 날씨 정보를 받아와 UI에 표시 DispatchQueue.main.async { self.weatherDescriptionLabel.text = weatherData.description - self.temperatureLabel.text = "\(weatherData.temperature) °C" + let celsiusTemp = round(weatherData.temperature - 273.15) + + self.temperatureLabel.text = "\(celsiusTemp) °C" // 아이콘 이미지를 표시 if let iconUrl = URL(string: weatherData.iconUrl) { diff --git a/Podfile b/Podfile deleted file mode 100644 index bbf389f..0000000 --- a/Podfile +++ /dev/null @@ -1,11 +0,0 @@ -# Uncomment the next line to define a global platform for your project -platform :ios, '13.0' - -target 'DiaryApp' do - use_frameworks! - - # Pods for DiaryApp -pod 'Alamofire', '~> 5.2' -pod 'SwiftyJSON', '~> 5.0' - -end diff --git a/Podfile.lock b/Podfile.lock deleted file mode 100644 index eea3d86..0000000 --- a/Podfile.lock +++ /dev/null @@ -1,20 +0,0 @@ -PODS: - - Alamofire (5.8.0) - - SwiftyJSON (5.0.1) - -DEPENDENCIES: - - Alamofire (~> 5.2) - - SwiftyJSON (~> 5.0) - -SPEC REPOS: - trunk: - - Alamofire - - SwiftyJSON - -SPEC CHECKSUMS: - Alamofire: 0e92e751b3e9e66d7982db43919d01f313b8eb91 - SwiftyJSON: 2f33a42c6fbc52764d96f13368585094bfd8aa5e - -PODFILE CHECKSUM: 5e61afd8812c9454d63f39ebb91e91b56a2d87b4 - -COCOAPODS: 1.12.1 diff --git a/Pods/Alamofire/LICENSE b/Pods/Alamofire/LICENSE deleted file mode 100644 index cae030a..0000000 --- a/Pods/Alamofire/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Pods/Alamofire/README.md b/Pods/Alamofire/README.md deleted file mode 100644 index b0ba4d5..0000000 --- a/Pods/Alamofire/README.md +++ /dev/null @@ -1,227 +0,0 @@ -![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/AlamofireLogo.png) - -[![Swift](https://img.shields.io/badge/Swift-5.5_5.6_5.7_5.8-orange?style=flat-square)](https://img.shields.io/badge/Swift-5.5_5.6_5.7_5.8-Orange?style=flat-square) -[![Platforms](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-yellowgreen?style=flat-square)](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-Green?style=flat-square) -[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg?style=flat-square)](https://img.shields.io/cocoapods/v/Alamofire.svg) -[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat-square)](https://github.com/Carthage/Carthage) -[![Swift Package Manager](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square)](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square) -[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat-square)](https://twitter.com/AlamofireSF) -[![Swift Forums](https://img.shields.io/badge/Swift_Forums-Alamofire-orange?style=flat-square)](https://forums.swift.org/c/related-projects/alamofire/37) - -Alamofire is an HTTP networking library written in Swift. - -- [Features](#features) -- [Component Libraries](#component-libraries) -- [Requirements](#requirements) -- [Migration Guides](#migration-guides) -- [Communication](#communication) -- [Installation](#installation) -- [Contributing](#contributing) -- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire) - - [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) - - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) - - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) - - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) -- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) - - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#sessiondelegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) - - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests-with-requestinterceptor) - - **Model Objects -** [Custom Response Handlers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#customizing-response-handlers) - - **Advanced Concurrency -** [Swift Concurrency](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-swift-concurrency) and [Combine](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-combine) - - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) -- [Open Radars](#open-radars) -- [FAQ](#faq) -- [Credits](#credits) -- [Donations](#donations) -- [License](#license) - -## Features - -- [x] Chainable Request / Response Methods -- [x] Swift Concurrency Support Back to iOS 13, macOS 10.15, tvOS 13, and watchOS 6. -- [x] Combine Support -- [x] URL / JSON Parameter Encoding -- [x] Upload File / Data / Stream / MultipartFormData -- [x] Download File using Request or Resume Data -- [x] Authentication with `URLCredential` -- [x] HTTP Response Validation -- [x] Upload and Download Progress Closures with Progress -- [x] cURL Command Output -- [x] Dynamically Adapt and Retry Requests -- [x] TLS Certificate and Public Key Pinning -- [x] Network Reachability -- [x] Comprehensive Unit and Integration Test Coverage -- [x] [Complete Documentation](https://alamofire.github.io/Alamofire) - -## Component Libraries - -In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. - -- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache, and a priority-based image downloading system. -- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. - -## Requirements - -| Platform | Minimum Swift Version | Installation | Status | -| --- | --- | --- | --- | -| iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ | 5.5 | [CocoaPods](#cocoapods), [Carthage](#carthage), [Swift Package Manager](#swift-package-manager), [Manual](#manually) | Fully Tested | -| Linux | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | -| Windows | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | - -#### Known Issues on Linux and Windows - -Alamofire builds on Linux and Windows but there are missing features and many issues in the underlying `swift-corelibs-foundation` that prevent full functionality and may cause crashes. These include: -- `ServerTrustManager` and associated certificate functionality is unavailable, so there is no certificate pinning and no client certificate support. -- Various methods of HTTP authentication may crash, including HTTP Basic and HTTP Digest. Crashes may occur if responses contain server challenges. -- Cache control through `CachedResponseHandler` and associated APIs is unavailable, as the underlying delegate methods aren't called. -- `URLSessionTaskMetrics` are never gathered. - -Due to these issues, Alamofire is unsupported on Linux and Windows. Please report any crashes to the [Swift bug reporter](https://bugs.swift.org). - -## Migration Guides - -- [Alamofire 5.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md) -- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) -- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) -- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) - -## Communication -- If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. -- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. -- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). -- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). -- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). -- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better! - -## Installation - -### CocoaPods - -[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: - -```ruby -pod 'Alamofire' -``` - -### Carthage - -[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: - -```ogdl -github "Alamofire/Alamofire" -``` - -### Swift Package Manager - -The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. - -Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. - -```swift -dependencies: [ - .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.6.4")) -] -``` - -### Manually - -If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. - -#### Embedded Framework - -- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: - - ```bash - $ git init - ``` - -- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: - - ```bash - $ git submodule add https://github.com/Alamofire/Alamofire.git - ``` - -- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. - - > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - -- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. -- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. -- In the tab bar at the top of that window, open the "General" panel. -- Click on the `+` button under the "Embedded Binaries" section. -- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. - - > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - -- Select the top `Alamofire.framework` for iOS and the bottom one for macOS. - - > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS`, or `Alamofire watchOS`. - -- And that's it! - - > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. - -## Contributing - -Before contributing to Alamofire, please read the instructions detailed in our [contribution guide](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md). - -## Open Radars - -The following radars have some effect on the current implementation of Alamofire. - -- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in the test case -- `rdar://26870455` - Background URL Session Configurations do not work in the simulator -- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` - -## Resolved Radars - -The following radars have been resolved over time after being filed against the Alamofire project. - -- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage. - - (Resolved): 9/1/17 in Xcode 9 beta 6. -- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ - - (Resolved): Just add `CFNetwork` to your linked frameworks. -- `FB7624529` - `urlSession(_:task:didFinishCollecting:)` never called on watchOS - - (Resolved): Metrics now collected on watchOS 7+. - -## FAQ - -### What's the origin of the name Alamofire? - -Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. - -## Credits - -Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. - -### Security Disclosure - -If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. - -## Sponsorship - -The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. -Registering will allow Foundation members to gain some legal protections and also allow us to put donations to use, tax-free. -Sponsoring the ASF will enable us to: - -- Pay our yearly legal fees to keep the non-profit in good status -- Pay for our mail servers to help us stay on top of all questions and security issues -- Potentially fund test servers to make it easier for us to test the edge cases -- Potentially fund developers to work on one of our projects full-time - -The community adoption of the ASF libraries has been amazing. -We are greatly humbled by your enthusiasm around the projects and want to continue to do everything we can to move the needle forward. -With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. -If you use any of our libraries for work, see if your employers would be interested in donating. -Any amount you can donate, whether once or monthly, to help us reach our goal would be greatly appreciated. - -[Sponsor Alamofire](https://github.com/sponsors/Alamofire) - -## Supporters - -[MacStadium](https://macstadium.com) provides Alamofire with a free, hosted Mac mini. - -![Powered by MacStadium](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/MacStadiumLogo.png) - -## License - -Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/Pods/Alamofire/Source/AFError.swift b/Pods/Alamofire/Source/AFError.swift deleted file mode 100644 index 82a75b5..0000000 --- a/Pods/Alamofire/Source/AFError.swift +++ /dev/null @@ -1,874 +0,0 @@ -// -// AFError.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -#if canImport(Security) -import Security -#endif - -/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with -/// their own associated reasons. -public enum AFError: Error { - /// The underlying reason the `.multipartEncodingFailed` error occurred. - public enum MultipartEncodingFailureReason { - /// The `fileURL` provided for reading an encodable body part isn't a file `URL`. - case bodyPartURLInvalid(url: URL) - /// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension. - case bodyPartFilenameInvalid(in: URL) - /// The file at the `fileURL` provided was not reachable. - case bodyPartFileNotReachable(at: URL) - /// Attempting to check the reachability of the `fileURL` provided threw an error. - case bodyPartFileNotReachableWithError(atURL: URL, error: Error) - /// The file at the `fileURL` provided is actually a directory. - case bodyPartFileIsDirectory(at: URL) - /// The size of the file at the `fileURL` provided was not returned by the system. - case bodyPartFileSizeNotAvailable(at: URL) - /// The attempt to find the size of the file at the `fileURL` provided threw an error. - case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) - /// An `InputStream` could not be created for the provided `fileURL`. - case bodyPartInputStreamCreationFailed(for: URL) - /// An `OutputStream` could not be created when attempting to write the encoded data to disk. - case outputStreamCreationFailed(for: URL) - /// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`. - case outputStreamFileAlreadyExists(at: URL) - /// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`. - case outputStreamURLInvalid(url: URL) - /// The attempt to write the encoded body data to disk failed with an underlying error. - case outputStreamWriteFailed(error: Error) - /// The attempt to read an encoded body part `InputStream` failed with underlying system error. - case inputStreamReadFailed(error: Error) - } - - /// Represents unexpected input stream length that occur when encoding the `MultipartFormData`. Instances will be - /// embedded within an `AFError.multipartEncodingFailed` `.inputStreamReadFailed` case. - public struct UnexpectedInputStreamLength: Error { - /// The expected byte count to read. - public var bytesExpected: UInt64 - /// The actual byte count read. - public var bytesRead: UInt64 - } - - /// The underlying reason the `.parameterEncodingFailed` error occurred. - public enum ParameterEncodingFailureReason { - /// The `URLRequest` did not have a `URL` to encode. - case missingURL - /// JSON serialization failed with an underlying system error during the encoding process. - case jsonEncodingFailed(error: Error) - /// Custom parameter encoding failed due to the associated `Error`. - case customEncodingFailed(error: Error) - } - - /// The underlying reason the `.parameterEncoderFailed` error occurred. - public enum ParameterEncoderFailureReason { - /// Possible missing components. - public enum RequiredComponent { - /// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding. - case url - /// The `HTTPMethod` could not be extracted from the passed `URLRequest`. - case httpMethod(rawValue: String) - } - - /// A `RequiredComponent` was missing during encoding. - case missingRequiredComponent(RequiredComponent) - /// The underlying encoder failed with the associated error. - case encoderFailed(error: Error) - } - - /// The underlying reason the `.responseValidationFailed` error occurred. - public enum ResponseValidationFailureReason { - /// The data file containing the server response did not exist. - case dataFileNil - /// The data file containing the server response at the associated `URL` could not be read. - case dataFileReadFailed(at: URL) - /// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a - /// wildcard type. - case missingContentType(acceptableContentTypes: [String]) - /// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`. - case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) - /// The response status code was not acceptable. - case unacceptableStatusCode(code: Int) - /// Custom response validation failed due to the associated `Error`. - case customValidationFailed(error: Error) - } - - /// The underlying reason the response serialization error occurred. - public enum ResponseSerializationFailureReason { - /// The server response contained no data or the data was zero length. - case inputDataNilOrZeroLength - /// The file containing the server response did not exist. - case inputFileNil - /// The file containing the server response could not be read from the associated `URL`. - case inputFileReadFailed(at: URL) - /// String serialization failed using the provided `String.Encoding`. - case stringSerializationFailed(encoding: String.Encoding) - /// JSON serialization failed with an underlying system error. - case jsonSerializationFailed(error: Error) - /// A `DataDecoder` failed to decode the response due to the associated `Error`. - case decodingFailed(error: Error) - /// A custom response serializer failed due to the associated `Error`. - case customSerializationFailed(error: Error) - /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type. - case invalidEmptyResponse(type: String) - } - - #if canImport(Security) - /// Underlying reason a server trust evaluation error occurred. - public enum ServerTrustFailureReason { - /// The output of a server trust evaluation. - public struct Output { - /// The host for which the evaluation was performed. - public let host: String - /// The `SecTrust` value which was evaluated. - public let trust: SecTrust - /// The `OSStatus` of evaluation operation. - public let status: OSStatus - /// The result of the evaluation operation. - public let result: SecTrustResultType - - /// Creates an `Output` value from the provided values. - init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) { - self.host = host - self.trust = trust - self.status = status - self.result = result - } - } - - /// No `ServerTrustEvaluator` was found for the associated host. - case noRequiredEvaluator(host: String) - /// No certificates were found with which to perform the trust evaluation. - case noCertificatesFound - /// No public keys were found with which to perform the trust evaluation. - case noPublicKeysFound - /// During evaluation, application of the associated `SecPolicy` failed. - case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus) - /// During evaluation, setting the associated anchor certificates failed. - case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate]) - /// During evaluation, creation of the revocation policy failed. - case revocationPolicyCreationFailed - /// `SecTrust` evaluation failed with the associated `Error`, if one was produced. - case trustEvaluationFailed(error: Error?) - /// Default evaluation failed with the associated `Output`. - case defaultEvaluationFailed(output: Output) - /// Host validation failed with the associated `Output`. - case hostValidationFailed(output: Output) - /// Revocation check failed with the associated `Output` and options. - case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options) - /// Certificate pinning failed. - case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate]) - /// Public key pinning failed. - case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey]) - /// Custom server trust evaluation failed due to the associated `Error`. - case customEvaluationFailed(error: Error) - } - #endif - - /// The underlying reason the `.urlRequestValidationFailed` - public enum URLRequestValidationFailureReason { - /// URLRequest with GET method had body data. - case bodyDataInGETRequest(Data) - } - - /// `UploadableConvertible` threw an error in `createUploadable()`. - case createUploadableFailed(error: Error) - /// `URLRequestConvertible` threw an error in `asURLRequest()`. - case createURLRequestFailed(error: Error) - /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL. - case downloadedFileMoveFailed(error: Error, source: URL, destination: URL) - /// `Request` was explicitly cancelled. - case explicitlyCancelled - /// `URLConvertible` type failed to create a valid `URL`. - case invalidURL(url: URLConvertible) - /// Multipart form encoding failed. - case multipartEncodingFailed(reason: MultipartEncodingFailureReason) - /// `ParameterEncoding` threw an error during the encoding process. - case parameterEncodingFailed(reason: ParameterEncodingFailureReason) - /// `ParameterEncoder` threw an error while running the encoder. - case parameterEncoderFailed(reason: ParameterEncoderFailureReason) - /// `RequestAdapter` threw an error during adaptation. - case requestAdaptationFailed(error: Error) - /// `RequestRetrier` threw an error during the request retry process. - case requestRetryFailed(retryError: Error, originalError: Error) - /// Response validation failed. - case responseValidationFailed(reason: ResponseValidationFailureReason) - /// Response serialization failed. - case responseSerializationFailed(reason: ResponseSerializationFailureReason) - #if canImport(Security) - /// `ServerTrustEvaluating` instance threw an error during trust evaluation. - case serverTrustEvaluationFailed(reason: ServerTrustFailureReason) - #endif - /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope. - case sessionDeinitialized - /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`. - case sessionInvalidated(error: Error?) - /// `URLSessionTask` completed with error. - case sessionTaskFailed(error: Error) - /// `URLRequest` failed validation. - case urlRequestValidationFailed(reason: URLRequestValidationFailureReason) -} - -extension Error { - /// Returns the instance cast as an `AFError`. - public var asAFError: AFError? { - self as? AFError - } - - /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown. - public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError { - guard let afError = self as? AFError else { - fatalError(message(), file: file, line: line) - } - return afError - } - - /// Casts the instance as `AFError` or returns `defaultAFError` - func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError { - self as? AFError ?? defaultAFError() - } -} - -// MARK: - Error Booleans - -extension AFError { - /// Returns whether the instance is `.sessionDeinitialized`. - public var isSessionDeinitializedError: Bool { - if case .sessionDeinitialized = self { return true } - return false - } - - /// Returns whether the instance is `.sessionInvalidated`. - public var isSessionInvalidatedError: Bool { - if case .sessionInvalidated = self { return true } - return false - } - - /// Returns whether the instance is `.explicitlyCancelled`. - public var isExplicitlyCancelledError: Bool { - if case .explicitlyCancelled = self { return true } - return false - } - - /// Returns whether the instance is `.invalidURL`. - public var isInvalidURLError: Bool { - if case .invalidURL = self { return true } - return false - } - - /// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isParameterEncodingError: Bool { - if case .parameterEncodingFailed = self { return true } - return false - } - - /// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isParameterEncoderError: Bool { - if case .parameterEncoderFailed = self { return true } - return false - } - - /// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError` - /// properties will contain the associated values. - public var isMultipartEncodingError: Bool { - if case .multipartEncodingFailed = self { return true } - return false - } - - /// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isRequestAdaptationError: Bool { - if case .requestAdaptationFailed = self { return true } - return false - } - - /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`, - /// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values. - public var isResponseValidationError: Bool { - if case .responseValidationFailed = self { return true } - return false - } - - /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and - /// `underlyingError` properties will contain the associated values. - public var isResponseSerializationError: Bool { - if case .responseSerializationFailed = self { return true } - return false - } - - #if canImport(Security) - /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isServerTrustEvaluationError: Bool { - if case .serverTrustEvaluationFailed = self { return true } - return false - } - #endif - - /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isRequestRetryError: Bool { - if case .requestRetryFailed = self { return true } - return false - } - - /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isCreateUploadableError: Bool { - if case .createUploadableFailed = self { return true } - return false - } - - /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isCreateURLRequestError: Bool { - if case .createURLRequestFailed = self { return true } - return false - } - - /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will - /// contain the associated values. - public var isDownloadedFileMoveError: Bool { - if case .downloadedFileMoveFailed = self { return true } - return false - } - - /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isSessionTaskError: Bool { - if case .sessionTaskFailed = self { return true } - return false - } -} - -// MARK: - Convenience Properties - -extension AFError { - /// The `URLConvertible` associated with the error. - public var urlConvertible: URLConvertible? { - guard case let .invalidURL(url) = self else { return nil } - return url - } - - /// The `URL` associated with the error. - public var url: URL? { - guard case let .multipartEncodingFailed(reason) = self else { return nil } - return reason.url - } - - /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`, - /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`, - /// `.responseSerializationFailed`, `.requestRetryFailed` errors. - public var underlyingError: Error? { - switch self { - case let .multipartEncodingFailed(reason): - return reason.underlyingError - case let .parameterEncodingFailed(reason): - return reason.underlyingError - case let .parameterEncoderFailed(reason): - return reason.underlyingError - case let .requestAdaptationFailed(error): - return error - case let .requestRetryFailed(retryError, _): - return retryError - case let .responseValidationFailed(reason): - return reason.underlyingError - case let .responseSerializationFailed(reason): - return reason.underlyingError - #if canImport(Security) - case let .serverTrustEvaluationFailed(reason): - return reason.underlyingError - #endif - case let .sessionInvalidated(error): - return error - case let .createUploadableFailed(error): - return error - case let .createURLRequestFailed(error): - return error - case let .downloadedFileMoveFailed(error, _, _): - return error - case let .sessionTaskFailed(error): - return error - case .explicitlyCancelled, - .invalidURL, - .sessionDeinitialized, - .urlRequestValidationFailed: - return nil - } - } - - /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. - public var acceptableContentTypes: [String]? { - guard case let .responseValidationFailed(reason) = self else { return nil } - return reason.acceptableContentTypes - } - - /// The response `Content-Type` of a `.responseValidationFailed` error. - public var responseContentType: String? { - guard case let .responseValidationFailed(reason) = self else { return nil } - return reason.responseContentType - } - - /// The response code of a `.responseValidationFailed` error. - public var responseCode: Int? { - guard case let .responseValidationFailed(reason) = self else { return nil } - return reason.responseCode - } - - /// The `String.Encoding` associated with a failed `.stringResponse()` call. - public var failedStringEncoding: String.Encoding? { - guard case let .responseSerializationFailed(reason) = self else { return nil } - return reason.failedStringEncoding - } - - /// The `source` URL of a `.downloadedFileMoveFailed` error. - public var sourceURL: URL? { - guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil } - return source - } - - /// The `destination` URL of a `.downloadedFileMoveFailed` error. - public var destinationURL: URL? { - guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil } - return destination - } - - #if canImport(Security) - /// The download resume data of any underlying network error. Only produced by `DownloadRequest`s. - public var downloadResumeData: Data? { - (underlyingError as? URLError)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data - } - #endif -} - -extension AFError.ParameterEncodingFailureReason { - var underlyingError: Error? { - switch self { - case let .jsonEncodingFailed(error), - let .customEncodingFailed(error): - return error - case .missingURL: - return nil - } - } -} - -extension AFError.ParameterEncoderFailureReason { - var underlyingError: Error? { - switch self { - case let .encoderFailed(error): - return error - case .missingRequiredComponent: - return nil - } - } -} - -extension AFError.MultipartEncodingFailureReason { - var url: URL? { - switch self { - case let .bodyPartURLInvalid(url), - let .bodyPartFilenameInvalid(url), - let .bodyPartFileNotReachable(url), - let .bodyPartFileIsDirectory(url), - let .bodyPartFileSizeNotAvailable(url), - let .bodyPartInputStreamCreationFailed(url), - let .outputStreamCreationFailed(url), - let .outputStreamFileAlreadyExists(url), - let .outputStreamURLInvalid(url), - let .bodyPartFileNotReachableWithError(url, _), - let .bodyPartFileSizeQueryFailedWithError(url, _): - return url - case .outputStreamWriteFailed, - .inputStreamReadFailed: - return nil - } - } - - var underlyingError: Error? { - switch self { - case let .bodyPartFileNotReachableWithError(_, error), - let .bodyPartFileSizeQueryFailedWithError(_, error), - let .outputStreamWriteFailed(error), - let .inputStreamReadFailed(error): - return error - case .bodyPartURLInvalid, - .bodyPartFilenameInvalid, - .bodyPartFileNotReachable, - .bodyPartFileIsDirectory, - .bodyPartFileSizeNotAvailable, - .bodyPartInputStreamCreationFailed, - .outputStreamCreationFailed, - .outputStreamFileAlreadyExists, - .outputStreamURLInvalid: - return nil - } - } -} - -extension AFError.ResponseValidationFailureReason { - var acceptableContentTypes: [String]? { - switch self { - case let .missingContentType(types), - let .unacceptableContentType(types, _): - return types - case .dataFileNil, - .dataFileReadFailed, - .unacceptableStatusCode, - .customValidationFailed: - return nil - } - } - - var responseContentType: String? { - switch self { - case let .unacceptableContentType(_, responseType): - return responseType - case .dataFileNil, - .dataFileReadFailed, - .missingContentType, - .unacceptableStatusCode, - .customValidationFailed: - return nil - } - } - - var responseCode: Int? { - switch self { - case let .unacceptableStatusCode(code): - return code - case .dataFileNil, - .dataFileReadFailed, - .missingContentType, - .unacceptableContentType, - .customValidationFailed: - return nil - } - } - - var underlyingError: Error? { - switch self { - case let .customValidationFailed(error): - return error - case .dataFileNil, - .dataFileReadFailed, - .missingContentType, - .unacceptableContentType, - .unacceptableStatusCode: - return nil - } - } -} - -extension AFError.ResponseSerializationFailureReason { - var failedStringEncoding: String.Encoding? { - switch self { - case let .stringSerializationFailed(encoding): - return encoding - case .inputDataNilOrZeroLength, - .inputFileNil, - .inputFileReadFailed(_), - .jsonSerializationFailed(_), - .decodingFailed(_), - .customSerializationFailed(_), - .invalidEmptyResponse: - return nil - } - } - - var underlyingError: Error? { - switch self { - case let .jsonSerializationFailed(error), - let .decodingFailed(error), - let .customSerializationFailed(error): - return error - case .inputDataNilOrZeroLength, - .inputFileNil, - .inputFileReadFailed, - .stringSerializationFailed, - .invalidEmptyResponse: - return nil - } - } -} - -#if canImport(Security) -extension AFError.ServerTrustFailureReason { - var output: AFError.ServerTrustFailureReason.Output? { - switch self { - case let .defaultEvaluationFailed(output), - let .hostValidationFailed(output), - let .revocationCheckFailed(output, _): - return output - case .noRequiredEvaluator, - .noCertificatesFound, - .noPublicKeysFound, - .policyApplicationFailed, - .settingAnchorCertificatesFailed, - .revocationPolicyCreationFailed, - .trustEvaluationFailed, - .certificatePinningFailed, - .publicKeyPinningFailed, - .customEvaluationFailed: - return nil - } - } - - var underlyingError: Error? { - switch self { - case let .customEvaluationFailed(error): - return error - case let .trustEvaluationFailed(error): - return error - case .noRequiredEvaluator, - .noCertificatesFound, - .noPublicKeysFound, - .policyApplicationFailed, - .settingAnchorCertificatesFailed, - .revocationPolicyCreationFailed, - .defaultEvaluationFailed, - .hostValidationFailed, - .revocationCheckFailed, - .certificatePinningFailed, - .publicKeyPinningFailed: - return nil - } - } -} -#endif - -// MARK: - Error Descriptions - -extension AFError: LocalizedError { - public var errorDescription: String? { - switch self { - case .explicitlyCancelled: - return "Request explicitly cancelled." - case let .invalidURL(url): - return "URL is not valid: \(url)" - case let .parameterEncodingFailed(reason): - return reason.localizedDescription - case let .parameterEncoderFailed(reason): - return reason.localizedDescription - case let .multipartEncodingFailed(reason): - return reason.localizedDescription - case let .requestAdaptationFailed(error): - return "Request adaption failed with error: \(error.localizedDescription)" - case let .responseValidationFailed(reason): - return reason.localizedDescription - case let .responseSerializationFailed(reason): - return reason.localizedDescription - case let .requestRetryFailed(retryError, originalError): - return """ - Request retry failed with retry error: \(retryError.localizedDescription), \ - original error: \(originalError.localizedDescription) - """ - case .sessionDeinitialized: - return """ - Session was invalidated without error, so it was likely deinitialized unexpectedly. \ - Be sure to retain a reference to your Session for the duration of your requests. - """ - case let .sessionInvalidated(error): - return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")" - #if canImport(Security) - case let .serverTrustEvaluationFailed(reason): - return "Server trust evaluation failed due to reason: \(reason.localizedDescription)" - #endif - case let .urlRequestValidationFailed(reason): - return "URLRequest validation failed due to reason: \(reason.localizedDescription)" - case let .createUploadableFailed(error): - return "Uploadable creation failed with error: \(error.localizedDescription)" - case let .createURLRequestFailed(error): - return "URLRequest creation failed with error: \(error.localizedDescription)" - case let .downloadedFileMoveFailed(error, source, destination): - return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)" - case let .sessionTaskFailed(error): - return "URLSessionTask failed with error: \(error.localizedDescription)" - } - } -} - -extension AFError.ParameterEncodingFailureReason { - var localizedDescription: String { - switch self { - case .missingURL: - return "URL request to encode was missing a URL" - case let .jsonEncodingFailed(error): - return "JSON could not be encoded because of error:\n\(error.localizedDescription)" - case let .customEncodingFailed(error): - return "Custom parameter encoder failed with error: \(error.localizedDescription)" - } - } -} - -extension AFError.ParameterEncoderFailureReason { - var localizedDescription: String { - switch self { - case let .missingRequiredComponent(component): - return "Encoding failed due to a missing request component: \(component)" - case let .encoderFailed(error): - return "The underlying encoder failed with the error: \(error)" - } - } -} - -extension AFError.MultipartEncodingFailureReason { - var localizedDescription: String { - switch self { - case let .bodyPartURLInvalid(url): - return "The URL provided is not a file URL: \(url)" - case let .bodyPartFilenameInvalid(url): - return "The URL provided does not have a valid filename: \(url)" - case let .bodyPartFileNotReachable(url): - return "The URL provided is not reachable: \(url)" - case let .bodyPartFileNotReachableWithError(url, error): - return """ - The system returned an error while checking the provided URL for reachability. - URL: \(url) - Error: \(error) - """ - case let .bodyPartFileIsDirectory(url): - return "The URL provided is a directory: \(url)" - case let .bodyPartFileSizeNotAvailable(url): - return "Could not fetch the file size from the provided URL: \(url)" - case let .bodyPartFileSizeQueryFailedWithError(url, error): - return """ - The system returned an error while attempting to fetch the file size from the provided URL. - URL: \(url) - Error: \(error) - """ - case let .bodyPartInputStreamCreationFailed(url): - return "Failed to create an InputStream for the provided URL: \(url)" - case let .outputStreamCreationFailed(url): - return "Failed to create an OutputStream for URL: \(url)" - case let .outputStreamFileAlreadyExists(url): - return "A file already exists at the provided URL: \(url)" - case let .outputStreamURLInvalid(url): - return "The provided OutputStream URL is invalid: \(url)" - case let .outputStreamWriteFailed(error): - return "OutputStream write failed with error: \(error)" - case let .inputStreamReadFailed(error): - return "InputStream read failed with error: \(error)" - } - } -} - -extension AFError.ResponseSerializationFailureReason { - var localizedDescription: String { - switch self { - case .inputDataNilOrZeroLength: - return "Response could not be serialized, input data was nil or zero length." - case .inputFileNil: - return "Response could not be serialized, input file was nil." - case let .inputFileReadFailed(url): - return "Response could not be serialized, input file could not be read: \(url)." - case let .stringSerializationFailed(encoding): - return "String could not be serialized with encoding: \(encoding)." - case let .jsonSerializationFailed(error): - return "JSON could not be serialized because of error:\n\(error.localizedDescription)" - case let .invalidEmptyResponse(type): - return """ - Empty response could not be serialized to type: \(type). \ - Use Empty as the expected type for such responses. - """ - case let .decodingFailed(error): - return "Response could not be decoded because of error:\n\(error.localizedDescription)" - case let .customSerializationFailed(error): - return "Custom response serializer failed with error:\n\(error.localizedDescription)" - } - } -} - -extension AFError.ResponseValidationFailureReason { - var localizedDescription: String { - switch self { - case .dataFileNil: - return "Response could not be validated, data file was nil." - case let .dataFileReadFailed(url): - return "Response could not be validated, data file could not be read: \(url)." - case let .missingContentType(types): - return """ - Response Content-Type was missing and acceptable content types \ - (\(types.joined(separator: ","))) do not match "*/*". - """ - case let .unacceptableContentType(acceptableTypes, responseType): - return """ - Response Content-Type "\(responseType)" does not match any acceptable types: \ - \(acceptableTypes.joined(separator: ",")). - """ - case let .unacceptableStatusCode(code): - return "Response status code was unacceptable: \(code)." - case let .customValidationFailed(error): - return "Custom response validation failed with error: \(error.localizedDescription)" - } - } -} - -#if canImport(Security) -extension AFError.ServerTrustFailureReason { - var localizedDescription: String { - switch self { - case let .noRequiredEvaluator(host): - return "A ServerTrustEvaluating value is required for host \(host) but none was found." - case .noCertificatesFound: - return "No certificates were found or provided for evaluation." - case .noPublicKeysFound: - return "No public keys were found or provided for evaluation." - case .policyApplicationFailed: - return "Attempting to set a SecPolicy failed." - case .settingAnchorCertificatesFailed: - return "Attempting to set the provided certificates as anchor certificates failed." - case .revocationPolicyCreationFailed: - return "Attempting to create a revocation policy failed." - case let .trustEvaluationFailed(error): - return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")" - case let .defaultEvaluationFailed(output): - return "Default evaluation failed for host \(output.host)." - case let .hostValidationFailed(output): - return "Host validation failed for host \(output.host)." - case let .revocationCheckFailed(output, _): - return "Revocation check failed for host \(output.host)." - case let .certificatePinningFailed(host, _, _, _): - return "Certificate pinning failed for host \(host)." - case let .publicKeyPinningFailed(host, _, _, _): - return "Public key pinning failed for host \(host)." - case let .customEvaluationFailed(error): - return "Custom trust evaluation failed with error: \(error.localizedDescription)" - } - } -} -#endif - -extension AFError.URLRequestValidationFailureReason { - var localizedDescription: String { - switch self { - case let .bodyDataInGETRequest(data): - return """ - Invalid URLRequest: Requests with GET method cannot have body data: - \(String(decoding: data, as: UTF8.self)) - """ - } - } -} diff --git a/Pods/Alamofire/Source/Alamofire.swift b/Pods/Alamofire/Source/Alamofire.swift deleted file mode 100644 index c99fe49..0000000 --- a/Pods/Alamofire/Source/Alamofire.swift +++ /dev/null @@ -1,40 +0,0 @@ -// -// Alamofire.swift -// -// Copyright (c) 2014-2021 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Dispatch -import Foundation -#if canImport(FoundationNetworking) -@_exported import FoundationNetworking -#endif - -// Enforce minimum Swift version for all platforms and build systems. -#if swift(<5.5) -#error("Alamofire doesn't support Swift versions below 5.5.") -#endif - -/// Reference to `Session.default` for quick bootstrapping and examples. -public let AF = Session.default - -/// Current Alamofire version. Necessary since SPM doesn't use dynamic libraries. Plus this will be more accurate. -let version = "5.8.0" diff --git a/Pods/Alamofire/Source/AlamofireExtended.swift b/Pods/Alamofire/Source/AlamofireExtended.swift deleted file mode 100644 index 280c6de..0000000 --- a/Pods/Alamofire/Source/AlamofireExtended.swift +++ /dev/null @@ -1,61 +0,0 @@ -// -// AlamofireExtended.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -/// Type that acts as a generic extension point for all `AlamofireExtended` types. -public struct AlamofireExtension { - /// Stores the type or meta-type of any extended type. - public private(set) var type: ExtendedType - - /// Create an instance from the provided value. - /// - /// - Parameter type: Instance being extended. - public init(_ type: ExtendedType) { - self.type = type - } -} - -/// Protocol describing the `af` extension points for Alamofire extended types. -public protocol AlamofireExtended { - /// Type being extended. - associatedtype ExtendedType - - /// Static Alamofire extension point. - static var af: AlamofireExtension.Type { get set } - /// Instance Alamofire extension point. - var af: AlamofireExtension { get set } -} - -extension AlamofireExtended { - /// Static Alamofire extension point. - public static var af: AlamofireExtension.Type { - get { AlamofireExtension.self } - set {} - } - - /// Instance Alamofire extension point. - public var af: AlamofireExtension { - get { AlamofireExtension(self) } - set {} - } -} diff --git a/Pods/Alamofire/Source/AuthenticationInterceptor.swift b/Pods/Alamofire/Source/AuthenticationInterceptor.swift deleted file mode 100644 index c3a3f31..0000000 --- a/Pods/Alamofire/Source/AuthenticationInterceptor.swift +++ /dev/null @@ -1,403 +0,0 @@ -// -// AuthenticationInterceptor.swift -// -// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Types adopting the `AuthenticationCredential` protocol can be used to authenticate `URLRequest`s. -/// -/// One common example of an `AuthenticationCredential` is an OAuth2 credential containing an access token used to -/// authenticate all requests on behalf of a user. The access token generally has an expiration window of 60 minutes -/// which will then require a refresh of the credential using the refresh token to generate a new access token. -public protocol AuthenticationCredential { - /// Whether the credential requires a refresh. This property should always return `true` when the credential is - /// expired. It is also wise to consider returning `true` when the credential will expire in several seconds or - /// minutes depending on the expiration window of the credential. - /// - /// For example, if the credential is valid for 60 minutes, then it would be wise to return `true` when the - /// credential is only valid for 5 minutes or less. That ensures the credential will not expire as it is passed - /// around backend services. - var requiresRefresh: Bool { get } -} - -// MARK: - - -/// Types adopting the `Authenticator` protocol can be used to authenticate `URLRequest`s with an -/// `AuthenticationCredential` as well as refresh the `AuthenticationCredential` when required. -public protocol Authenticator: AnyObject { - /// The type of credential associated with the `Authenticator` instance. - associatedtype Credential: AuthenticationCredential - - /// Applies the `Credential` to the `URLRequest`. - /// - /// In the case of OAuth2, the access token of the `Credential` would be added to the `URLRequest` as a Bearer - /// token to the `Authorization` header. - /// - /// - Parameters: - /// - credential: The `Credential`. - /// - urlRequest: The `URLRequest`. - func apply(_ credential: Credential, to urlRequest: inout URLRequest) - - /// Refreshes the `Credential` and executes the `completion` closure with the `Result` once complete. - /// - /// Refresh can be called in one of two ways. It can be called before the `Request` is actually executed due to - /// a `requiresRefresh` returning `true` during the adapt portion of the `Request` creation process. It can also - /// be triggered by a failed `Request` where the authentication server denied access due to an expired or - /// invalidated access token. - /// - /// In the case of OAuth2, this method would use the refresh token of the `Credential` to generate a new - /// `Credential` using the authentication service. Once complete, the `completion` closure should be called with - /// the new `Credential`, or the error that occurred. - /// - /// In general, if the refresh call fails with certain status codes from the authentication server (commonly a 401), - /// the refresh token in the `Credential` can no longer be used to generate a valid `Credential`. In these cases, - /// you will need to reauthenticate the user with their username / password. - /// - /// Please note, these are just general examples of common use cases. They are not meant to solve your specific - /// authentication server challenges. Please work with your authentication server team to ensure your - /// `Authenticator` logic matches their expectations. - /// - /// - Parameters: - /// - credential: The `Credential` to refresh. - /// - session: The `Session` requiring the refresh. - /// - completion: The closure to be executed once the refresh is complete. - func refresh(_ credential: Credential, for session: Session, completion: @escaping (Result) -> Void) - - /// Determines whether the `URLRequest` failed due to an authentication error based on the `HTTPURLResponse`. - /// - /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `false` - /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then you - /// will need to work with your authentication server team to understand how to identify when this occurs. - /// - /// In the case of OAuth2, where an authentication server can invalidate credentials, you will need to inspect the - /// `HTTPURLResponse` or possibly the `Error` for when this occurs. This is commonly handled by the authentication - /// server returning a 401 status code and some additional header to indicate an OAuth2 failure occurred. - /// - /// It is very important to understand how your authentication server works to be able to implement this correctly. - /// For example, if your authentication server returns a 401 when an OAuth2 error occurs, and your downstream - /// service also returns a 401 when you are not authorized to perform that operation, how do you know which layer - /// of the backend returned you a 401? You do not want to trigger a refresh unless you know your authentication - /// server is actually the layer rejecting the request. Again, work with your authentication server team to understand - /// how to identify an OAuth2 401 error vs. a downstream 401 error to avoid endless refresh loops. - /// - /// - Parameters: - /// - urlRequest: The `URLRequest`. - /// - response: The `HTTPURLResponse`. - /// - error: The `Error`. - /// - /// - Returns: `true` if the `URLRequest` failed due to an authentication error, `false` otherwise. - func didRequest(_ urlRequest: URLRequest, with response: HTTPURLResponse, failDueToAuthenticationError error: Error) -> Bool - - /// Determines whether the `URLRequest` is authenticated with the `Credential`. - /// - /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `true` - /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then - /// read on. - /// - /// When an authentication server can invalidate credentials, it means that you may have a non-expired credential - /// that appears to be valid, but will be rejected by the authentication server when used. Generally when this - /// happens, a number of requests are all sent when the application is foregrounded, and all of them will be - /// rejected by the authentication server in the order they are received. The first failed request will trigger a - /// refresh internally, which will update the credential, and then retry all the queued requests with the new - /// credential. However, it is possible that some of the original requests will not return from the authentication - /// server until the refresh has completed. This is where this method comes in. - /// - /// When the authentication server rejects a credential, we need to check to make sure we haven't refreshed the - /// credential while the request was in flight. If it has already refreshed, then we don't need to trigger an - /// additional refresh. If it hasn't refreshed, then we need to refresh. - /// - /// Now that it is understood how the result of this method is used in the refresh lifecyle, let's walk through how - /// to implement it. You should return `true` in this method if the `URLRequest` is authenticated in a way that - /// matches the values in the `Credential`. In the case of OAuth2, this would mean that the Bearer token in the - /// `Authorization` header of the `URLRequest` matches the access token in the `Credential`. If it matches, then we - /// know the `Credential` was used to authenticate the `URLRequest` and should return `true`. If the Bearer token - /// did not match the access token, then you should return `false`. - /// - /// - Parameters: - /// - urlRequest: The `URLRequest`. - /// - credential: The `Credential`. - /// - /// - Returns: `true` if the `URLRequest` is authenticated with the `Credential`, `false` otherwise. - func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: Credential) -> Bool -} - -// MARK: - - -/// Represents various authentication failures that occur when using the `AuthenticationInterceptor`. All errors are -/// still vended from Alamofire as `AFError` types. The `AuthenticationError` instances will be embedded within -/// `AFError` `.requestAdaptationFailed` or `.requestRetryFailed` cases. -public enum AuthenticationError: Error { - /// The credential was missing so the request could not be authenticated. - case missingCredential - /// The credential was refreshed too many times within the `RefreshWindow`. - case excessiveRefresh -} - -// MARK: - - -/// The `AuthenticationInterceptor` class manages the queuing and threading complexity of authenticating requests. -/// It relies on an `Authenticator` type to handle the actual `URLRequest` authentication and `Credential` refresh. -public class AuthenticationInterceptor: RequestInterceptor where AuthenticatorType: Authenticator { - // MARK: Typealiases - - /// Type of credential used to authenticate requests. - public typealias Credential = AuthenticatorType.Credential - - // MARK: Helper Types - - /// Type that defines a time window used to identify excessive refresh calls. When enabled, prior to executing a - /// refresh, the `AuthenticationInterceptor` compares the timestamp history of previous refresh calls against the - /// `RefreshWindow`. If more refreshes have occurred within the refresh window than allowed, the refresh is - /// cancelled and an `AuthorizationError.excessiveRefresh` error is thrown. - public struct RefreshWindow { - /// `TimeInterval` defining the duration of the time window before the current time in which the number of - /// refresh attempts is compared against `maximumAttempts`. For example, if `interval` is 30 seconds, then the - /// `RefreshWindow` represents the past 30 seconds. If more attempts occurred in the past 30 seconds than - /// `maximumAttempts`, an `.excessiveRefresh` error will be thrown. - public let interval: TimeInterval - - /// Total refresh attempts allowed within `interval` before throwing an `.excessiveRefresh` error. - public let maximumAttempts: Int - - /// Creates a `RefreshWindow` instance from the specified `interval` and `maximumAttempts`. - /// - /// - Parameters: - /// - interval: `TimeInterval` defining the duration of the time window before the current time. - /// - maximumAttempts: The maximum attempts allowed within the `TimeInterval`. - public init(interval: TimeInterval = 30.0, maximumAttempts: Int = 5) { - self.interval = interval - self.maximumAttempts = maximumAttempts - } - } - - private struct AdaptOperation { - let urlRequest: URLRequest - let session: Session - let completion: (Result) -> Void - } - - private enum AdaptResult { - case adapt(Credential) - case doNotAdapt(AuthenticationError) - case adaptDeferred - } - - private struct MutableState { - var credential: Credential? - - var isRefreshing = false - var refreshTimestamps: [TimeInterval] = [] - var refreshWindow: RefreshWindow? - - var adaptOperations: [AdaptOperation] = [] - var requestsToRetry: [(RetryResult) -> Void] = [] - } - - // MARK: Properties - - /// The `Credential` used to authenticate requests. - public var credential: Credential? { - get { $mutableState.credential } - set { $mutableState.credential = newValue } - } - - let authenticator: AuthenticatorType - let queue = DispatchQueue(label: "org.alamofire.authentication.inspector") - - @Protected - private var mutableState: MutableState - - // MARK: Initialization - - /// Creates an `AuthenticationInterceptor` instance from the specified parameters. - /// - /// A `nil` `RefreshWindow` will result in the `AuthenticationInterceptor` not checking for excessive refresh calls. - /// It is recommended to always use a `RefreshWindow` to avoid endless refresh cycles. - /// - /// - Parameters: - /// - authenticator: The `Authenticator` type. - /// - credential: The `Credential` if it exists. `nil` by default. - /// - refreshWindow: The `RefreshWindow` used to identify excessive refresh calls. `RefreshWindow()` by default. - public init(authenticator: AuthenticatorType, - credential: Credential? = nil, - refreshWindow: RefreshWindow? = RefreshWindow()) { - self.authenticator = authenticator - mutableState = MutableState(credential: credential, refreshWindow: refreshWindow) - } - - // MARK: Adapt - - public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - let adaptResult: AdaptResult = $mutableState.write { mutableState in - // Queue the adapt operation if a refresh is already in place. - guard !mutableState.isRefreshing else { - let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) - mutableState.adaptOperations.append(operation) - return .adaptDeferred - } - - // Throw missing credential error is the credential is missing. - guard let credential = mutableState.credential else { - let error = AuthenticationError.missingCredential - return .doNotAdapt(error) - } - - // Queue the adapt operation and trigger refresh operation if credential requires refresh. - guard !credential.requiresRefresh else { - let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) - mutableState.adaptOperations.append(operation) - refresh(credential, for: session, insideLock: &mutableState) - return .adaptDeferred - } - - return .adapt(credential) - } - - switch adaptResult { - case let .adapt(credential): - var authenticatedRequest = urlRequest - authenticator.apply(credential, to: &authenticatedRequest) - completion(.success(authenticatedRequest)) - - case let .doNotAdapt(adaptError): - completion(.failure(adaptError)) - - case .adaptDeferred: - // No-op: adapt operation captured during refresh. - break - } - } - - // MARK: Retry - - public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { - // Do not attempt retry if there was not an original request and response from the server. - guard let urlRequest = request.request, let response = request.response else { - completion(.doNotRetry) - return - } - - // Do not attempt retry unless the `Authenticator` verifies failure was due to authentication error (i.e. 401 status code). - guard authenticator.didRequest(urlRequest, with: response, failDueToAuthenticationError: error) else { - completion(.doNotRetry) - return - } - - // Do not attempt retry if there is no credential. - guard let credential = credential else { - let error = AuthenticationError.missingCredential - completion(.doNotRetryWithError(error)) - return - } - - // Retry the request if the `Authenticator` verifies it was authenticated with a previous credential. - guard authenticator.isRequest(urlRequest, authenticatedWith: credential) else { - completion(.retry) - return - } - - $mutableState.write { mutableState in - mutableState.requestsToRetry.append(completion) - - guard !mutableState.isRefreshing else { return } - - refresh(credential, for: session, insideLock: &mutableState) - } - } - - // MARK: Refresh - - private func refresh(_ credential: Credential, for session: Session, insideLock mutableState: inout MutableState) { - guard !isRefreshExcessive(insideLock: &mutableState) else { - let error = AuthenticationError.excessiveRefresh - handleRefreshFailure(error, insideLock: &mutableState) - return - } - - mutableState.refreshTimestamps.append(ProcessInfo.processInfo.systemUptime) - mutableState.isRefreshing = true - - // Dispatch to queue to hop out of the lock in case authenticator.refresh is implemented synchronously. - queue.async { - self.authenticator.refresh(credential, for: session) { result in - self.$mutableState.write { mutableState in - switch result { - case let .success(credential): - self.handleRefreshSuccess(credential, insideLock: &mutableState) - case let .failure(error): - self.handleRefreshFailure(error, insideLock: &mutableState) - } - } - } - } - } - - private func isRefreshExcessive(insideLock mutableState: inout MutableState) -> Bool { - guard let refreshWindow = mutableState.refreshWindow else { return false } - - let refreshWindowMin = ProcessInfo.processInfo.systemUptime - refreshWindow.interval - - let refreshAttemptsWithinWindow = mutableState.refreshTimestamps.reduce(into: 0) { attempts, refreshTimestamp in - guard refreshWindowMin <= refreshTimestamp else { return } - attempts += 1 - } - - let isRefreshExcessive = refreshAttemptsWithinWindow >= refreshWindow.maximumAttempts - - return isRefreshExcessive - } - - private func handleRefreshSuccess(_ credential: Credential, insideLock mutableState: inout MutableState) { - mutableState.credential = credential - - let adaptOperations = mutableState.adaptOperations - let requestsToRetry = mutableState.requestsToRetry - - mutableState.adaptOperations.removeAll() - mutableState.requestsToRetry.removeAll() - - mutableState.isRefreshing = false - - // Dispatch to queue to hop out of the mutable state lock - queue.async { - adaptOperations.forEach { self.adapt($0.urlRequest, for: $0.session, completion: $0.completion) } - requestsToRetry.forEach { $0(.retry) } - } - } - - private func handleRefreshFailure(_ error: Error, insideLock mutableState: inout MutableState) { - let adaptOperations = mutableState.adaptOperations - let requestsToRetry = mutableState.requestsToRetry - - mutableState.adaptOperations.removeAll() - mutableState.requestsToRetry.removeAll() - - mutableState.isRefreshing = false - - // Dispatch to queue to hop out of the mutable state lock - queue.async { - adaptOperations.forEach { $0.completion(.failure(error)) } - requestsToRetry.forEach { $0(.doNotRetryWithError(error)) } - } - } -} diff --git a/Pods/Alamofire/Source/CachedResponseHandler.swift b/Pods/Alamofire/Source/CachedResponseHandler.swift deleted file mode 100644 index 1371b6e..0000000 --- a/Pods/Alamofire/Source/CachedResponseHandler.swift +++ /dev/null @@ -1,107 +0,0 @@ -// -// CachedResponseHandler.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that handles whether the data task should store the HTTP response in the cache. -public protocol CachedResponseHandler { - /// Determines whether the HTTP response should be stored in the cache. - /// - /// The `completion` closure should be passed one of three possible options: - /// - /// 1. The cached response provided by the server (this is the most common use case). - /// 2. A modified version of the cached response (you may want to modify it in some way before caching). - /// 3. A `nil` value to prevent the cached response from being stored in the cache. - /// - /// - Parameters: - /// - task: The data task whose request resulted in the cached response. - /// - response: The cached response to potentially store in the cache. - /// - completion: The closure to execute containing cached response, a modified response, or `nil`. - func dataTask(_ task: URLSessionDataTask, - willCacheResponse response: CachedURLResponse, - completion: @escaping (CachedURLResponse?) -> Void) -} - -// MARK: - - -/// `ResponseCacher` is a convenience `CachedResponseHandler` making it easy to cache, not cache, or modify a cached -/// response. -public struct ResponseCacher { - /// Defines the behavior of the `ResponseCacher` type. - public enum Behavior { - /// Stores the cached response in the cache. - case cache - /// Prevents the cached response from being stored in the cache. - case doNotCache - /// Modifies the cached response before storing it in the cache. - case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?) - } - - /// Returns a `ResponseCacher` with a `.cache` `Behavior`. - public static let cache = ResponseCacher(behavior: .cache) - /// Returns a `ResponseCacher` with a `.doNotCache` `Behavior`. - public static let doNotCache = ResponseCacher(behavior: .doNotCache) - - /// The `Behavior` of the `ResponseCacher`. - public let behavior: Behavior - - /// Creates a `ResponseCacher` instance from the `Behavior`. - /// - /// - Parameter behavior: The `Behavior`. - public init(behavior: Behavior) { - self.behavior = behavior - } -} - -extension ResponseCacher: CachedResponseHandler { - public func dataTask(_ task: URLSessionDataTask, - willCacheResponse response: CachedURLResponse, - completion: @escaping (CachedURLResponse?) -> Void) { - switch behavior { - case .cache: - completion(response) - case .doNotCache: - completion(nil) - case let .modify(closure): - let response = closure(task, response) - completion(response) - } - } -} - -extension CachedResponseHandler where Self == ResponseCacher { - /// Provides a `ResponseCacher` which caches the response, if allowed. Equivalent to `ResponseCacher.cache`. - public static var cache: ResponseCacher { .cache } - - /// Provides a `ResponseCacher` which does not cache the response. Equivalent to `ResponseCacher.doNotCache`. - public static var doNotCache: ResponseCacher { .doNotCache } - - /// Creates a `ResponseCacher` which modifies the proposed `CachedURLResponse` using the provided closure. - /// - /// - Parameter closure: Closure used to modify the `CachedURLResponse`. - /// - Returns: The `ResponseCacher`. - public static func modify(using closure: @escaping ((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)) -> ResponseCacher { - ResponseCacher(behavior: .modify(closure)) - } -} diff --git a/Pods/Alamofire/Source/Combine.swift b/Pods/Alamofire/Source/Combine.swift deleted file mode 100644 index 416610e..0000000 --- a/Pods/Alamofire/Source/Combine.swift +++ /dev/null @@ -1,655 +0,0 @@ -// -// Combine.swift -// -// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#if !((os(iOS) && (arch(i386) || arch(arm))) || os(Windows) || os(Linux) || os(Android)) - -import Combine -import Dispatch -import Foundation - -// MARK: - DataRequest / UploadRequest - -/// A Combine `Publisher` that publishes the `DataResponse` of the provided `DataRequest`. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -public struct DataResponsePublisher: Publisher { - public typealias Output = DataResponse - public typealias Failure = Never - - private typealias Handler = (@escaping (_ response: DataResponse) -> Void) -> DataRequest - - private let request: DataRequest - private let responseHandler: Handler - - /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. - /// - /// - Parameters: - /// - request: `DataRequest` for which to publish the response. - /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. - /// - serializer: `ResponseSerializer` used to produce the published `DataResponse`. - public init(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer) - where Value == Serializer.SerializedObject { - self.request = request - responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } - } - - /// Creates an instance which will serialize responses using the provided `DataResponseSerializerProtocol`. - /// - /// - Parameters: - /// - request: `DataRequest` for which to publish the response. - /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. - /// - serializer: `DataResponseSerializerProtocol` used to produce the published `DataResponse`. - public init(_ request: DataRequest, - queue: DispatchQueue, - serializer: Serializer) - where Value == Serializer.SerializedObject { - self.request = request - responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } - } - - /// Publishes only the `Result` of the `DataResponse` value. - /// - /// - Returns: The `AnyPublisher` publishing the `Result` value. - public func result() -> AnyPublisher, Never> { - map(\.result).eraseToAnyPublisher() - } - - /// Publishes the `Result` of the `DataResponse` as a single `Value` or fail with the `AFError` instance. - /// - /// - Returns: The `AnyPublisher` publishing the stream. - public func value() -> AnyPublisher { - setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() - } - - public func receive(subscriber: S) where S: Subscriber, DataResponsePublisher.Failure == S.Failure, DataResponsePublisher.Output == S.Input { - subscriber.receive(subscription: Inner(request: request, - responseHandler: responseHandler, - downstream: subscriber)) - } - - private final class Inner: Subscription - where Downstream.Input == Output { - typealias Failure = Downstream.Failure - - @Protected - private var downstream: Downstream? - private let request: DataRequest - private let responseHandler: Handler - - init(request: DataRequest, responseHandler: @escaping Handler, downstream: Downstream) { - self.request = request - self.responseHandler = responseHandler - self.downstream = downstream - } - - func request(_ demand: Subscribers.Demand) { - assert(demand > 0) - - guard let downstream = downstream else { return } - - self.downstream = nil - responseHandler { response in - _ = downstream.receive(response) - downstream.receive(completion: .finished) - }.resume() - } - - func cancel() { - request.cancel() - downstream = nil - } - } -} - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -extension DataResponsePublisher where Value == Data? { - /// Creates an instance which publishes a `DataResponse` value without serialization. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public init(_ request: DataRequest, queue: DispatchQueue) { - self.request = request - responseHandler = { request.response(queue: queue, completionHandler: $0) } - } -} - -extension DataRequest { - /// Creates a `DataResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. - /// - /// - Parameters: - /// - serializer: `ResponseSerializer` used to serialize response `Data`. - /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. - /// - /// - Returns: The `DataResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataResponsePublisher - where Serializer.SerializedObject == T { - DataResponsePublisher(self, queue: queue, serializer: serializer) - } - - /// Creates a `DataResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the - /// response. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. - /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` - /// by default. - /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by - /// default. - /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of - /// status code. `[.head]` by default. - /// - Returns: The `DataResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishData(queue: DispatchQueue = .main, - preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { - publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - on: queue) - } - - /// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the - /// response. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. - /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` - /// by default. - /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding - /// will be determined by the server response, falling back to the default HTTP character - /// set, `ISO-8859-1`. - /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by - /// default. - /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of - /// status code. `[.head]` by default. - /// - /// - Returns: The `DataResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishString(queue: DispatchQueue = .main, - preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, - encoding: String.Encoding? = nil, - emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { - publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, - encoding: encoding, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - on: queue) - } - - @_disfavoredOverload - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") - public func publishDecodable(type: T.Type = T.self, - queue: DispatchQueue = .main, - preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { - publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, - decoder: decoder, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyResponseMethods), - on: queue) - } - - /// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the - /// response. - /// - /// - Parameters: - /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by - /// default. - /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. - /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. - /// `PassthroughPreprocessor()` by default. - /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. - /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by - /// default. - /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of - /// status code. `[.head]` by default. - /// - /// - Returns: The `DataResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishDecodable(type: T.Type = T.self, - queue: DispatchQueue = .main, - preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { - publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, - decoder: decoder, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - on: queue) - } - - /// Creates a `DataResponsePublisher` for this instance which does not serialize the response before publishing. - /// - /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. - /// - /// - Returns: The `DataResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishUnserialized(queue: DispatchQueue = .main) -> DataResponsePublisher { - DataResponsePublisher(self, queue: queue) - } -} - -// A Combine `Publisher` that publishes a sequence of `Stream` values received by the provided `DataStreamRequest`. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -public struct DataStreamPublisher: Publisher { - public typealias Output = DataStreamRequest.Stream - public typealias Failure = Never - - private typealias Handler = (@escaping DataStreamRequest.Handler) -> DataStreamRequest - - private let request: DataStreamRequest - private let streamHandler: Handler - - /// Creates an instance which will serialize responses using the provided `DataStreamSerializer`. - /// - /// - Parameters: - /// - request: `DataStreamRequest` for which to publish the response. - /// - queue: `DispatchQueue` on which the `Stream` values will be published. `.main` by - /// default. - /// - serializer: `DataStreamSerializer` used to produce the published `Stream` values. - public init(_ request: DataStreamRequest, queue: DispatchQueue, serializer: Serializer) - where Value == Serializer.SerializedObject { - self.request = request - streamHandler = { request.responseStream(using: serializer, on: queue, stream: $0) } - } - - /// Publishes only the `Result` of the `DataStreamRequest.Stream`'s `Event`s. - /// - /// - Returns: The `AnyPublisher` publishing the `Result` value. - public func result() -> AnyPublisher, Never> { - compactMap { stream in - switch stream.event { - case let .stream(result): - return result - // If the stream has completed with an error, send the error value downstream as a `.failure`. - case let .complete(completion): - return completion.error.map(Result.failure) - } - } - .eraseToAnyPublisher() - } - - /// Publishes the streamed values of the `DataStreamRequest.Stream` as a sequence of `Value` or fail with the - /// `AFError` instance. - /// - /// - Returns: The `AnyPublisher` publishing the stream. - public func value() -> AnyPublisher { - result().setFailureType(to: AFError.self).flatMap(\.publisher).eraseToAnyPublisher() - } - - public func receive(subscriber: S) where S: Subscriber, DataStreamPublisher.Failure == S.Failure, DataStreamPublisher.Output == S.Input { - subscriber.receive(subscription: Inner(request: request, - streamHandler: streamHandler, - downstream: subscriber)) - } - - private final class Inner: Subscription - where Downstream.Input == Output { - typealias Failure = Downstream.Failure - - @Protected - private var downstream: Downstream? - private let request: DataStreamRequest - private let streamHandler: Handler - - init(request: DataStreamRequest, streamHandler: @escaping Handler, downstream: Downstream) { - self.request = request - self.streamHandler = streamHandler - self.downstream = downstream - } - - func request(_ demand: Subscribers.Demand) { - assert(demand > 0) - - guard let downstream = downstream else { return } - - self.downstream = nil - streamHandler { stream in - _ = downstream.receive(stream) - if case .complete = stream.event { - downstream.receive(completion: .finished) - } - }.resume() - } - - func cancel() { - request.cancel() - downstream = nil - } - } -} - -extension DataStreamRequest { - /// Creates a `DataStreamPublisher` for this instance using the given `DataStreamSerializer` and `DispatchQueue`. - /// - /// - Parameters: - /// - serializer: `DataStreamSerializer` used to serialize the streamed `Data`. - /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. - /// - Returns: The `DataStreamPublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishStream(using serializer: Serializer, - on queue: DispatchQueue = .main) -> DataStreamPublisher { - DataStreamPublisher(self, queue: queue, serializer: serializer) - } - - /// Creates a `DataStreamPublisher` for this instance which uses a `PassthroughStreamSerializer` to stream `Data` - /// unserialized. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. - /// - Returns: The `DataStreamPublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher { - publishStream(using: PassthroughStreamSerializer(), on: queue) - } - - /// Creates a `DataStreamPublisher` for this instance which uses a `StringStreamSerializer` to serialize stream - /// `Data` values into `String` values. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. - /// - Returns: The `DataStreamPublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher { - publishStream(using: StringStreamSerializer(), on: queue) - } - - /// Creates a `DataStreamPublisher` for this instance which uses a `DecodableStreamSerializer` with the provided - /// parameters to serialize stream `Data` values into the provided type. - /// - /// - Parameters: - /// - type: `Decodable` type to which to decode stream `Data`. Inferred from the context by default. - /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. - /// - decoder: `DataDecoder` instance used to decode stream `Data`. `JSONDecoder()` by default. - /// - preprocessor: `DataPreprocessor` which filters incoming stream `Data` before serialization. - /// `PassthroughPreprocessor()` by default. - /// - Returns: The `DataStreamPublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishDecodable(type: T.Type = T.self, - queue: DispatchQueue = .main, - decoder: DataDecoder = JSONDecoder(), - preprocessor: DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher { - publishStream(using: DecodableStreamSerializer(decoder: decoder, - dataPreprocessor: preprocessor), - on: queue) - } -} - -/// A Combine `Publisher` that publishes the `DownloadResponse` of the provided `DownloadRequest`. -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -public struct DownloadResponsePublisher: Publisher { - public typealias Output = DownloadResponse - public typealias Failure = Never - - private typealias Handler = (@escaping (_ response: DownloadResponse) -> Void) -> DownloadRequest - - private let request: DownloadRequest - private let responseHandler: Handler - - /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. - /// - /// - Parameters: - /// - request: `DownloadRequest` for which to publish the response. - /// - queue: `DispatchQueue` on which the `DownloadResponse` value will be published. `.main` by default. - /// - serializer: `ResponseSerializer` used to produce the published `DownloadResponse`. - public init(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer) - where Value == Serializer.SerializedObject { - self.request = request - responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } - } - - /// Creates an instance which will serialize responses using the provided `DownloadResponseSerializerProtocol` value. - /// - /// - Parameters: - /// - request: `DownloadRequest` for which to publish the response. - /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. - /// - serializer: `DownloadResponseSerializerProtocol` used to produce the published `DownloadResponse`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public init(_ request: DownloadRequest, - queue: DispatchQueue, - serializer: Serializer) - where Value == Serializer.SerializedObject { - self.request = request - responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } - } - - /// Publishes only the `Result` of the `DownloadResponse` value. - /// - /// - Returns: The `AnyPublisher` publishing the `Result` value. - public func result() -> AnyPublisher, Never> { - map(\.result).eraseToAnyPublisher() - } - - /// Publishes the `Result` of the `DownloadResponse` as a single `Value` or fail with the `AFError` instance. - /// - /// - Returns: The `AnyPublisher` publishing the stream. - public func value() -> AnyPublisher { - setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() - } - - public func receive(subscriber: S) where S: Subscriber, DownloadResponsePublisher.Failure == S.Failure, DownloadResponsePublisher.Output == S.Input { - subscriber.receive(subscription: Inner(request: request, - responseHandler: responseHandler, - downstream: subscriber)) - } - - private final class Inner: Subscription - where Downstream.Input == Output { - typealias Failure = Downstream.Failure - - @Protected - private var downstream: Downstream? - private let request: DownloadRequest - private let responseHandler: Handler - - init(request: DownloadRequest, responseHandler: @escaping Handler, downstream: Downstream) { - self.request = request - self.responseHandler = responseHandler - self.downstream = downstream - } - - func request(_ demand: Subscribers.Demand) { - assert(demand > 0) - - guard let downstream = downstream else { return } - - self.downstream = nil - responseHandler { response in - _ = downstream.receive(response) - downstream.receive(completion: .finished) - }.resume() - } - - func cancel() { - request.cancel() - downstream = nil - } - } -} - -extension DownloadRequest { - /// Creates a `DownloadResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. - /// - /// - Parameters: - /// - serializer: `ResponseSerializer` used to serialize the response `Data` from disk. - /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. - /// - /// - Returns: The `DownloadResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher - where Serializer.SerializedObject == T { - DownloadResponsePublisher(self, queue: queue, serializer: serializer) - } - - /// Creates a `DownloadResponsePublisher` for this instance using the given `DownloadResponseSerializerProtocol` and - /// `DispatchQueue`. - /// - /// - Parameters: - /// - serializer: `DownloadResponseSerializer` used to serialize the response `Data` from disk. - /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. - /// - /// - Returns: The `DownloadResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher - where Serializer.SerializedObject == T { - DownloadResponsePublisher(self, queue: queue, serializer: serializer) - } - - /// Creates a `DownloadResponsePublisher` for this instance and uses a `URLResponseSerializer` to serialize the - /// response. - /// - /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. - /// - /// - Returns: The `DownloadResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishURL(queue: DispatchQueue = .main) -> DownloadResponsePublisher { - publishResponse(using: URLResponseSerializer(), on: queue) - } - - /// Creates a `DownloadResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the - /// response. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. - /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` - /// by default. - /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by - /// default. - /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of - /// status code. `[.head]` by default. - /// - /// - Returns: The `DownloadResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishData(queue: DispatchQueue = .main, - preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { - publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - on: queue) - } - - /// Creates a `DownloadResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the - /// response. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. - /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` - /// by default. - /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding - /// will be determined by the server response, falling back to the default HTTP character - /// set, `ISO-8859-1`. - /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by - /// default. - /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of - /// status code. `[.head]` by default. - /// - /// - Returns: The `DownloadResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishString(queue: DispatchQueue = .main, - preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, - encoding: String.Encoding? = nil, - emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { - publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, - encoding: encoding, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - on: queue) - } - - @_disfavoredOverload - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") - public func publishDecodable(type: T.Type = T.self, - queue: DispatchQueue = .main, - preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { - publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, - decoder: decoder, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyResponseMethods), - on: queue) - } - - /// Creates a `DownloadResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize - /// the response. - /// - /// - Parameters: - /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default. - /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. - /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. - /// `PassthroughPreprocessor()` by default. - /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. - /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by - /// default. - /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless - /// of status code. `[.head]` by default. - /// - /// - Returns: The `DownloadResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishDecodable(type: T.Type = T.self, - queue: DispatchQueue = .main, - preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { - publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, - decoder: decoder, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - on: queue) - } -} - -@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) -extension DownloadResponsePublisher where Value == URL? { - /// Creates an instance which publishes a `DownloadResponse` value without serialization. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public init(_ request: DownloadRequest, queue: DispatchQueue) { - self.request = request - responseHandler = { request.response(queue: queue, completionHandler: $0) } - } -} - -extension DownloadRequest { - /// Creates a `DownloadResponsePublisher` for this instance which does not serialize the response before publishing. - /// - /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. - /// - /// - Returns: The `DownloadResponsePublisher`. - @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) - public func publishUnserialized(on queue: DispatchQueue = .main) -> DownloadResponsePublisher { - DownloadResponsePublisher(self, queue: queue) - } -} - -#endif diff --git a/Pods/Alamofire/Source/Concurrency.swift b/Pods/Alamofire/Source/Concurrency.swift deleted file mode 100644 index 21e7e1e..0000000 --- a/Pods/Alamofire/Source/Concurrency.swift +++ /dev/null @@ -1,832 +0,0 @@ -// -// Concurrency.swift -// -// Copyright (c) 2021 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#if compiler(>=5.6.0) && canImport(_Concurrency) - -import Foundation - -// MARK: - Request Event Streams - -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -extension Request { - /// Creates a `StreamOf` for the instance's upload progress. - /// - /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `StreamOf`. - public func uploadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { - stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in - uploadProgress(queue: underlyingQueue) { progress in - continuation.yield(progress) - } - } - } - - /// Creates a `StreamOf` for the instance's download progress. - /// - /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `StreamOf`. - public func downloadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { - stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in - downloadProgress(queue: underlyingQueue) { progress in - continuation.yield(progress) - } - } - } - - /// Creates a `StreamOf` for the `URLRequest`s produced for the instance. - /// - /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `StreamOf`. - public func urlRequests(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { - stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in - onURLRequestCreation(on: underlyingQueue) { request in - continuation.yield(request) - } - } - } - - /// Creates a `StreamOf` for the `URLSessionTask`s produced for the instance. - /// - /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `StreamOf`. - public func urlSessionTasks(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { - stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in - onURLSessionTaskCreation(on: underlyingQueue) { task in - continuation.yield(task) - } - } - } - - /// Creates a `StreamOf` for the cURL descriptions produced for the instance. - /// - /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `StreamOf`. - public func cURLDescriptions(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { - stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in - cURLDescription(on: underlyingQueue) { description in - continuation.yield(description) - } - } - } - - fileprivate func stream(of type: T.Type = T.self, - bufferingPolicy: StreamOf.BufferingPolicy = .unbounded, - yielder: @escaping (StreamOf.Continuation) -> Void) -> StreamOf { - StreamOf(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in - yielder(continuation) - // Must come after serializers run in order to catch retry progress. - onFinish { - continuation.finish() - } - } - } -} - -// MARK: - DataTask - -/// Value used to `await` a `DataResponse` and associated values. -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -public struct DataTask { - /// `DataResponse` produced by the `DataRequest` and its response handler. - public var response: DataResponse { - get async { - if shouldAutomaticallyCancel { - return await withTaskCancellationHandler { - await task.value - } onCancel: { - cancel() - } - } else { - return await task.value - } - } - } - - /// `Result` of any response serialization performed for the `response`. - public var result: Result { - get async { await response.result } - } - - /// `Value` returned by the `response`. - public var value: Value { - get async throws { - try await result.get() - } - } - - private let request: DataRequest - private let task: Task, Never> - private let shouldAutomaticallyCancel: Bool - - fileprivate init(request: DataRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { - self.request = request - self.task = task - self.shouldAutomaticallyCancel = shouldAutomaticallyCancel - } - - /// Cancel the underlying `DataRequest` and `Task`. - public func cancel() { - task.cancel() - } - - /// Resume the underlying `DataRequest`. - public func resume() { - request.resume() - } - - /// Suspend the underlying `DataRequest`. - public func suspend() { - request.suspend() - } -} - -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -extension DataRequest { - /// Creates a `StreamOf` for the instance's responses. - /// - /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `StreamOf`. - public func httpResponses(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { - stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in - onHTTPResponse(on: underlyingQueue) { response in - continuation.yield(response) - } - } - } - - #if swift(>=5.7) - /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataRequest` produces an - /// `HTTPURLResponse`. - /// - /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). - /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, - /// where responses after the first will contain the part headers. - /// - /// - Parameters: - /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a - /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as - /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread, - /// so any synchronous calls in it will execute in that context. - /// - /// - Returns: The instance. - @_disfavoredOverload - @discardableResult - public func onHTTPResponse( - perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> ResponseDisposition - ) -> Self { - onHTTPResponse(on: underlyingQueue) { response, completionHandler in - Task { - let disposition = await handler(response) - completionHandler(disposition) - } - } - - return self - } - - /// Sets an async closure called whenever the `DataRequest` produces an `HTTPURLResponse`. - /// - /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). - /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, - /// where responses after the first will contain the part headers. - /// - /// - Parameters: - /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an - /// arbitrary thread, so any synchronous calls in it will execute in that context. - /// - /// - Returns: The instance. - @discardableResult - public func onHTTPResponse(perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> Void) -> Self { - onHTTPResponse { response in - await handler(response) - return .allow - } - - return self - } - #endif - - /// Creates a `DataTask` to `await` a `Data` value. - /// - /// - Parameters: - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DataTask`'s async - /// properties. `true` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. - /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - /// - Returns: The `DataTask`. - public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, - dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataTask { - serializingResponse(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - automaticallyCancelling: shouldAutomaticallyCancel) - } - - /// Creates a `DataTask` to `await` serialization of a `Decodable` value. - /// - /// - Parameters: - /// - type: `Decodable` type to decode from response data. - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DataTask`'s async - /// properties. `true` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. - /// `PassthroughPreprocessor()` by default. - /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - /// - Returns: The `DataTask`. - public func serializingDecodable(_ type: Value.Type = Value.self, - automaticallyCancelling shouldAutomaticallyCancel: Bool = true, - dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataTask { - serializingResponse(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, - decoder: decoder, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - automaticallyCancelling: shouldAutomaticallyCancel) - } - - /// Creates a `DataTask` to `await` serialization of a `String` value. - /// - /// - Parameters: - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DataTask`'s async - /// properties. `true` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. - /// `PassthroughPreprocessor()` by default. - /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case - /// the encoding will be determined from the server response, falling back to the - /// default HTTP character set, `ISO-8859-1`. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - /// - Returns: The `DataTask`. - public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, - dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, - encoding: String.Encoding? = nil, - emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataTask { - serializingResponse(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, - encoding: encoding, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - automaticallyCancelling: shouldAutomaticallyCancel) - } - - /// Creates a `DataTask` to `await` serialization using the provided `ResponseSerializer` instance. - /// - /// - Parameters: - /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DataTask`'s async - /// properties. `true` by default. - /// - /// - Returns: The `DataTask`. - public func serializingResponse(using serializer: Serializer, - automaticallyCancelling shouldAutomaticallyCancel: Bool = true) - -> DataTask { - dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in - response(queue: underlyingQueue, - responseSerializer: serializer, - completionHandler: $0) - } - } - - /// Creates a `DataTask` to `await` serialization using the provided `DataResponseSerializerProtocol` instance. - /// - /// - Parameters: - /// - serializer: `DataResponseSerializerProtocol` responsible for serializing the request, - /// response, and data. - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DataTask`'s async - /// properties. `true` by default. - /// - /// - Returns: The `DataTask`. - public func serializingResponse(using serializer: Serializer, - automaticallyCancelling shouldAutomaticallyCancel: Bool = true) - -> DataTask { - dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in - response(queue: underlyingQueue, - responseSerializer: serializer, - completionHandler: $0) - } - } - - private func dataTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, - forResponse onResponse: @escaping (@escaping (DataResponse) -> Void) -> Void) - -> DataTask { - let task = Task { - await withTaskCancellationHandler { - await withCheckedContinuation { continuation in - onResponse { - continuation.resume(returning: $0) - } - } - } onCancel: { - self.cancel() - } - } - - return DataTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) - } -} - -// MARK: - DownloadTask - -/// Value used to `await` a `DownloadResponse` and associated values. -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -public struct DownloadTask { - /// `DownloadResponse` produced by the `DownloadRequest` and its response handler. - public var response: DownloadResponse { - get async { - if shouldAutomaticallyCancel { - return await withTaskCancellationHandler { - await task.value - } onCancel: { - cancel() - } - } else { - return await task.value - } - } - } - - /// `Result` of any response serialization performed for the `response`. - public var result: Result { - get async { await response.result } - } - - /// `Value` returned by the `response`. - public var value: Value { - get async throws { - try await result.get() - } - } - - private let task: Task, Never> - private let request: DownloadRequest - private let shouldAutomaticallyCancel: Bool - - fileprivate init(request: DownloadRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { - self.request = request - self.task = task - self.shouldAutomaticallyCancel = shouldAutomaticallyCancel - } - - /// Cancel the underlying `DownloadRequest` and `Task`. - public func cancel() { - task.cancel() - } - - /// Resume the underlying `DownloadRequest`. - public func resume() { - request.resume() - } - - /// Suspend the underlying `DownloadRequest`. - public func suspend() { - request.suspend() - } -} - -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -extension DownloadRequest { - /// Creates a `DownloadTask` to `await` a `Data` value. - /// - /// - Parameters: - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async - /// properties. `true` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. - /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - /// - Returns: The `DownloadTask`. - public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, - dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { - serializingDownload(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - automaticallyCancelling: shouldAutomaticallyCancel) - } - - /// Creates a `DownloadTask` to `await` serialization of a `Decodable` value. - /// - /// - Note: This serializer reads the entire response into memory before parsing. - /// - /// - Parameters: - /// - type: `Decodable` type to decode from response data. - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async - /// properties. `true` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. - /// `PassthroughPreprocessor()` by default. - /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - /// - Returns: The `DownloadTask`. - public func serializingDecodable(_ type: Value.Type = Value.self, - automaticallyCancelling shouldAutomaticallyCancel: Bool = true, - dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { - serializingDownload(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, - decoder: decoder, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - automaticallyCancelling: shouldAutomaticallyCancel) - } - - /// Creates a `DownloadTask` to `await` serialization of the downloaded file's `URL` on disk. - /// - /// - Parameters: - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async - /// properties. `true` by default. - /// - /// - Returns: The `DownloadTask`. - public func serializingDownloadedFileURL(automaticallyCancelling shouldAutomaticallyCancel: Bool = true) -> DownloadTask { - serializingDownload(using: URLResponseSerializer(), - automaticallyCancelling: shouldAutomaticallyCancel) - } - - /// Creates a `DownloadTask` to `await` serialization of a `String` value. - /// - /// - Parameters: - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async - /// properties. `true` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the - /// serializer. `PassthroughPreprocessor()` by default. - /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case - /// the encoding will be determined from the server response, falling back to the - /// default HTTP character set, `ISO-8859-1`. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - /// - Returns: The `DownloadTask`. - public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, - dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, - encoding: String.Encoding? = nil, - emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { - serializingDownload(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, - encoding: encoding, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - automaticallyCancelling: shouldAutomaticallyCancel) - } - - /// Creates a `DownloadTask` to `await` serialization using the provided `ResponseSerializer` instance. - /// - /// - Parameters: - /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async - /// properties. `true` by default. - /// - /// - Returns: The `DownloadTask`. - public func serializingDownload(using serializer: Serializer, - automaticallyCancelling shouldAutomaticallyCancel: Bool = true) - -> DownloadTask { - downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in - response(queue: underlyingQueue, - responseSerializer: serializer, - completionHandler: $0) - } - } - - /// Creates a `DownloadTask` to `await` serialization using the provided `DownloadResponseSerializerProtocol` - /// instance. - /// - /// - Parameters: - /// - serializer: `DownloadResponseSerializerProtocol` responsible for serializing the request, - /// response, and data. - /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the - /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async - /// properties. `true` by default. - /// - /// - Returns: The `DownloadTask`. - public func serializingDownload(using serializer: Serializer, - automaticallyCancelling shouldAutomaticallyCancel: Bool = true) - -> DownloadTask { - downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in - response(queue: underlyingQueue, - responseSerializer: serializer, - completionHandler: $0) - } - } - - private func downloadTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, - forResponse onResponse: @escaping (@escaping (DownloadResponse) -> Void) -> Void) - -> DownloadTask { - let task = Task { - await withTaskCancellationHandler { - await withCheckedContinuation { continuation in - onResponse { - continuation.resume(returning: $0) - } - } - } onCancel: { - self.cancel() - } - } - - return DownloadTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) - } -} - -// MARK: - DataStreamTask - -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -public struct DataStreamTask { - // Type of created streams. - public typealias Stream = StreamOf> - - private let request: DataStreamRequest - - fileprivate init(request: DataStreamRequest) { - self.request = request - } - - /// Creates a `Stream` of `Data` values from the underlying `DataStreamRequest`. - /// - /// - Parameters: - /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled - /// which observation of the stream stops. `true` by default. - /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `Stream`. - public func streamingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { - createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in - request.responseStream(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) - } - } - - /// Creates a `Stream` of `UTF-8` `String`s from the underlying `DataStreamRequest`. - /// - /// - Parameters: - /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled - /// which observation of the stream stops. `true` by default. - /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - Returns: - public func streamingStrings(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { - createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in - request.responseStreamString(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) - } - } - - /// Creates a `Stream` of `Decodable` values from the underlying `DataStreamRequest`. - /// - /// - Parameters: - /// - type: `Decodable` type to be serialized from stream payloads. - /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled - /// which observation of the stream stops. `true` by default. - /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `Stream`. - public func streamingDecodables(_ type: T.Type = T.self, - automaticallyCancelling shouldAutomaticallyCancel: Bool = true, - bufferingPolicy: Stream.BufferingPolicy = .unbounded) - -> Stream where T: Decodable { - streamingResponses(serializedUsing: DecodableStreamSerializer(), - automaticallyCancelling: shouldAutomaticallyCancel, - bufferingPolicy: bufferingPolicy) - } - - /// Creates a `Stream` of values using the provided `DataStreamSerializer` from the underlying `DataStreamRequest`. - /// - /// - Parameters: - /// - serializer: `DataStreamSerializer` to use to serialize incoming `Data`. - /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled - /// which observation of the stream stops. `true` by default. - /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `Stream`. - public func streamingResponses(serializedUsing serializer: Serializer, - automaticallyCancelling shouldAutomaticallyCancel: Bool = true, - bufferingPolicy: Stream.BufferingPolicy = .unbounded) - -> Stream { - createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in - request.responseStream(using: serializer, - on: .streamCompletionQueue(forRequestID: request.id), - stream: onStream) - } - } - - private func createStream(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, - bufferingPolicy: Stream.BufferingPolicy = .unbounded, - forResponse onResponse: @escaping (@escaping (DataStreamRequest.Stream) -> Void) -> Void) - -> Stream { - StreamOf(bufferingPolicy: bufferingPolicy) { - guard shouldAutomaticallyCancel, - request.isInitialized || request.isResumed || request.isSuspended else { return } - - cancel() - } builder: { continuation in - onResponse { stream in - continuation.yield(stream) - if case .complete = stream.event { - continuation.finish() - } - } - } - } - - /// Cancel the underlying `DataStreamRequest`. - public func cancel() { - request.cancel() - } - - /// Resume the underlying `DataStreamRequest`. - public func resume() { - request.resume() - } - - /// Suspend the underlying `DataStreamRequest`. - public func suspend() { - request.suspend() - } -} - -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -extension DataStreamRequest { - /// Creates a `StreamOf` for the instance's responses. - /// - /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. - /// - /// - Returns: The `StreamOf`. - public func httpResponses(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { - stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in - onHTTPResponse(on: underlyingQueue) { response in - continuation.yield(response) - } - } - } - - #if swift(>=5.7) - /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataStreamRequest` - /// produces an `HTTPURLResponse`. - /// - /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). - /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, - /// where responses after the first will contain the part headers. - /// - /// - Parameters: - /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a - /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as - /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread, - /// so any synchronous calls in it will execute in that context. - /// - /// - Returns: The instance. - @_disfavoredOverload - @discardableResult - public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> ResponseDisposition) -> Self { - onHTTPResponse(on: underlyingQueue) { response, completionHandler in - Task { - let disposition = await handler(response) - completionHandler(disposition) - } - } - - return self - } - - /// Sets an async closure called whenever the `DataStreamRequest` produces an `HTTPURLResponse`. - /// - /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). - /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, - /// where responses after the first will contain the part headers. - /// - /// - Parameters: - /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an - /// arbitrary thread, so any synchronous calls in it will execute in that context. - /// - /// - Returns: The instance. - @discardableResult - public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> Void) -> Self { - onHTTPResponse { response in - await handler(response) - return .allow - } - - return self - } - #endif - - /// Creates a `DataStreamTask` used to `await` streams of serialized values. - /// - /// - Returns: The `DataStreamTask`. - public func streamTask() -> DataStreamTask { - DataStreamTask(request: self) - } -} - -extension DispatchQueue { - fileprivate static let singleEventQueue = DispatchQueue(label: "org.alamofire.concurrencySingleEventQueue", - attributes: .concurrent) - - fileprivate static func streamCompletionQueue(forRequestID id: UUID) -> DispatchQueue { - DispatchQueue(label: "org.alamofire.concurrencyStreamCompletionQueue-\(id)", target: .singleEventQueue) - } -} - -/// An asynchronous sequence generated from an underlying `AsyncStream`. Only produced by Alamofire. -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -public struct StreamOf: AsyncSequence { - public typealias AsyncIterator = Iterator - public typealias BufferingPolicy = AsyncStream.Continuation.BufferingPolicy - fileprivate typealias Continuation = AsyncStream.Continuation - - private let bufferingPolicy: BufferingPolicy - private let onTermination: (() -> Void)? - private let builder: (Continuation) -> Void - - fileprivate init(bufferingPolicy: BufferingPolicy = .unbounded, - onTermination: (() -> Void)? = nil, - builder: @escaping (Continuation) -> Void) { - self.bufferingPolicy = bufferingPolicy - self.onTermination = onTermination - self.builder = builder - } - - public func makeAsyncIterator() -> Iterator { - var continuation: AsyncStream.Continuation? - let stream = AsyncStream(bufferingPolicy: bufferingPolicy) { innerContinuation in - continuation = innerContinuation - builder(innerContinuation) - } - - return Iterator(iterator: stream.makeAsyncIterator()) { - continuation?.finish() - onTermination?() - } - } - - public struct Iterator: AsyncIteratorProtocol { - private final class Token { - private let onDeinit: () -> Void - - init(onDeinit: @escaping () -> Void) { - self.onDeinit = onDeinit - } - - deinit { - onDeinit() - } - } - - private var iterator: AsyncStream.AsyncIterator - private let token: Token - - init(iterator: AsyncStream.AsyncIterator, onCancellation: @escaping () -> Void) { - self.iterator = iterator - token = Token(onDeinit: onCancellation) - } - - public mutating func next() async -> Element? { - await iterator.next() - } - } -} - -#endif diff --git a/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift deleted file mode 100644 index 10cd273..0000000 --- a/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// DispatchQueue+Alamofire.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Dispatch -import Foundation - -extension DispatchQueue { - /// Execute the provided closure after a `TimeInterval`. - /// - /// - Parameters: - /// - delay: `TimeInterval` to delay execution. - /// - closure: Closure to execute. - func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { - asyncAfter(deadline: .now() + delay, execute: closure) - } -} diff --git a/Pods/Alamofire/Source/EventMonitor.swift b/Pods/Alamofire/Source/EventMonitor.swift deleted file mode 100644 index 75b60f2..0000000 --- a/Pods/Alamofire/Source/EventMonitor.swift +++ /dev/null @@ -1,907 +0,0 @@ -// -// EventMonitor.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various -/// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses. -public protocol EventMonitor { - /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default. - var queue: DispatchQueue { get } - - // MARK: - URLSession Events - - // MARK: URLSessionDelegate Events - - /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method. - func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) - - // MARK: URLSessionTaskDelegate Events - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method. - func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method. - func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method. - func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method. - func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method. - func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method. - func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) - - /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method. - func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) - - // MARK: URLSessionDataDelegate Events - - /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:completionHandler:)` method. - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) - - /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method. - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) - - /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method. - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) - - // MARK: URLSessionDownloadDelegate Events - - /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method. - func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) - - /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method. - func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) - - /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method. - func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) - - // MARK: - Request Events - - /// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the - /// `URLRequest` will be adapted before being issued. - func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) - - /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails. - func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) - - /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`. - func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) - - /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`. - func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) - - /// Event called when a final `URLRequest` is created for a `Request`. - func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) - - /// Event called when a `URLSessionTask` subclass instance is created for a `Request`. - func request(_ request: Request, didCreateTask task: URLSessionTask) - - /// Event called when a `Request` receives a `URLSessionTaskMetrics` value. - func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) - - /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails. - func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) - - /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event - /// multiple times if it is retried. - func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) - - /// Event called when a `Request` is about to be retried. - func requestIsRetrying(_ request: Request) - - /// Event called when a `Request` finishes and response serializers are being called. - func requestDidFinish(_ request: Request) - - /// Event called when a `Request` receives a `resume` call. - func requestDidResume(_ request: Request) - - /// Event called when a `Request`'s associated `URLSessionTask` is resumed. - func request(_ request: Request, didResumeTask task: URLSessionTask) - - /// Event called when a `Request` receives a `suspend` call. - func requestDidSuspend(_ request: Request) - - /// Event called when a `Request`'s associated `URLSessionTask` is suspended. - func request(_ request: Request, didSuspendTask task: URLSessionTask) - - /// Event called when a `Request` receives a `cancel` call. - func requestDidCancel(_ request: Request) - - /// Event called when a `Request`'s associated `URLSessionTask` is cancelled. - func request(_ request: Request, didCancelTask task: URLSessionTask) - - // MARK: DataRequest Events - - /// Event called when a `DataRequest` calls a `Validation`. - func request(_ request: DataRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - data: Data?, - withResult result: Request.ValidationResult) - - /// Event called when a `DataRequest` creates a `DataResponse` value without calling a `ResponseSerializer`. - func request(_ request: DataRequest, didParseResponse response: DataResponse) - - /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse`. - func request(_ request: DataRequest, didParseResponse response: DataResponse) - - // MARK: DataStreamRequest Events - - /// Event called when a `DataStreamRequest` calls a `Validation` closure. - /// - /// - Parameters: - /// - request: `DataStreamRequest` which is calling the `Validation`. - /// - urlRequest: `URLRequest` of the request being validated. - /// - response: `HTTPURLResponse` of the request being validated. - /// - result: Produced `ValidationResult`. - func request(_ request: DataStreamRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - withResult result: Request.ValidationResult) - - /// Event called when a `DataStreamSerializer` produces a value from streamed `Data`. - /// - /// - Parameters: - /// - request: `DataStreamRequest` for which the value was serialized. - /// - result: `Result` of the serialization attempt. - func request(_ request: DataStreamRequest, didParseStream result: Result) - - // MARK: UploadRequest Events - - /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents. - func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) - - /// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error. - func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) - - /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if - /// the `InputStream` does not wrap a `Data` value or file `URL`. - func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) - - // MARK: DownloadRequest Events - - /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved. - func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) - - /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the - /// downloaded file will be moved to. - func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) - - /// Event called when a `DownloadRequest` calls a `Validation`. - func request(_ request: DownloadRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - fileURL: URL?, - withResult result: Request.ValidationResult) - - /// Event called when a `DownloadRequest` creates a `DownloadResponse` without calling a `ResponseSerializer`. - func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) - - /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse` - func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) -} - -extension EventMonitor { - /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default. - public var queue: DispatchQueue { .main } - - // MARK: Default Implementations - - public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {} - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge) {} - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) {} - public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {} - public func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest) {} - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didFinishCollecting metrics: URLSessionTaskMetrics) {} - public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {} - public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {} - public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) {} - public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {} - public func urlSession(_ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse) {} - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) {} - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) {} - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) {} - public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {} - public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {} - public func request(_ request: Request, - didAdaptInitialRequest initialRequest: URLRequest, - to adaptedRequest: URLRequest) {} - public func request(_ request: Request, - didFailToAdaptURLRequest initialRequest: URLRequest, - withError error: AFError) {} - public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {} - public func request(_ request: Request, didCreateTask task: URLSessionTask) {} - public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {} - public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {} - public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {} - public func requestIsRetrying(_ request: Request) {} - public func requestDidFinish(_ request: Request) {} - public func requestDidResume(_ request: Request) {} - public func request(_ request: Request, didResumeTask task: URLSessionTask) {} - public func requestDidSuspend(_ request: Request) {} - public func request(_ request: Request, didSuspendTask task: URLSessionTask) {} - public func requestDidCancel(_ request: Request) {} - public func request(_ request: Request, didCancelTask task: URLSessionTask) {} - public func request(_ request: DataRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - data: Data?, - withResult result: Request.ValidationResult) {} - public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} - public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} - public func request(_ request: DataStreamRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - withResult result: Request.ValidationResult) {} - public func request(_ request: DataStreamRequest, didParseStream result: Result) {} - public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {} - public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {} - public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {} - public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {} - public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {} - public func request(_ request: DownloadRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - fileURL: URL?, - withResult result: Request.ValidationResult) {} - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} -} - -/// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues. -public final class CompositeEventMonitor: EventMonitor { - public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor", qos: .utility) - - let monitors: [EventMonitor] - - init(monitors: [EventMonitor]) { - self.monitors = monitors - } - - func performEvent(_ event: @escaping (EventMonitor) -> Void) { - queue.async { - for monitor in self.monitors { - monitor.queue.async { event(monitor) } - } - } - } - - public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) } - } - - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge) { - performEvent { $0.urlSession(session, task: task, didReceive: challenge) } - } - - public func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - performEvent { - $0.urlSession(session, - task: task, - didSendBodyData: bytesSent, - totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend) - } - } - - public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { - performEvent { - $0.urlSession(session, taskNeedsNewBodyStream: task) - } - } - - public func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest) { - performEvent { - $0.urlSession(session, - task: task, - willPerformHTTPRedirection: response, - newRequest: request) - } - } - - public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) } - } - - public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) } - } - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) - public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { - performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) } - } - - public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) { - performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: response) } - } - - public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) } - } - - public func urlSession(_ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse) { - performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) } - } - - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - performEvent { - $0.urlSession(session, - downloadTask: downloadTask, - didResumeAtOffset: fileOffset, - expectedTotalBytes: expectedTotalBytes) - } - } - - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - performEvent { - $0.urlSession(session, - downloadTask: downloadTask, - didWriteData: bytesWritten, - totalBytesWritten: totalBytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite) - } - } - - public func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) { - performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } - } - - public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { - performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) } - } - - public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { - performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) } - } - - public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { - performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) } - } - - public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { - performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) } - } - - public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { - performEvent { $0.request(request, didCreateURLRequest: urlRequest) } - } - - public func request(_ request: Request, didCreateTask task: URLSessionTask) { - performEvent { $0.request(request, didCreateTask: task) } - } - - public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { - performEvent { $0.request(request, didGatherMetrics: metrics) } - } - - public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { - performEvent { $0.request(request, didFailTask: task, earlyWithError: error) } - } - - public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { - performEvent { $0.request(request, didCompleteTask: task, with: error) } - } - - public func requestIsRetrying(_ request: Request) { - performEvent { $0.requestIsRetrying(request) } - } - - public func requestDidFinish(_ request: Request) { - performEvent { $0.requestDidFinish(request) } - } - - public func requestDidResume(_ request: Request) { - performEvent { $0.requestDidResume(request) } - } - - public func request(_ request: Request, didResumeTask task: URLSessionTask) { - performEvent { $0.request(request, didResumeTask: task) } - } - - public func requestDidSuspend(_ request: Request) { - performEvent { $0.requestDidSuspend(request) } - } - - public func request(_ request: Request, didSuspendTask task: URLSessionTask) { - performEvent { $0.request(request, didSuspendTask: task) } - } - - public func requestDidCancel(_ request: Request) { - performEvent { $0.requestDidCancel(request) } - } - - public func request(_ request: Request, didCancelTask task: URLSessionTask) { - performEvent { $0.request(request, didCancelTask: task) } - } - - public func request(_ request: DataRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - data: Data?, - withResult result: Request.ValidationResult) { - performEvent { $0.request(request, - didValidateRequest: urlRequest, - response: response, - data: data, - withResult: result) - } - } - - public func request(_ request: DataRequest, didParseResponse response: DataResponse) { - performEvent { $0.request(request, didParseResponse: response) } - } - - public func request(_ request: DataRequest, didParseResponse response: DataResponse) { - performEvent { $0.request(request, didParseResponse: response) } - } - - public func request(_ request: DataStreamRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - withResult result: Request.ValidationResult) { - performEvent { $0.request(request, - didValidateRequest: urlRequest, - response: response, - withResult: result) - } - } - - public func request(_ request: DataStreamRequest, didParseStream result: Result) { - performEvent { $0.request(request, didParseStream: result) } - } - - public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { - performEvent { $0.request(request, didCreateUploadable: uploadable) } - } - - public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { - performEvent { $0.request(request, didFailToCreateUploadableWithError: error) } - } - - public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { - performEvent { $0.request(request, didProvideInputStream: stream) } - } - - public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { - performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) } - } - - public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { - performEvent { $0.request(request, didCreateDestinationURL: url) } - } - - public func request(_ request: DownloadRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - fileURL: URL?, - withResult result: Request.ValidationResult) { - performEvent { $0.request(request, - didValidateRequest: urlRequest, - response: response, - fileURL: fileURL, - withResult: result) } - } - - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { - performEvent { $0.request(request, didParseResponse: response) } - } - - public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { - performEvent { $0.request(request, didParseResponse: response) } - } -} - -/// `EventMonitor` that allows optional closures to be set to receive events. -open class ClosureEventMonitor: EventMonitor { - /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event. - open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? - - /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`. - open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)? - - /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event. - open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? - - /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event. - open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)? - - /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event. - open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)? - - /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event. - open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)? - - /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event. - open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? - - /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event. - open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)? - - /// Closure called on the `urlSession(_:dataTask:didReceive:completionHandler:)` event. - open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> Void)? - - /// Closure that receives the `urlSession(_:dataTask:didReceive:)` event. - open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? - - /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event. - open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)? - - /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event. - open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? - - /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` - /// event. - open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - - /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event. - open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? - - // MARK: - Request Events - - /// Closure called on the `request(_:didCreateInitialURLRequest:)` event. - open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)? - - /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event. - open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)? - - /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event. - open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)? - - /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event. - open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)? - - /// Closure called on the `request(_:didCreateURLRequest:)` event. - open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)? - - /// Closure called on the `request(_:didCreateTask:)` event. - open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)? - - /// Closure called on the `request(_:didGatherMetrics:)` event. - open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)? - - /// Closure called on the `request(_:didFailTask:earlyWithError:)` event. - open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)? - - /// Closure called on the `request(_:didCompleteTask:with:)` event. - open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)? - - /// Closure called on the `requestIsRetrying(_:)` event. - open var requestIsRetrying: ((Request) -> Void)? - - /// Closure called on the `requestDidFinish(_:)` event. - open var requestDidFinish: ((Request) -> Void)? - - /// Closure called on the `requestDidResume(_:)` event. - open var requestDidResume: ((Request) -> Void)? - - /// Closure called on the `request(_:didResumeTask:)` event. - open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)? - - /// Closure called on the `requestDidSuspend(_:)` event. - open var requestDidSuspend: ((Request) -> Void)? - - /// Closure called on the `request(_:didSuspendTask:)` event. - open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)? - - /// Closure called on the `requestDidCancel(_:)` event. - open var requestDidCancel: ((Request) -> Void)? - - /// Closure called on the `request(_:didCancelTask:)` event. - open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)? - - /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event. - open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)? - - /// Closure called on the `request(_:didParseResponse:)` event. - open var requestDidParseResponse: ((DataRequest, DataResponse) -> Void)? - - /// Closure called on the `request(_:didValidateRequest:response:withResult:)` event. - open var requestDidValidateRequestResponseWithResult: ((DataStreamRequest, URLRequest?, HTTPURLResponse, Request.ValidationResult) -> Void)? - - /// Closure called on the `request(_:didCreateUploadable:)` event. - open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)? - - /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event. - open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)? - - /// Closure called on the `request(_:didProvideInputStream:)` event. - open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)? - - /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event. - open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result) -> Void)? - - /// Closure called on the `request(_:didCreateDestinationURL:)` event. - open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)? - - /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event. - open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)? - - /// Closure called on the `request(_:didParseResponse:)` event. - open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse) -> Void)? - - public let queue: DispatchQueue - - /// Creates an instance using the provided queue. - /// - /// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default. - public init(queue: DispatchQueue = .main) { - self.queue = queue - } - - open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - sessionDidBecomeInvalidWithError?(session, error) - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) { - taskDidReceiveChallenge?(session, task, challenge) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } - - open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { - taskNeedNewBodyStream?(session, task) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest) { - taskWillPerformHTTPRedirection?(session, task, response, request) - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - taskDidFinishCollectingMetrics?(session, task, metrics) - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - taskDidComplete?(session, task, error) - } - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) - open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { - taskIsWaitingForConnectivity?(session, task) - } - - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) { - dataTaskDidReceiveResponse?(session, dataTask, response) - } - - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - dataTaskDidReceiveData?(session, dataTask, data) - } - - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) { - dataTaskWillCacheResponse?(session, dataTask, proposedResponse) - } - - open func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes) - } - - open func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) - } - - open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { - downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location) - } - - // MARK: Request Events - - open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { - requestDidCreateInitialURLRequest?(request, urlRequest) - } - - open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { - requestDidFailToCreateURLRequestWithError?(request, error) - } - - open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { - requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest) - } - - open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { - requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error) - } - - open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { - requestDidCreateURLRequest?(request, urlRequest) - } - - open func request(_ request: Request, didCreateTask task: URLSessionTask) { - requestDidCreateTask?(request, task) - } - - open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { - requestDidGatherMetrics?(request, metrics) - } - - open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { - requestDidFailTaskEarlyWithError?(request, task, error) - } - - open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { - requestDidCompleteTaskWithError?(request, task, error) - } - - open func requestIsRetrying(_ request: Request) { - requestIsRetrying?(request) - } - - open func requestDidFinish(_ request: Request) { - requestDidFinish?(request) - } - - open func requestDidResume(_ request: Request) { - requestDidResume?(request) - } - - public func request(_ request: Request, didResumeTask task: URLSessionTask) { - requestDidResumeTask?(request, task) - } - - open func requestDidSuspend(_ request: Request) { - requestDidSuspend?(request) - } - - public func request(_ request: Request, didSuspendTask task: URLSessionTask) { - requestDidSuspendTask?(request, task) - } - - open func requestDidCancel(_ request: Request) { - requestDidCancel?(request) - } - - public func request(_ request: Request, didCancelTask task: URLSessionTask) { - requestDidCancelTask?(request, task) - } - - open func request(_ request: DataRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - data: Data?, - withResult result: Request.ValidationResult) { - requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result) - } - - open func request(_ request: DataRequest, didParseResponse response: DataResponse) { - requestDidParseResponse?(request, response) - } - - public func request(_ request: DataStreamRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, withResult result: Request.ValidationResult) { - requestDidValidateRequestResponseWithResult?(request, urlRequest, response, result) - } - - open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { - requestDidCreateUploadable?(request, uploadable) - } - - open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { - requestDidFailToCreateUploadableWithError?(request, error) - } - - open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { - requestDidProvideInputStream?(request, stream) - } - - open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { - requestDidFinishDownloadingUsingTaskWithResult?(request, task, result) - } - - open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { - requestDidCreateDestinationURL?(request, url) - } - - open func request(_ request: DownloadRequest, - didValidateRequest urlRequest: URLRequest?, - response: HTTPURLResponse, - fileURL: URL?, - withResult result: Request.ValidationResult) { - requestDidValidateRequestResponseFileURLWithResult?(request, - urlRequest, - response, - fileURL, - result) - } - - open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { - requestDidParseDownloadResponse?(request, response) - } -} diff --git a/Pods/Alamofire/Source/HTTPHeaders.swift b/Pods/Alamofire/Source/HTTPHeaders.swift deleted file mode 100644 index 08d4799..0000000 --- a/Pods/Alamofire/Source/HTTPHeaders.swift +++ /dev/null @@ -1,452 +0,0 @@ -// -// HTTPHeaders.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// An order-preserving and case-insensitive representation of HTTP headers. -public struct HTTPHeaders { - private var headers: [HTTPHeader] = [] - - /// Creates an empty instance. - public init() {} - - /// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last - /// name and value encountered. - public init(_ headers: [HTTPHeader]) { - headers.forEach { update($0) } - } - - /// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name - /// and value encountered. - public init(_ dictionary: [String: String]) { - dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) } - } - - /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. - /// - /// - Parameters: - /// - name: The `HTTPHeader` name. - /// - value: The `HTTPHeader value. - public mutating func add(name: String, value: String) { - update(HTTPHeader(name: name, value: value)) - } - - /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. - /// - /// - Parameter header: The `HTTPHeader` to update or append. - public mutating func add(_ header: HTTPHeader) { - update(header) - } - - /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. - /// - /// - Parameters: - /// - name: The `HTTPHeader` name. - /// - value: The `HTTPHeader value. - public mutating func update(name: String, value: String) { - update(HTTPHeader(name: name, value: value)) - } - - /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. - /// - /// - Parameter header: The `HTTPHeader` to update or append. - public mutating func update(_ header: HTTPHeader) { - guard let index = headers.index(of: header.name) else { - headers.append(header) - return - } - - headers.replaceSubrange(index...index, with: [header]) - } - - /// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance. - /// - /// - Parameter name: The name of the `HTTPHeader` to remove. - public mutating func remove(name: String) { - guard let index = headers.index(of: name) else { return } - - headers.remove(at: index) - } - - /// Sort the current instance by header name, case insensitively. - public mutating func sort() { - headers.sort { $0.name.lowercased() < $1.name.lowercased() } - } - - /// Returns an instance sorted by header name. - /// - /// - Returns: A copy of the current instance sorted by name. - public func sorted() -> HTTPHeaders { - var headers = self - headers.sort() - - return headers - } - - /// Case-insensitively find a header's value by name. - /// - /// - Parameter name: The name of the header to search for, case-insensitively. - /// - /// - Returns: The value of header, if it exists. - public func value(for name: String) -> String? { - guard let index = headers.index(of: name) else { return nil } - - return headers[index].value - } - - /// Case-insensitively access the header with the given name. - /// - /// - Parameter name: The name of the header. - public subscript(_ name: String) -> String? { - get { value(for: name) } - set { - if let value = newValue { - update(name: name, value: value) - } else { - remove(name: name) - } - } - } - - /// The dictionary representation of all headers. - /// - /// This representation does not preserve the current order of the instance. - public var dictionary: [String: String] { - let namesAndValues = headers.map { ($0.name, $0.value) } - - return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last }) - } -} - -extension HTTPHeaders: ExpressibleByDictionaryLiteral { - public init(dictionaryLiteral elements: (String, String)...) { - elements.forEach { update(name: $0.0, value: $0.1) } - } -} - -extension HTTPHeaders: ExpressibleByArrayLiteral { - public init(arrayLiteral elements: HTTPHeader...) { - self.init(elements) - } -} - -extension HTTPHeaders: Sequence { - public func makeIterator() -> IndexingIterator<[HTTPHeader]> { - headers.makeIterator() - } -} - -extension HTTPHeaders: Collection { - public var startIndex: Int { - headers.startIndex - } - - public var endIndex: Int { - headers.endIndex - } - - public subscript(position: Int) -> HTTPHeader { - headers[position] - } - - public func index(after i: Int) -> Int { - headers.index(after: i) - } -} - -extension HTTPHeaders: CustomStringConvertible { - public var description: String { - headers.map(\.description) - .joined(separator: "\n") - } -} - -// MARK: - HTTPHeader - -/// A representation of a single HTTP header's name / value pair. -public struct HTTPHeader: Hashable { - /// Name of the header. - public let name: String - - /// Value of the header. - public let value: String - - /// Creates an instance from the given `name` and `value`. - /// - /// - Parameters: - /// - name: The name of the header. - /// - value: The value of the header. - public init(name: String, value: String) { - self.name = name - self.value = value - } -} - -extension HTTPHeader: CustomStringConvertible { - public var description: String { - "\(name): \(value)" - } -} - -extension HTTPHeader { - /// Returns an `Accept` header. - /// - /// - Parameter value: The `Accept` value. - /// - Returns: The header. - public static func accept(_ value: String) -> HTTPHeader { - HTTPHeader(name: "Accept", value: value) - } - - /// Returns an `Accept-Charset` header. - /// - /// - Parameter value: The `Accept-Charset` value. - /// - Returns: The header. - public static func acceptCharset(_ value: String) -> HTTPHeader { - HTTPHeader(name: "Accept-Charset", value: value) - } - - /// Returns an `Accept-Language` header. - /// - /// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages. - /// Use `HTTPHeader.defaultAcceptLanguage`. - /// - /// - Parameter value: The `Accept-Language` value. - /// - /// - Returns: The header. - public static func acceptLanguage(_ value: String) -> HTTPHeader { - HTTPHeader(name: "Accept-Language", value: value) - } - - /// Returns an `Accept-Encoding` header. - /// - /// Alamofire offers a default accept encoding value that provides the most common values. Use - /// `HTTPHeader.defaultAcceptEncoding`. - /// - /// - Parameter value: The `Accept-Encoding` value. - /// - /// - Returns: The header - public static func acceptEncoding(_ value: String) -> HTTPHeader { - HTTPHeader(name: "Accept-Encoding", value: value) - } - - /// Returns a `Basic` `Authorization` header using the `username` and `password` provided. - /// - /// - Parameters: - /// - username: The username of the header. - /// - password: The password of the header. - /// - /// - Returns: The header. - public static func authorization(username: String, password: String) -> HTTPHeader { - let credential = Data("\(username):\(password)".utf8).base64EncodedString() - - return authorization("Basic \(credential)") - } - - /// Returns a `Bearer` `Authorization` header using the `bearerToken` provided - /// - /// - Parameter bearerToken: The bearer token. - /// - /// - Returns: The header. - public static func authorization(bearerToken: String) -> HTTPHeader { - authorization("Bearer \(bearerToken)") - } - - /// Returns an `Authorization` header. - /// - /// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use - /// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use - /// `HTTPHeader.authorization(bearerToken:)`. - /// - /// - Parameter value: The `Authorization` value. - /// - /// - Returns: The header. - public static func authorization(_ value: String) -> HTTPHeader { - HTTPHeader(name: "Authorization", value: value) - } - - /// Returns a `Content-Disposition` header. - /// - /// - Parameter value: The `Content-Disposition` value. - /// - /// - Returns: The header. - public static func contentDisposition(_ value: String) -> HTTPHeader { - HTTPHeader(name: "Content-Disposition", value: value) - } - - /// Returns a `Content-Encoding` header. - /// - /// - Parameter value: The `Content-Encoding`. - /// - /// - Returns: The header. - public static func contentEncoding(_ value: String) -> HTTPHeader { - HTTPHeader(name: "Content-Encoding", value: value) - } - - /// Returns a `Content-Type` header. - /// - /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not - /// be necessary to manually set this value. - /// - /// - Parameter value: The `Content-Type` value. - /// - /// - Returns: The header. - public static func contentType(_ value: String) -> HTTPHeader { - HTTPHeader(name: "Content-Type", value: value) - } - - /// Returns a `User-Agent` header. - /// - /// - Parameter value: The `User-Agent` value. - /// - /// - Returns: The header. - public static func userAgent(_ value: String) -> HTTPHeader { - HTTPHeader(name: "User-Agent", value: value) - } -} - -extension Array where Element == HTTPHeader { - /// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists. - func index(of name: String) -> Int? { - let lowercasedName = name.lowercased() - return firstIndex { $0.name.lowercased() == lowercasedName } - } -} - -// MARK: - Defaults - -extension HTTPHeaders { - /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and - /// `User-Agent`. - public static let `default`: HTTPHeaders = [.defaultAcceptEncoding, - .defaultAcceptLanguage, - .defaultUserAgent] -} - -extension HTTPHeader { - /// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS - /// versions. - /// - /// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) . - public static let defaultAcceptEncoding: HTTPHeader = { - let encodings: [String] - if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) { - encodings = ["br", "gzip", "deflate"] - } else { - encodings = ["gzip", "deflate"] - } - - return .acceptEncoding(encodings.qualityEncoded()) - }() - - /// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's - /// `preferredLanguages`. - /// - /// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5). - public static let defaultAcceptLanguage: HTTPHeader = .acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded()) - - /// Returns Alamofire's default `User-Agent` header. - /// - /// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3). - /// - /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0` - public static let defaultUserAgent: HTTPHeader = { - let info = Bundle.main.infoDictionary - let executable = (info?["CFBundleExecutable"] as? String) ?? - (ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ?? - "Unknown" - let bundle = info?["CFBundleIdentifier"] as? String ?? "Unknown" - let appVersion = info?["CFBundleShortVersionString"] as? String ?? "Unknown" - let appBuild = info?["CFBundleVersion"] as? String ?? "Unknown" - - let osNameVersion: String = { - let version = ProcessInfo.processInfo.operatingSystemVersion - let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" - let osName: String = { - #if os(iOS) - #if targetEnvironment(macCatalyst) - return "macOS(Catalyst)" - #else - return "iOS" - #endif - #elseif os(watchOS) - return "watchOS" - #elseif os(tvOS) - return "tvOS" - #elseif os(macOS) - return "macOS" - #elseif os(Linux) - return "Linux" - #elseif os(Windows) - return "Windows" - #elseif os(Android) - return "Android" - #else - return "Unknown" - #endif - }() - - return "\(osName) \(versionString)" - }() - - let alamofireVersion = "Alamofire/\(version)" - - let userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" - - return .userAgent(userAgent) - }() -} - -extension Collection where Element == String { - func qualityEncoded() -> String { - enumerated().map { index, encoding in - let quality = 1.0 - (Double(index) * 0.1) - return "\(encoding);q=\(quality)" - }.joined(separator: ", ") - } -} - -// MARK: - System Type Extensions - -extension URLRequest { - /// Returns `allHTTPHeaderFields` as `HTTPHeaders`. - public var headers: HTTPHeaders { - get { allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() } - set { allHTTPHeaderFields = newValue.dictionary } - } -} - -extension HTTPURLResponse { - /// Returns `allHeaderFields` as `HTTPHeaders`. - public var headers: HTTPHeaders { - (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() - } -} - -extension URLSessionConfiguration { - /// Returns `httpAdditionalHeaders` as `HTTPHeaders`. - public var headers: HTTPHeaders { - get { (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() } - set { httpAdditionalHeaders = newValue.dictionary } - } -} diff --git a/Pods/Alamofire/Source/HTTPMethod.swift b/Pods/Alamofire/Source/HTTPMethod.swift deleted file mode 100644 index 539d214..0000000 --- a/Pods/Alamofire/Source/HTTPMethod.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// HTTPMethod.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -/// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so -/// `HTTPMethod.get != HTTPMethod(rawValue: "get")`. -/// -/// See https://tools.ietf.org/html/rfc7231#section-4.3 -public struct HTTPMethod: RawRepresentable, Equatable, Hashable { - /// `CONNECT` method. - public static let connect = HTTPMethod(rawValue: "CONNECT") - /// `DELETE` method. - public static let delete = HTTPMethod(rawValue: "DELETE") - /// `GET` method. - public static let get = HTTPMethod(rawValue: "GET") - /// `HEAD` method. - public static let head = HTTPMethod(rawValue: "HEAD") - /// `OPTIONS` method. - public static let options = HTTPMethod(rawValue: "OPTIONS") - /// `PATCH` method. - public static let patch = HTTPMethod(rawValue: "PATCH") - /// `POST` method. - public static let post = HTTPMethod(rawValue: "POST") - /// `PUT` method. - public static let put = HTTPMethod(rawValue: "PUT") - /// `QUERY` method. - public static let query = HTTPMethod(rawValue: "QUERY") - /// `TRACE` method. - public static let trace = HTTPMethod(rawValue: "TRACE") - - public let rawValue: String - - public init(rawValue: String) { - self.rawValue = rawValue - } -} diff --git a/Pods/Alamofire/Source/MultipartFormData.swift b/Pods/Alamofire/Source/MultipartFormData.swift deleted file mode 100644 index 3fb6e2b..0000000 --- a/Pods/Alamofire/Source/MultipartFormData.swift +++ /dev/null @@ -1,601 +0,0 @@ -// -// MultipartFormData.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -#if canImport(MobileCoreServices) -import MobileCoreServices -#elseif canImport(CoreServices) -import CoreServices -#endif - -/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode -/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead -/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the -/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for -/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. -/// -/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well -/// and the w3 form documentation. -/// -/// - https://www.ietf.org/rfc/rfc2388.txt -/// - https://www.ietf.org/rfc/rfc2045.txt -/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 -open class MultipartFormData { - // MARK: - Helper Types - - enum EncodingCharacters { - static let crlf = "\r\n" - } - - enum BoundaryGenerator { - enum BoundaryType { - case initial, encapsulated, final - } - - static func randomBoundary() -> String { - let first = UInt32.random(in: UInt32.min...UInt32.max) - let second = UInt32.random(in: UInt32.min...UInt32.max) - - return String(format: "alamofire.boundary.%08x%08x", first, second) - } - - static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { - let boundaryText: String - - switch boundaryType { - case .initial: - boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" - case .encapsulated: - boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" - case .final: - boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" - } - - return Data(boundaryText.utf8) - } - } - - class BodyPart { - let headers: HTTPHeaders - let bodyStream: InputStream - let bodyContentLength: UInt64 - var hasInitialBoundary = false - var hasFinalBoundary = false - - init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { - self.headers = headers - self.bodyStream = bodyStream - self.bodyContentLength = bodyContentLength - } - } - - // MARK: - Properties - - /// Default memory threshold used when encoding `MultipartFormData`, in bytes. - public static let encodingMemoryThreshold: UInt64 = 10_000_000 - - /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. - open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" - - /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. - public var contentLength: UInt64 { bodyParts.reduce(0) { $0 + $1.bodyContentLength } } - - /// The boundary used to separate the body parts in the encoded form data. - public let boundary: String - - let fileManager: FileManager - - private var bodyParts: [BodyPart] - private var bodyPartError: AFError? - private let streamBufferSize: Int - - // MARK: - Lifecycle - - /// Creates an instance. - /// - /// - Parameters: - /// - fileManager: `FileManager` to use for file operations, if needed. - /// - boundary: Boundary `String` used to separate body parts. - public init(fileManager: FileManager = .default, boundary: String? = nil) { - self.fileManager = fileManager - self.boundary = boundary ?? BoundaryGenerator.randomBoundary() - bodyParts = [] - - // - // The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more - // information, please refer to the following article: - // - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html - // - streamBufferSize = 1024 - } - - // MARK: - Body Parts - - /// Creates a body part from the data and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - /// - `Content-Type: #{mimeType}` (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// - Parameters: - /// - data: `Data` to encoding into the instance. - /// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header. - /// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header. - /// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header. - public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the file and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) - /// - `Content-Type: #{generated mimeType}` (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the - /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the - /// system associated MIME type. - /// - /// - Parameters: - /// - fileURL: `URL` of the file whose content will be encoded into the instance. - /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. - public func append(_ fileURL: URL, withName name: String) { - let fileName = fileURL.lastPathComponent - let pathExtension = fileURL.pathExtension - - if !fileName.isEmpty && !pathExtension.isEmpty { - let mime = mimeType(forPathExtension: pathExtension) - append(fileURL, withName: name, fileName: fileName, mimeType: mime) - } else { - setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) - } - } - - /// Creates a body part from the file and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) - /// - Content-Type: #{mimeType} (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// - Parameters: - /// - fileURL: `URL` of the file whose content will be encoded into the instance. - /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. - /// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header. - /// - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header. - public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - - //============================================================ - // Check 1 - is file URL? - //============================================================ - - guard fileURL.isFileURL else { - setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) - return - } - - //============================================================ - // Check 2 - is file URL reachable? - //============================================================ - - #if !(os(Linux) || os(Windows) || os(Android)) - do { - let isReachable = try fileURL.checkPromisedItemIsReachable() - guard isReachable else { - setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) - return - } - } catch { - setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) - return - } - #endif - - //============================================================ - // Check 3 - is file URL a directory? - //============================================================ - - var isDirectory: ObjCBool = false - let path = fileURL.path - - guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { - setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) - return - } - - //============================================================ - // Check 4 - can the file size be extracted? - //============================================================ - - let bodyContentLength: UInt64 - - do { - guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else { - setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) - return - } - - bodyContentLength = fileSize.uint64Value - } catch { - setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) - return - } - - //============================================================ - // Check 5 - can a stream be created from file URL? - //============================================================ - - guard let stream = InputStream(url: fileURL) else { - setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) - return - } - - append(stream, withLength: bodyContentLength, headers: headers) - } - - /// Creates a body part from the stream and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - /// - `Content-Type: #{mimeType}` (HTTP Header) - /// - Encoded stream data - /// - Multipart form boundary - /// - /// - Parameters: - /// - stream: `InputStream` to encode into the instance. - /// - length: Length, in bytes, of the stream. - /// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header. - /// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header. - /// - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header. - public func append(_ stream: InputStream, - withLength length: UInt64, - name: String, - fileName: String, - mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part with the stream, length, and headers and appends it to the instance. - /// - /// The body part data will be encoded using the following format: - /// - /// - HTTP headers - /// - Encoded stream data - /// - Multipart form boundary - /// - /// - Parameters: - /// - stream: `InputStream` to encode into the instance. - /// - length: Length, in bytes, of the stream. - /// - headers: `HTTPHeaders` for the body part. - public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { - let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) - bodyParts.append(bodyPart) - } - - // MARK: - Data Encoding - - /// Encodes all appended body parts into a single `Data` value. - /// - /// - Note: This method will load all the appended body parts into memory all at the same time. This method should - /// only be used when the encoded data will have a small memory footprint. For large data cases, please use - /// the `writeEncodedData(to:))` method. - /// - /// - Returns: The encoded `Data`, if encoding is successful. - /// - Throws: An `AFError` if encoding encounters an error. - public func encode() throws -> Data { - if let bodyPartError = bodyPartError { - throw bodyPartError - } - - var encoded = Data() - - bodyParts.first?.hasInitialBoundary = true - bodyParts.last?.hasFinalBoundary = true - - for bodyPart in bodyParts { - let encodedData = try encode(bodyPart) - encoded.append(encodedData) - } - - return encoded - } - - /// Writes all appended body parts to the given file `URL`. - /// - /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, - /// this approach is very memory efficient and should be used for large body part data. - /// - /// - Parameter fileURL: File `URL` to which to write the form data. - /// - Throws: An `AFError` if encoding encounters an error. - public func writeEncodedData(to fileURL: URL) throws { - if let bodyPartError = bodyPartError { - throw bodyPartError - } - - if fileManager.fileExists(atPath: fileURL.path) { - throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) - } else if !fileURL.isFileURL { - throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) - } - - guard let outputStream = OutputStream(url: fileURL, append: false) else { - throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) - } - - outputStream.open() - defer { outputStream.close() } - - bodyParts.first?.hasInitialBoundary = true - bodyParts.last?.hasFinalBoundary = true - - for bodyPart in bodyParts { - try write(bodyPart, to: outputStream) - } - } - - // MARK: - Private - Body Part Encoding - - private func encode(_ bodyPart: BodyPart) throws -> Data { - var encoded = Data() - - let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - encoded.append(initialData) - - let headerData = encodeHeaders(for: bodyPart) - encoded.append(headerData) - - let bodyStreamData = try encodeBodyStream(for: bodyPart) - encoded.append(bodyStreamData) - - if bodyPart.hasFinalBoundary { - encoded.append(finalBoundaryData()) - } - - return encoded - } - - private func encodeHeaders(for bodyPart: BodyPart) -> Data { - let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" } - .joined() - + EncodingCharacters.crlf - - return Data(headerText.utf8) - } - - private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { - let inputStream = bodyPart.bodyStream - inputStream.open() - defer { inputStream.close() } - - var encoded = Data() - - while inputStream.hasBytesAvailable { - var buffer = [UInt8](repeating: 0, count: streamBufferSize) - let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) - - if let error = inputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) - } - - if bytesRead > 0 { - encoded.append(buffer, count: bytesRead) - } else { - break - } - } - - guard UInt64(encoded.count) == bodyPart.bodyContentLength else { - let error = AFError.UnexpectedInputStreamLength(bytesExpected: bodyPart.bodyContentLength, - bytesRead: UInt64(encoded.count)) - throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) - } - - return encoded - } - - // MARK: - Private - Writing Body Part to Output Stream - - private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { - try writeInitialBoundaryData(for: bodyPart, to: outputStream) - try writeHeaderData(for: bodyPart, to: outputStream) - try writeBodyStream(for: bodyPart, to: outputStream) - try writeFinalBoundaryData(for: bodyPart, to: outputStream) - } - - private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - return try write(initialData, to: outputStream) - } - - private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let headerData = encodeHeaders(for: bodyPart) - return try write(headerData, to: outputStream) - } - - private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let inputStream = bodyPart.bodyStream - - inputStream.open() - defer { inputStream.close() } - - var bytesLeftToRead = bodyPart.bodyContentLength - while inputStream.hasBytesAvailable && bytesLeftToRead > 0 { - let bufferSize = min(streamBufferSize, Int(bytesLeftToRead)) - var buffer = [UInt8](repeating: 0, count: bufferSize) - let bytesRead = inputStream.read(&buffer, maxLength: bufferSize) - - if let streamError = inputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) - } - - if bytesRead > 0 { - if buffer.count != bytesRead { - buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { - let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) - - if let error = outputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) - } - - bytesToWrite -= bytesWritten - - if bytesToWrite > 0 { - buffer = Array(buffer[bytesWritten.. HTTPHeaders { - var disposition = "form-data; name=\"\(name)\"" - if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } - - var headers: HTTPHeaders = [.contentDisposition(disposition)] - if let mimeType = mimeType { headers.add(.contentType(mimeType)) } - - return headers - } - - // MARK: - Private - Boundary Encoding - - private func initialBoundaryData() -> Data { - BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) - } - - private func encapsulatedBoundaryData() -> Data { - BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) - } - - private func finalBoundaryData() -> Data { - BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) - } - - // MARK: - Private - Errors - - private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { - guard bodyPartError == nil else { return } - bodyPartError = AFError.multipartEncodingFailed(reason: reason) - } -} - -#if canImport(UniformTypeIdentifiers) -import UniformTypeIdentifiers - -extension MultipartFormData { - // MARK: - Private - Mime Type - - private func mimeType(forPathExtension pathExtension: String) -> String { - #if swift(>=5.9) - if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, visionOS 1, *) { - return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream" - } else { - if - let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), - let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { - return contentType as String - } - - return "application/octet-stream" - } - #else - if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) { - return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream" - } else { - if - let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), - let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { - return contentType as String - } - - return "application/octet-stream" - } - #endif - } -} - -#else - -extension MultipartFormData { - // MARK: - Private - Mime Type - - private func mimeType(forPathExtension pathExtension: String) -> String { - #if canImport(CoreServices) || canImport(MobileCoreServices) - if - let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), - let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { - return contentType as String - } - #endif - - return "application/octet-stream" - } -} - -#endif diff --git a/Pods/Alamofire/Source/MultipartUpload.swift b/Pods/Alamofire/Source/MultipartUpload.swift deleted file mode 100644 index ceda21f..0000000 --- a/Pods/Alamofire/Source/MultipartUpload.swift +++ /dev/null @@ -1,89 +0,0 @@ -// -// MultipartUpload.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Internal type which encapsulates a `MultipartFormData` upload. -final class MultipartUpload { - lazy var result = Result { try build() } - - @Protected - private(set) var multipartFormData: MultipartFormData - let encodingMemoryThreshold: UInt64 - let request: URLRequestConvertible - let fileManager: FileManager - - init(encodingMemoryThreshold: UInt64, - request: URLRequestConvertible, - multipartFormData: MultipartFormData) { - self.encodingMemoryThreshold = encodingMemoryThreshold - self.request = request - fileManager = multipartFormData.fileManager - self.multipartFormData = multipartFormData - } - - func build() throws -> UploadRequest.Uploadable { - let uploadable: UploadRequest.Uploadable - if $multipartFormData.contentLength < encodingMemoryThreshold { - let data = try $multipartFormData.read { try $0.encode() } - - uploadable = .data(data) - } else { - let tempDirectoryURL = fileManager.temporaryDirectory - let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") - let fileName = UUID().uuidString - let fileURL = directoryURL.appendingPathComponent(fileName) - - try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) - - do { - try $multipartFormData.read { try $0.writeEncodedData(to: fileURL) } - } catch { - // Cleanup after attempted write if it fails. - try? fileManager.removeItem(at: fileURL) - throw error - } - - uploadable = .file(fileURL, shouldRemove: true) - } - - return uploadable - } -} - -extension MultipartUpload: UploadConvertible { - func asURLRequest() throws -> URLRequest { - var urlRequest = try request.asURLRequest() - - $multipartFormData.read { multipartFormData in - urlRequest.headers.add(.contentType(multipartFormData.contentType)) - } - - return urlRequest - } - - func createUploadable() throws -> UploadRequest.Uploadable { - try result.get() - } -} diff --git a/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Pods/Alamofire/Source/NetworkReachabilityManager.swift deleted file mode 100644 index 8ba715b..0000000 --- a/Pods/Alamofire/Source/NetworkReachabilityManager.swift +++ /dev/null @@ -1,301 +0,0 @@ -// -// NetworkReachabilityManager.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#if canImport(SystemConfiguration) - -import Foundation -import SystemConfiguration - -/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular and -/// WiFi network interfaces. -/// -/// Reachability can be used to determine background information about why a network operation failed, or to retry -/// network requests when a connection is established. It should not be used to prevent a user from initiating a network -/// request, as it's possible that an initial request may be required to establish reachability. -open class NetworkReachabilityManager { - /// Defines the various states of network reachability. - public enum NetworkReachabilityStatus { - /// It is unknown whether the network is reachable. - case unknown - /// The network is not reachable. - case notReachable - /// The network is reachable on the associated `ConnectionType`. - case reachable(ConnectionType) - - init(_ flags: SCNetworkReachabilityFlags) { - guard flags.isActuallyReachable else { self = .notReachable; return } - - var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) - - if flags.isCellular { networkStatus = .reachable(.cellular) } - - self = networkStatus - } - - /// Defines the various connection types detected by reachability flags. - public enum ConnectionType { - /// The connection type is either over Ethernet or WiFi. - case ethernetOrWiFi - /// The connection type is a cellular connection. - case cellular - } - } - - /// A closure executed when the network reachability status changes. The closure takes a single argument: the - /// network reachability status. - public typealias Listener = (NetworkReachabilityStatus) -> Void - - /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`. - public static let `default` = NetworkReachabilityManager() - - // MARK: - Properties - - /// Whether the network is currently reachable. - open var isReachable: Bool { isReachableOnCellular || isReachableOnEthernetOrWiFi } - - /// Whether the network is currently reachable over the cellular interface. - /// - /// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended. - /// Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued. - /// - open var isReachableOnCellular: Bool { status == .reachable(.cellular) } - - /// Whether the network is currently reachable over Ethernet or WiFi interface. - open var isReachableOnEthernetOrWiFi: Bool { status == .reachable(.ethernetOrWiFi) } - - /// `DispatchQueue` on which reachability will update. - public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue") - - /// Flags of the current reachability type, if any. - open var flags: SCNetworkReachabilityFlags? { - var flags = SCNetworkReachabilityFlags() - - return SCNetworkReachabilityGetFlags(reachability, &flags) ? flags : nil - } - - /// The current network reachability status. - open var status: NetworkReachabilityStatus { - flags.map(NetworkReachabilityStatus.init) ?? .unknown - } - - /// Mutable state storage. - struct MutableState { - /// A closure executed when the network reachability status changes. - var listener: Listener? - /// `DispatchQueue` on which listeners will be called. - var listenerQueue: DispatchQueue? - /// Previously calculated status. - var previousStatus: NetworkReachabilityStatus? - } - - /// `SCNetworkReachability` instance providing notifications. - private let reachability: SCNetworkReachability - - /// Protected storage for mutable state. - @Protected - private var mutableState = MutableState() - - // MARK: - Initialization - - /// Creates an instance with the specified host. - /// - /// - Note: The `host` value must *not* contain a scheme, just the hostname. - /// - /// - Parameters: - /// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`). - public convenience init?(host: String) { - guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } - - self.init(reachability: reachability) - } - - /// Creates an instance that monitors the address 0.0.0.0. - /// - /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing - /// status of the device, both IPv4 and IPv6. - public convenience init?() { - var zero = sockaddr() - zero.sa_len = UInt8(MemoryLayout.size) - zero.sa_family = sa_family_t(AF_INET) - - guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil } - - self.init(reachability: reachability) - } - - private init(reachability: SCNetworkReachability) { - self.reachability = reachability - } - - deinit { - stopListening() - } - - // MARK: - Listening - - /// Starts listening for changes in network reachability status. - /// - /// - Note: Stops and removes any existing listener. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default. - /// - listener: `Listener` closure called when reachability changes. - /// - /// - Returns: `true` if listening was started successfully, `false` otherwise. - @discardableResult - open func startListening(onQueue queue: DispatchQueue = .main, - onUpdatePerforming listener: @escaping Listener) -> Bool { - stopListening() - - $mutableState.write { state in - state.listenerQueue = queue - state.listener = listener - } - - let weakManager = WeakManager(manager: self) - - var context = SCNetworkReachabilityContext( - version: 0, - info: Unmanaged.passUnretained(weakManager).toOpaque(), - retain: { info in - let unmanaged = Unmanaged.fromOpaque(info) - _ = unmanaged.retain() - - return UnsafeRawPointer(unmanaged.toOpaque()) - }, - release: { info in - let unmanaged = Unmanaged.fromOpaque(info) - unmanaged.release() - }, - copyDescription: { info in - let unmanaged = Unmanaged.fromOpaque(info) - let weakManager = unmanaged.takeUnretainedValue() - let description = weakManager.manager?.flags?.readableDescription ?? "nil" - - return Unmanaged.passRetained(description as CFString) - } - ) - let callback: SCNetworkReachabilityCallBack = { _, flags, info in - guard let info = info else { return } - - let weakManager = Unmanaged.fromOpaque(info).takeUnretainedValue() - weakManager.manager?.notifyListener(flags) - } - - let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue) - let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context) - - // Manually call listener to give initial state, since the framework may not. - if let currentFlags = flags { - reachabilityQueue.async { - self.notifyListener(currentFlags) - } - } - - return callbackAdded && queueAdded - } - - /// Stops listening for changes in network reachability status. - open func stopListening() { - SCNetworkReachabilitySetCallback(reachability, nil, nil) - SCNetworkReachabilitySetDispatchQueue(reachability, nil) - $mutableState.write { state in - state.listener = nil - state.listenerQueue = nil - state.previousStatus = nil - } - } - - // MARK: - Internal - Listener Notification - - /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed. - /// - /// - Note: Should only be called from the `reachabilityQueue`. - /// - /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status. - func notifyListener(_ flags: SCNetworkReachabilityFlags) { - let newStatus = NetworkReachabilityStatus(flags) - - $mutableState.write { state in - guard state.previousStatus != newStatus else { return } - - state.previousStatus = newStatus - - let listener = state.listener - state.listenerQueue?.async { listener?(newStatus) } - } - } - - private final class WeakManager { - weak var manager: NetworkReachabilityManager? - - init(manager: NetworkReachabilityManager?) { - self.manager = manager - } - } -} - -// MARK: - - -extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} - -extension SCNetworkReachabilityFlags { - var isReachable: Bool { contains(.reachable) } - var isConnectionRequired: Bool { contains(.connectionRequired) } - var canConnectAutomatically: Bool { contains(.connectionOnDemand) || contains(.connectionOnTraffic) } - var canConnectWithoutUserInteraction: Bool { canConnectAutomatically && !contains(.interventionRequired) } - var isActuallyReachable: Bool { isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) } - var isCellular: Bool { - #if swift(>=5.9) - #if os(iOS) || os(tvOS) || os(visionOS) - return contains(.isWWAN) - #else - return false - #endif - #else - #if os(iOS) || os(tvOS) - return contains(.isWWAN) - #else - return false - #endif - #endif - } - - /// Human readable `String` for all states, to help with debugging. - var readableDescription: String { - let W = isCellular ? "W" : "-" - let R = isReachable ? "R" : "-" - let c = isConnectionRequired ? "c" : "-" - let t = contains(.transientConnection) ? "t" : "-" - let i = contains(.interventionRequired) ? "i" : "-" - let C = contains(.connectionOnTraffic) ? "C" : "-" - let D = contains(.connectionOnDemand) ? "D" : "-" - let l = contains(.isLocalAddress) ? "l" : "-" - let d = contains(.isDirect) ? "d" : "-" - let a = contains(.connectionAutomatic) ? "a" : "-" - - return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)" - } -} -#endif diff --git a/Pods/Alamofire/Source/Notifications.swift b/Pods/Alamofire/Source/Notifications.swift deleted file mode 100644 index 66434b6..0000000 --- a/Pods/Alamofire/Source/Notifications.swift +++ /dev/null @@ -1,115 +0,0 @@ -// -// Notifications.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension Request { - /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`. - public static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume") - /// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`. - public static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend") - /// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`. - public static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel") - /// Posted when a `Request` is finished. The `Notification` contains the completed `Request`. - public static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish") - - /// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`. - public static let didResumeTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResumeTask") - /// Posted when a `URLSessionTask` is suspended. The `Notification` contains the `Request` associated with the `URLSessionTask`. - public static let didSuspendTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspendTask") - /// Posted when a `URLSessionTask` is cancelled. The `Notification` contains the `Request` associated with the `URLSessionTask`. - public static let didCancelTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancelTask") - /// Posted when a `URLSessionTask` is completed. The `Notification` contains the `Request` associated with the `URLSessionTask`. - public static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask") -} - -// MARK: - - -extension Notification { - /// The `Request` contained by the instance's `userInfo`, `nil` otherwise. - public var request: Request? { - userInfo?[String.requestKey] as? Request - } - - /// Convenience initializer for a `Notification` containing a `Request` payload. - /// - /// - Parameters: - /// - name: The name of the notification. - /// - request: The `Request` payload. - init(name: Notification.Name, request: Request) { - self.init(name: name, object: nil, userInfo: [String.requestKey: request]) - } -} - -extension NotificationCenter { - /// Convenience function for posting notifications with `Request` payloads. - /// - /// - Parameters: - /// - name: The name of the notification. - /// - request: The `Request` payload. - func postNotification(named name: Notification.Name, with request: Request) { - let notification = Notification(name: name, request: request) - post(notification) - } -} - -extension String { - /// User info dictionary key representing the `Request` associated with the notification. - fileprivate static let requestKey = "org.alamofire.notification.key.request" -} - -/// `EventMonitor` that provides Alamofire's notifications. -public final class AlamofireNotifications: EventMonitor { - public func requestDidResume(_ request: Request) { - NotificationCenter.default.postNotification(named: Request.didResumeNotification, with: request) - } - - public func requestDidSuspend(_ request: Request) { - NotificationCenter.default.postNotification(named: Request.didSuspendNotification, with: request) - } - - public func requestDidCancel(_ request: Request) { - NotificationCenter.default.postNotification(named: Request.didCancelNotification, with: request) - } - - public func requestDidFinish(_ request: Request) { - NotificationCenter.default.postNotification(named: Request.didFinishNotification, with: request) - } - - public func request(_ request: Request, didResumeTask task: URLSessionTask) { - NotificationCenter.default.postNotification(named: Request.didResumeTaskNotification, with: request) - } - - public func request(_ request: Request, didSuspendTask task: URLSessionTask) { - NotificationCenter.default.postNotification(named: Request.didSuspendTaskNotification, with: request) - } - - public func request(_ request: Request, didCancelTask task: URLSessionTask) { - NotificationCenter.default.postNotification(named: Request.didCancelTaskNotification, with: request) - } - - public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { - NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request) - } -} diff --git a/Pods/Alamofire/Source/OperationQueue+Alamofire.swift b/Pods/Alamofire/Source/OperationQueue+Alamofire.swift deleted file mode 100644 index b06a0cc..0000000 --- a/Pods/Alamofire/Source/OperationQueue+Alamofire.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// OperationQueue+Alamofire.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension OperationQueue { - /// Creates an instance using the provided parameters. - /// - /// - Parameters: - /// - qualityOfService: `QualityOfService` to be applied to the queue. `.default` by default. - /// - maxConcurrentOperationCount: Maximum concurrent operations. - /// `OperationQueue.defaultMaxConcurrentOperationCount` by default. - /// - underlyingQueue: Underlying `DispatchQueue`. `nil` by default. - /// - name: Name for the queue. `nil` by default. - /// - startSuspended: Whether the queue starts suspended. `false` by default. - convenience init(qualityOfService: QualityOfService = .default, - maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount, - underlyingQueue: DispatchQueue? = nil, - name: String? = nil, - startSuspended: Bool = false) { - self.init() - self.qualityOfService = qualityOfService - self.maxConcurrentOperationCount = maxConcurrentOperationCount - self.underlyingQueue = underlyingQueue - self.name = name - isSuspended = startSuspended - } -} diff --git a/Pods/Alamofire/Source/ParameterEncoder.swift b/Pods/Alamofire/Source/ParameterEncoder.swift deleted file mode 100644 index 8916978..0000000 --- a/Pods/Alamofire/Source/ParameterEncoder.swift +++ /dev/null @@ -1,213 +0,0 @@ -// -// ParameterEncoder.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that can encode any `Encodable` type into a `URLRequest`. -public protocol ParameterEncoder { - /// Encode the provided `Encodable` parameters into `request`. - /// - /// - Parameters: - /// - parameters: The `Encodable` parameter value. - /// - request: The `URLRequest` into which to encode the parameters. - /// - /// - Returns: A `URLRequest` with the result of the encoding. - /// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of - /// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`. - func encode(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest -} - -/// A `ParameterEncoder` that encodes types as JSON body data. -/// -/// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`. -open class JSONParameterEncoder: ParameterEncoder { - /// Returns an encoder with default parameters. - public static var `default`: JSONParameterEncoder { JSONParameterEncoder() } - - /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`. - public static var prettyPrinted: JSONParameterEncoder { - let encoder = JSONEncoder() - encoder.outputFormatting = .prettyPrinted - - return JSONParameterEncoder(encoder: encoder) - } - - /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`. - @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) - public static var sortedKeys: JSONParameterEncoder { - let encoder = JSONEncoder() - encoder.outputFormatting = .sortedKeys - - return JSONParameterEncoder(encoder: encoder) - } - - /// `JSONEncoder` used to encode parameters. - public let encoder: JSONEncoder - - /// Creates an instance with the provided `JSONEncoder`. - /// - /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default. - public init(encoder: JSONEncoder = JSONEncoder()) { - self.encoder = encoder - } - - open func encode(_ parameters: Parameters?, - into request: URLRequest) throws -> URLRequest { - guard let parameters = parameters else { return request } - - var request = request - - do { - let data = try encoder.encode(parameters) - request.httpBody = data - if request.headers["Content-Type"] == nil { - request.headers.update(.contentType("application/json")) - } - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return request - } -} - -extension ParameterEncoder where Self == JSONParameterEncoder { - /// Provides a default `JSONParameterEncoder` instance. - public static var json: JSONParameterEncoder { JSONParameterEncoder() } - - /// Creates a `JSONParameterEncoder` using the provided `JSONEncoder`. - /// - /// - Parameter encoder: `JSONEncoder` used to encode parameters. `JSONEncoder()` by default. - /// - Returns: The `JSONParameterEncoder`. - public static func json(encoder: JSONEncoder = JSONEncoder()) -> JSONParameterEncoder { - JSONParameterEncoder(encoder: encoder) - } -} - -/// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending -/// on the `Destination` set. -/// -/// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to -/// `application/x-www-form-urlencoded; charset=utf-8`. -/// -/// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer. -open class URLEncodedFormParameterEncoder: ParameterEncoder { - /// Defines where the URL-encoded string should be set for each `URLRequest`. - public enum Destination { - /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request. - /// Sets it to the `httpBody` for all other methods. - case methodDependent - /// Applies the encoded query string to any existing query string from the `URLRequest`. - case queryString - /// Applies the encoded query string to the `httpBody` of the `URLRequest`. - case httpBody - - /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`. - /// - /// - Parameter method: The `HTTPMethod`. - /// - /// - Returns: Whether the URL-encoded string should be applied to a `URL`. - func encodesParametersInURL(for method: HTTPMethod) -> Bool { - switch self { - case .methodDependent: return [.get, .head, .delete].contains(method) - case .queryString: return true - case .httpBody: return false - } - } - } - - /// Returns an encoder with default parameters. - public static var `default`: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } - - /// The `URLEncodedFormEncoder` to use. - public let encoder: URLEncodedFormEncoder - - /// The `Destination` for the URL-encoded string. - public let destination: Destination - - /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value. - /// - /// - Parameters: - /// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default. - /// - destination: The `Destination`. `.methodDependent` by default. - public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) { - self.encoder = encoder - self.destination = destination - } - - open func encode(_ parameters: Parameters?, - into request: URLRequest) throws -> URLRequest { - guard let parameters = parameters else { return request } - - var request = request - - guard let url = request.url else { - throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) - } - - guard let method = request.method else { - let rawValue = request.method?.rawValue ?? "nil" - throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue))) - } - - if destination.encodesParametersInURL(for: method), - var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { - let query: String = try Result { try encoder.encode(parameters) } - .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() - let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands() - components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString - - guard let newURL = components.url else { - throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) - } - - request.url = newURL - } else { - if request.headers["Content-Type"] == nil { - request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) - } - - request.httpBody = try Result { try encoder.encode(parameters) } - .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() - } - - return request - } -} - -extension ParameterEncoder where Self == URLEncodedFormParameterEncoder { - /// Provides a default `URLEncodedFormParameterEncoder` instance. - public static var urlEncodedForm: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } - - /// Creates a `URLEncodedFormParameterEncoder` with the provided encoder and destination. - /// - /// - Parameters: - /// - encoder: `URLEncodedFormEncoder` used to encode the parameters. `URLEncodedFormEncoder()` by default. - /// - destination: `Destination` to which to encode the parameters. `.methodDependent` by default. - /// - Returns: The `URLEncodedFormParameterEncoder`. - public static func urlEncodedForm(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), - destination: URLEncodedFormParameterEncoder.Destination = .methodDependent) -> URLEncodedFormParameterEncoder { - URLEncodedFormParameterEncoder(encoder: encoder, destination: destination) - } -} diff --git a/Pods/Alamofire/Source/ParameterEncoding.swift b/Pods/Alamofire/Source/ParameterEncoding.swift deleted file mode 100644 index ea61256..0000000 --- a/Pods/Alamofire/Source/ParameterEncoding.swift +++ /dev/null @@ -1,346 +0,0 @@ -// -// ParameterEncoding.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A dictionary of parameters to apply to a `URLRequest`. -public typealias Parameters = [String: Any] - -/// A type used to define how a set of parameters are applied to a `URLRequest`. -public protocol ParameterEncoding { - /// Creates a `URLRequest` by encoding parameters and applying them on the passed request. - /// - /// - Parameters: - /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. - /// - parameters: `Parameters` to encode onto the request. - /// - /// - Returns: The encoded `URLRequest`. - /// - Throws: Any `Error` produced during parameter encoding. - func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest -} - -// MARK: - - -/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP -/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as -/// the HTTP body depends on the destination of the encoding. -/// -/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to -/// `application/x-www-form-urlencoded; charset=utf-8`. -/// -/// There is no published specification for how to encode collection types. By default the convention of appending -/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for -/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the -/// square brackets appended to array keys. -/// -/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode -/// `true` as 1 and `false` as 0. -public struct URLEncoding: ParameterEncoding { - // MARK: Helper Types - - /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the - /// resulting URL request. - public enum Destination { - /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and - /// sets as the HTTP body for requests with any other HTTP method. - case methodDependent - /// Sets or appends encoded query string result to existing query string. - case queryString - /// Sets encoded query string result as the HTTP body of the URL request. - case httpBody - - func encodesParametersInURL(for method: HTTPMethod) -> Bool { - switch self { - case .methodDependent: return [.get, .head, .delete].contains(method) - case .queryString: return true - case .httpBody: return false - } - } - } - - /// Configures how `Array` parameters are encoded. - public enum ArrayEncoding { - /// An empty set of square brackets is appended to the key for every value. This is the default behavior. - case brackets - /// No brackets are appended. The key is encoded as is. - case noBrackets - /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. - case indexInBrackets - /// Provide a custom array key encoding with the given closure. - case custom((_ key: String, _ index: Int) -> String) - - func encode(key: String, atIndex index: Int) -> String { - switch self { - case .brackets: - return "\(key)[]" - case .noBrackets: - return key - case .indexInBrackets: - return "\(key)[\(index)]" - case let .custom(encoding): - return encoding(key, index) - } - } - } - - /// Configures how `Bool` parameters are encoded. - public enum BoolEncoding { - /// Encode `true` as `1` and `false` as `0`. This is the default behavior. - case numeric - /// Encode `true` and `false` as string literals. - case literal - - func encode(value: Bool) -> String { - switch self { - case .numeric: - return value ? "1" : "0" - case .literal: - return value ? "true" : "false" - } - } - } - - // MARK: Properties - - /// Returns a default `URLEncoding` instance with a `.methodDependent` destination. - public static var `default`: URLEncoding { URLEncoding() } - - /// Returns a `URLEncoding` instance with a `.queryString` destination. - public static var queryString: URLEncoding { URLEncoding(destination: .queryString) } - - /// Returns a `URLEncoding` instance with an `.httpBody` destination. - public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) } - - /// The destination defining where the encoded query string is to be applied to the URL request. - public let destination: Destination - - /// The encoding to use for `Array` parameters. - public let arrayEncoding: ArrayEncoding - - /// The encoding to use for `Bool` parameters. - public let boolEncoding: BoolEncoding - - // MARK: Initialization - - /// Creates an instance using the specified parameters. - /// - /// - Parameters: - /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by - /// default. - /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default. - /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default. - public init(destination: Destination = .methodDependent, - arrayEncoding: ArrayEncoding = .brackets, - boolEncoding: BoolEncoding = .numeric) { - self.destination = destination - self.arrayEncoding = arrayEncoding - self.boolEncoding = boolEncoding - } - - // MARK: Encoding - - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - if let method = urlRequest.method, destination.encodesParametersInURL(for: method) { - guard let url = urlRequest.url else { - throw AFError.parameterEncodingFailed(reason: .missingURL) - } - - if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { - let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) - urlComponents.percentEncodedQuery = percentEncodedQuery - urlRequest.url = urlComponents.url - } - } else { - if urlRequest.headers["Content-Type"] == nil { - urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) - } - - urlRequest.httpBody = Data(query(parameters).utf8) - } - - return urlRequest - } - - /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively. - /// - /// - Parameters: - /// - key: Key of the query component. - /// - value: Value of the query component. - /// - /// - Returns: The percent-escaped, URL encoded query string components. - public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { - var components: [(String, String)] = [] - switch value { - case let dictionary as [String: Any]: - for (nestedKey, value) in dictionary { - components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) - } - case let array as [Any]: - for (index, value) in array.enumerated() { - components += queryComponents(fromKey: arrayEncoding.encode(key: key, atIndex: index), value: value) - } - case let number as NSNumber: - if number.isBool { - components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue)))) - } else { - components.append((escape(key), escape("\(number)"))) - } - case let bool as Bool: - components.append((escape(key), escape(boolEncoding.encode(value: bool)))) - default: - components.append((escape(key), escape("\(value)"))) - } - return components - } - - /// Creates a percent-escaped string following RFC 3986 for a query string key or value. - /// - /// - Parameter string: `String` to be percent-escaped. - /// - /// - Returns: The percent-escaped `String`. - public func escape(_ string: String) -> String { - string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string - } - - private func query(_ parameters: [String: Any]) -> String { - var components: [(String, String)] = [] - - for key in parameters.keys.sorted(by: <) { - let value = parameters[key]! - components += queryComponents(fromKey: key, value: value) - } - return components.map { "\($0)=\($1)" }.joined(separator: "&") - } -} - -// MARK: - - -/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the -/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. -public struct JSONEncoding: ParameterEncoding { - public enum Error: Swift.Error { - case invalidJSONObject - } - - // MARK: Properties - - /// Returns a `JSONEncoding` instance with default writing options. - public static var `default`: JSONEncoding { JSONEncoding() } - - /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. - public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) } - - /// The options for writing the parameters as JSON data. - public let options: JSONSerialization.WritingOptions - - // MARK: Initialization - - /// Creates an instance using the specified `WritingOptions`. - /// - /// - Parameter options: `JSONSerialization.WritingOptions` to use. - public init(options: JSONSerialization.WritingOptions = []) { - self.options = options - } - - // MARK: Encoding - - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - guard JSONSerialization.isValidJSONObject(parameters) else { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) - } - - do { - let data = try JSONSerialization.data(withJSONObject: parameters, options: options) - - if urlRequest.headers["Content-Type"] == nil { - urlRequest.headers.update(.contentType("application/json")) - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return urlRequest - } - - /// Encodes any JSON compatible object into a `URLRequest`. - /// - /// - Parameters: - /// - urlRequest: `URLRequestConvertible` value into which the object will be encoded. - /// - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default. - /// - /// - Returns: The encoded `URLRequest`. - /// - Throws: Any `Error` produced during encoding. - public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let jsonObject = jsonObject else { return urlRequest } - - guard JSONSerialization.isValidJSONObject(jsonObject) else { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) - } - - do { - let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) - - if urlRequest.headers["Content-Type"] == nil { - urlRequest.headers.update(.contentType("application/json")) - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return urlRequest - } -} - -extension JSONEncoding.Error { - public var localizedDescription: String { - """ - Invalid JSON object provided for parameter or object encoding. \ - This is most likely due to a value which can't be represented in Objective-C. - """ - } -} - -// MARK: - - -extension NSNumber { - fileprivate var isBool: Bool { - // Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of - // swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22). - String(cString: objCType) == "c" - } -} diff --git a/Pods/Alamofire/Source/Protected.swift b/Pods/Alamofire/Source/Protected.swift deleted file mode 100644 index 9449412..0000000 --- a/Pods/Alamofire/Source/Protected.swift +++ /dev/null @@ -1,161 +0,0 @@ -// -// Protected.swift -// -// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -private protocol Lock { - func lock() - func unlock() -} - -extension Lock { - /// Executes a closure returning a value while acquiring the lock. - /// - /// - Parameter closure: The closure to run. - /// - /// - Returns: The value the closure generated. - func around(_ closure: () throws -> T) rethrows -> T { - lock(); defer { unlock() } - return try closure() - } - - /// Execute a closure while acquiring the lock. - /// - /// - Parameter closure: The closure to run. - func around(_ closure: () throws -> Void) rethrows { - lock(); defer { unlock() } - try closure() - } -} - -#if os(Linux) || os(Windows) || os(Android) - -extension NSLock: Lock {} - -#endif - -#if canImport(Darwin) -/// An `os_unfair_lock` wrapper. -final class UnfairLock: Lock { - private let unfairLock: os_unfair_lock_t - - init() { - unfairLock = .allocate(capacity: 1) - unfairLock.initialize(to: os_unfair_lock()) - } - - deinit { - unfairLock.deinitialize(count: 1) - unfairLock.deallocate() - } - - fileprivate func lock() { - os_unfair_lock_lock(unfairLock) - } - - fileprivate func unlock() { - os_unfair_lock_unlock(unfairLock) - } -} -#endif - -/// A thread-safe wrapper around a value. -@propertyWrapper -@dynamicMemberLookup -final class Protected { - #if canImport(Darwin) - private let lock = UnfairLock() - #elseif os(Linux) || os(Windows) || os(Android) - private let lock = NSLock() - #endif - private var value: T - - init(_ value: T) { - self.value = value - } - - /// The contained value. Unsafe for anything more than direct read or write. - var wrappedValue: T { - get { lock.around { value } } - set { lock.around { value = newValue } } - } - - var projectedValue: Protected { self } - - init(wrappedValue: T) { - value = wrappedValue - } - - /// Synchronously read or transform the contained value. - /// - /// - Parameter closure: The closure to execute. - /// - /// - Returns: The return value of the closure passed. - func read(_ closure: (T) throws -> U) rethrows -> U { - try lock.around { try closure(self.value) } - } - - /// Synchronously modify the protected value. - /// - /// - Parameter closure: The closure to execute. - /// - /// - Returns: The modified value. - @discardableResult - func write(_ closure: (inout T) throws -> U) rethrows -> U { - try lock.around { try closure(&self.value) } - } - - subscript(dynamicMember keyPath: WritableKeyPath) -> Property { - get { lock.around { value[keyPath: keyPath] } } - set { lock.around { value[keyPath: keyPath] = newValue } } - } - - subscript(dynamicMember keyPath: KeyPath) -> Property { - lock.around { value[keyPath: keyPath] } - } -} - -extension Protected where T == Request.MutableState { - /// Attempts to transition to the passed `State`. - /// - /// - Parameter state: The `State` to attempt transition to. - /// - /// - Returns: Whether the transition occurred. - func attemptToTransitionTo(_ state: Request.State) -> Bool { - lock.around { - guard value.state.canTransitionTo(state) else { return false } - - value.state = state - - return true - } - } - - /// Perform a closure while locked with the provided `Request.State`. - /// - /// - Parameter perform: The closure to perform while locked. - func withState(perform: (Request.State) -> Void) { - lock.around { perform(value.state) } - } -} diff --git a/Pods/Alamofire/Source/RedirectHandler.swift b/Pods/Alamofire/Source/RedirectHandler.swift deleted file mode 100644 index cf88abf..0000000 --- a/Pods/Alamofire/Source/RedirectHandler.swift +++ /dev/null @@ -1,111 +0,0 @@ -// -// RedirectHandler.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that handles how an HTTP redirect response from a remote server should be redirected to the new request. -public protocol RedirectHandler { - /// Determines how the HTTP redirect response should be redirected to the new request. - /// - /// The `completion` closure should be passed one of three possible options: - /// - /// 1. The new request specified by the redirect (this is the most common use case). - /// 2. A modified version of the new request (you may want to route it somewhere else). - /// 3. A `nil` value to deny the redirect request and return the body of the redirect response. - /// - /// - Parameters: - /// - task: The `URLSessionTask` whose request resulted in a redirect. - /// - request: The `URLRequest` to the new location specified by the redirect response. - /// - response: The `HTTPURLResponse` containing the server's response to the original request. - /// - completion: The closure to execute containing the new `URLRequest`, a modified `URLRequest`, or `nil`. - func task(_ task: URLSessionTask, - willBeRedirectedTo request: URLRequest, - for response: HTTPURLResponse, - completion: @escaping (URLRequest?) -> Void) -} - -// MARK: - - -/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect. -public struct Redirector { - /// Defines the behavior of the `Redirector` type. - public enum Behavior { - /// Follow the redirect as defined in the response. - case follow - /// Do not follow the redirect defined in the response. - case doNotFollow - /// Modify the redirect request defined in the response. - case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) - } - - /// Returns a `Redirector` with a `.follow` `Behavior`. - public static let follow = Redirector(behavior: .follow) - /// Returns a `Redirector` with a `.doNotFollow` `Behavior`. - public static let doNotFollow = Redirector(behavior: .doNotFollow) - - /// The `Behavior` of the `Redirector`. - public let behavior: Behavior - - /// Creates a `Redirector` instance from the `Behavior`. - /// - /// - Parameter behavior: The `Behavior`. - public init(behavior: Behavior) { - self.behavior = behavior - } -} - -// MARK: - - -extension Redirector: RedirectHandler { - public func task(_ task: URLSessionTask, - willBeRedirectedTo request: URLRequest, - for response: HTTPURLResponse, - completion: @escaping (URLRequest?) -> Void) { - switch behavior { - case .follow: - completion(request) - case .doNotFollow: - completion(nil) - case let .modify(closure): - let request = closure(task, request, response) - completion(request) - } - } -} - -extension RedirectHandler where Self == Redirector { - /// Provides a `Redirector` which follows redirects. Equivalent to `Redirector.follow`. - public static var follow: Redirector { .follow } - - /// Provides a `Redirector` which does not follow redirects. Equivalent to `Redirector.doNotFollow`. - public static var doNotFollow: Redirector { .doNotFollow } - - /// Creates a `Redirector` which modifies the redirected `URLRequest` using the provided closure. - /// - /// - Parameter closure: Closure used to modify the redirect. - /// - Returns: The `Redirector`. - public static func modify(using closure: @escaping (URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) -> Redirector { - Redirector(behavior: .modify(closure)) - } -} diff --git a/Pods/Alamofire/Source/Request.swift b/Pods/Alamofire/Source/Request.swift deleted file mode 100644 index fbae9db..0000000 --- a/Pods/Alamofire/Source/Request.swift +++ /dev/null @@ -1,2070 +0,0 @@ -// -// Request.swift -// -// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback -/// handling. -public class Request { - /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or - /// `cancel()` on the `Request`. - public enum State { - /// Initial state of the `Request`. - case initialized - /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on - /// them in this state. - case resumed - /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on - /// them in this state. - case suspended - /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on - /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition - /// to any other state. - case cancelled - /// `State` set when all response serialization completion closures have been cleared on the `Request` and - /// enqueued on their respective queues. - case finished - - /// Determines whether `self` can be transitioned to the provided `State`. - func canTransitionTo(_ state: State) -> Bool { - switch (self, state) { - case (.initialized, _): - return true - case (_, .initialized), (.cancelled, _), (.finished, _): - return false - case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed): - return true - case (.suspended, .suspended), (.resumed, .resumed): - return false - case (_, .finished): - return true - } - } - } - - // MARK: - Initial State - - /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances. - public let id: UUID - /// The serial queue for all internal async actions. - public let underlyingQueue: DispatchQueue - /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`. - public let serializationQueue: DispatchQueue - /// `EventMonitor` used for event callbacks. - public let eventMonitor: EventMonitor? - /// The `Request`'s interceptor. - public let interceptor: RequestInterceptor? - /// The `Request`'s delegate. - public private(set) weak var delegate: RequestDelegate? - - // MARK: - Mutable State - - /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`. - struct MutableState { - /// State of the `Request`. - var state: State = .initialized - /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks. - var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? - /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks. - var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? - /// `RedirectHandler` provided for to handle request redirection. - var redirectHandler: RedirectHandler? - /// `CachedResponseHandler` provided to handle response caching. - var cachedResponseHandler: CachedResponseHandler? - /// Queue and closure called when the `Request` is able to create a cURL description of itself. - var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)? - /// Queue and closure called when the `Request` creates a `URLRequest`. - var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)? - /// Queue and closure called when the `Request` creates a `URLSessionTask`. - var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)? - /// Response serialization closures that handle response parsing. - var responseSerializers: [() -> Void] = [] - /// Response serialization completion closures executed once all response serializers are complete. - var responseSerializerCompletions: [() -> Void] = [] - /// Whether response serializer processing is finished. - var responseSerializerProcessingFinished = false - /// `URLCredential` used for authentication challenges. - var credential: URLCredential? - /// All `URLRequest`s created by Alamofire on behalf of the `Request`. - var requests: [URLRequest] = [] - /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`. - var tasks: [URLSessionTask] = [] - /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond - /// exactly the the `tasks` created. - var metrics: [URLSessionTaskMetrics] = [] - /// Number of times any retriers provided retried the `Request`. - var retryCount = 0 - /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`. - var error: AFError? - /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a - /// representation in the state machine in the future. - var isFinishing = false - /// Actions to run when requests are finished. Use for concurrency support. - var finishHandlers: [() -> Void] = [] - } - - /// Protected `MutableState` value that provides thread-safe access to state values. - @Protected - fileprivate var mutableState = MutableState() - - /// `State` of the `Request`. - public var state: State { $mutableState.state } - /// Returns whether `state` is `.initialized`. - public var isInitialized: Bool { state == .initialized } - /// Returns whether `state is `.resumed`. - public var isResumed: Bool { state == .resumed } - /// Returns whether `state` is `.suspended`. - public var isSuspended: Bool { state == .suspended } - /// Returns whether `state` is `.cancelled`. - public var isCancelled: Bool { state == .cancelled } - /// Returns whether `state` is `.finished`. - public var isFinished: Bool { state == .finished } - - // MARK: Progress - - /// Closure type executed when monitoring the upload or download progress of a request. - public typealias ProgressHandler = (Progress) -> Void - - /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried. - public let uploadProgress = Progress(totalUnitCount: 0) - /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried. - public let downloadProgress = Progress(totalUnitCount: 0) - /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`. - private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { - get { $mutableState.uploadProgressHandler } - set { $mutableState.uploadProgressHandler = newValue } - } - - /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. - fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { - get { $mutableState.downloadProgressHandler } - set { $mutableState.downloadProgressHandler = newValue } - } - - // MARK: Redirect Handling - - /// `RedirectHandler` set on the instance. - public private(set) var redirectHandler: RedirectHandler? { - get { $mutableState.redirectHandler } - set { $mutableState.redirectHandler = newValue } - } - - // MARK: Cached Response Handling - - /// `CachedResponseHandler` set on the instance. - public private(set) var cachedResponseHandler: CachedResponseHandler? { - get { $mutableState.cachedResponseHandler } - set { $mutableState.cachedResponseHandler = newValue } - } - - // MARK: URLCredential - - /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. - public private(set) var credential: URLCredential? { - get { $mutableState.credential } - set { $mutableState.credential = newValue } - } - - // MARK: Validators - - /// `Validator` callback closures that store the validation calls enqueued. - @Protected - fileprivate var validators: [() -> Void] = [] - - // MARK: URLRequests - - /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests. - public var requests: [URLRequest] { $mutableState.requests } - /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. - public var firstRequest: URLRequest? { requests.first } - /// Last `URLRequest` created on behalf of the `Request`. - public var lastRequest: URLRequest? { requests.last } - /// Current `URLRequest` created on behalf of the `Request`. - public var request: URLRequest? { lastRequest } - - /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from - /// `requests` due to `URLSession` manipulation. - public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap(\.currentRequest) } } - - // MARK: HTTPURLResponse - - /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the - /// last `URLSessionTask`. - public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse } - - // MARK: Tasks - - /// All `URLSessionTask`s created on behalf of the `Request`. - public var tasks: [URLSessionTask] { $mutableState.tasks } - /// First `URLSessionTask` created on behalf of the `Request`. - public var firstTask: URLSessionTask? { tasks.first } - /// Last `URLSessionTask` created on behalf of the `Request`. - public var lastTask: URLSessionTask? { tasks.last } - /// Current `URLSessionTask` created on behalf of the `Request`. - public var task: URLSessionTask? { lastTask } - - // MARK: Metrics - - /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. - public var allMetrics: [URLSessionTaskMetrics] { $mutableState.metrics } - /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. - public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first } - /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. - public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last } - /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. - public var metrics: URLSessionTaskMetrics? { lastMetrics } - - // MARK: Retry Count - - /// Number of times the `Request` has been retried. - public var retryCount: Int { $mutableState.retryCount } - - // MARK: Error - - /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. - public fileprivate(set) var error: AFError? { - get { $mutableState.error } - set { $mutableState.error = newValue } - } - - /// Default initializer for the `Request` superclass. - /// - /// - Parameters: - /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. - /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. - /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets - /// `underlyingQueue`, but can be passed another queue from a `Session`. - /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. - /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. - /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. - init(id: UUID = UUID(), - underlyingQueue: DispatchQueue, - serializationQueue: DispatchQueue, - eventMonitor: EventMonitor?, - interceptor: RequestInterceptor?, - delegate: RequestDelegate) { - self.id = id - self.underlyingQueue = underlyingQueue - self.serializationQueue = serializationQueue - self.eventMonitor = eventMonitor - self.interceptor = interceptor - self.delegate = delegate - } - - // MARK: - Internal Event API - - // All API must be called from underlyingQueue. - - /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, - /// the `URLRequest` will be adapted before being issued. - /// - /// - Parameter request: The `URLRequest` created. - func didCreateInitialURLRequest(_ request: URLRequest) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - $mutableState.write { $0.requests.append(request) } - - eventMonitor?.request(self, didCreateInitialURLRequest: request) - } - - /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. - /// - /// - Note: Triggers retry. - /// - /// - Parameter error: `AFError` thrown from the failed creation. - func didFailToCreateURLRequest(with error: AFError) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - self.error = error - - eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) - - callCURLHandlerIfNecessary() - - retryOrFinish(error: error) - } - - /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`. - /// - /// - Parameters: - /// - initialRequest: The `URLRequest` that was adapted. - /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`. - func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - $mutableState.write { $0.requests.append(adaptedRequest) } - - eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) - } - - /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. - /// - /// - Note: Triggers retry. - /// - /// - Parameters: - /// - request: The `URLRequest` the adapter was called with. - /// - error: The `AFError` returned by the `RequestAdapter`. - func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - self.error = error - - eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) - - callCURLHandlerIfNecessary() - - retryOrFinish(error: error) - } - - /// Final `URLRequest` has been created for the instance. - /// - /// - Parameter request: The `URLRequest` created. - func didCreateURLRequest(_ request: URLRequest) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - $mutableState.read { state in - state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) } - } - - eventMonitor?.request(self, didCreateURLRequest: request) - - callCURLHandlerIfNecessary() - } - - /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. - private func callCURLHandlerIfNecessary() { - $mutableState.write { mutableState in - guard let cURLHandler = mutableState.cURLHandler else { return } - - cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) } - - mutableState.cURLHandler = nil - } - } - - /// Called when a `URLSessionTask` is created on behalf of the instance. - /// - /// - Parameter task: The `URLSessionTask` created. - func didCreateTask(_ task: URLSessionTask) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - $mutableState.write { state in - state.tasks.append(task) - - guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return } - - urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) } - } - - eventMonitor?.request(self, didCreateTask: task) - } - - /// Called when resumption is completed. - func didResume() { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - eventMonitor?.requestDidResume(self) - } - - /// Called when a `URLSessionTask` is resumed on behalf of the instance. - /// - /// - Parameter task: The `URLSessionTask` resumed. - func didResumeTask(_ task: URLSessionTask) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - eventMonitor?.request(self, didResumeTask: task) - } - - /// Called when suspension is completed. - func didSuspend() { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - eventMonitor?.requestDidSuspend(self) - } - - /// Called when a `URLSessionTask` is suspended on behalf of the instance. - /// - /// - Parameter task: The `URLSessionTask` suspended. - func didSuspendTask(_ task: URLSessionTask) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - eventMonitor?.request(self, didSuspendTask: task) - } - - /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. - func didCancel() { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - $mutableState.write { mutableState in - mutableState.error = mutableState.error ?? AFError.explicitlyCancelled - } - - eventMonitor?.requestDidCancel(self) - } - - /// Called when a `URLSessionTask` is cancelled on behalf of the instance. - /// - /// - Parameter task: The `URLSessionTask` cancelled. - func didCancelTask(_ task: URLSessionTask) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - eventMonitor?.request(self, didCancelTask: task) - } - - /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance. - /// - /// - Parameter metrics: The `URLSessionTaskMetrics` gathered. - func didGatherMetrics(_ metrics: URLSessionTaskMetrics) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - $mutableState.write { $0.metrics.append(metrics) } - - eventMonitor?.request(self, didGatherMetrics: metrics) - } - - /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning. - /// - /// - Parameters: - /// - task: The `URLSessionTask` which failed. - /// - error: The early failure `AFError`. - func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - self.error = error - - // Task will still complete, so didCompleteTask(_:with:) will handle retry. - eventMonitor?.request(self, didFailTask: task, earlyWithError: error) - } - - /// Called when a `URLSessionTask` completes. All tasks will eventually call this method. - /// - /// - Note: Response validation is synchronously triggered in this step. - /// - /// - Parameters: - /// - task: The `URLSessionTask` which completed. - /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this - /// value is ignored. - func didCompleteTask(_ task: URLSessionTask, with error: AFError?) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - self.error = self.error ?? error - - validators.forEach { $0() } - - eventMonitor?.request(self, didCompleteTask: task, with: error) - - retryOrFinish(error: self.error) - } - - /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. - func prepareForRetry() { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - $mutableState.write { $0.retryCount += 1 } - - reset() - - eventMonitor?.requestIsRetrying(self) - } - - /// Called to determine whether retry will be triggered for the particular error, or whether the instance should - /// call `finish()`. - /// - /// - Parameter error: The possible `AFError` which may trigger retry. - func retryOrFinish(error: AFError?) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - guard !isCancelled, let error = error, let delegate = delegate else { finish(); return } - - delegate.retryResult(for: self, dueTo: error) { retryResult in - switch retryResult { - case .doNotRetry: - self.finish() - case let .doNotRetryWithError(retryError): - self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError")) - case .retry, .retryWithDelay: - delegate.retryRequest(self, withDelay: retryResult.delay) - } - } - } - - /// Finishes this `Request` and starts the response serializers. - /// - /// - Parameter error: The possible `Error` with which the instance will finish. - func finish(error: AFError? = nil) { - dispatchPrecondition(condition: .onQueue(underlyingQueue)) - - guard !$mutableState.isFinishing else { return } - - $mutableState.isFinishing = true - - if let error = error { self.error = error } - - // Start response handlers - processNextResponseSerializer() - - eventMonitor?.requestDidFinish(self) - } - - /// Appends the response serialization closure to the instance. - /// - /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. - /// - /// - Parameter closure: The closure containing the response serialization call. - func appendResponseSerializer(_ closure: @escaping () -> Void) { - $mutableState.write { mutableState in - mutableState.responseSerializers.append(closure) - - if mutableState.state == .finished { - mutableState.state = .resumed - } - - if mutableState.responseSerializerProcessingFinished { - underlyingQueue.async { self.processNextResponseSerializer() } - } - - if mutableState.state.canTransitionTo(.resumed) { - underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } } - } - } - } - - /// Returns the next response serializer closure to execute if there's one left. - /// - /// - Returns: The next response serialization closure, if there is one. - func nextResponseSerializer() -> (() -> Void)? { - var responseSerializer: (() -> Void)? - - $mutableState.write { mutableState in - let responseSerializerIndex = mutableState.responseSerializerCompletions.count - - if responseSerializerIndex < mutableState.responseSerializers.count { - responseSerializer = mutableState.responseSerializers[responseSerializerIndex] - } - } - - return responseSerializer - } - - /// Processes the next response serializer and calls all completions if response serialization is complete. - func processNextResponseSerializer() { - guard let responseSerializer = nextResponseSerializer() else { - // Execute all response serializer completions and clear them - var completions: [() -> Void] = [] - - $mutableState.write { mutableState in - completions = mutableState.responseSerializerCompletions - - // Clear out all response serializers and response serializer completions in mutable state since the - // request is complete. It's important to do this prior to calling the completion closures in case - // the completions call back into the request triggering a re-processing of the response serializers. - // An example of how this can happen is by calling cancel inside a response completion closure. - mutableState.responseSerializers.removeAll() - mutableState.responseSerializerCompletions.removeAll() - - if mutableState.state.canTransitionTo(.finished) { - mutableState.state = .finished - } - - mutableState.responseSerializerProcessingFinished = true - mutableState.isFinishing = false - } - - completions.forEach { $0() } - - // Cleanup the request - cleanup() - - return - } - - serializationQueue.async { responseSerializer() } - } - - /// Notifies the `Request` that the response serializer is complete. - /// - /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers - /// are complete. - func responseSerializerDidComplete(completion: @escaping () -> Void) { - $mutableState.write { $0.responseSerializerCompletions.append(completion) } - processNextResponseSerializer() - } - - /// Resets all task and response serializer related state for retry. - func reset() { - error = nil - - uploadProgress.totalUnitCount = 0 - uploadProgress.completedUnitCount = 0 - downloadProgress.totalUnitCount = 0 - downloadProgress.completedUnitCount = 0 - - $mutableState.write { state in - state.isFinishing = false - state.responseSerializerCompletions = [] - } - } - - /// Called when updating the upload progress. - /// - /// - Parameters: - /// - totalBytesSent: Total bytes sent so far. - /// - totalBytesExpectedToSend: Total bytes expected to send. - func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { - uploadProgress.totalUnitCount = totalBytesExpectedToSend - uploadProgress.completedUnitCount = totalBytesSent - - uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } - } - - /// Perform a closure on the current `state` while locked. - /// - /// - Parameter perform: The closure to perform. - func withState(perform: (State) -> Void) { - $mutableState.withState(perform: perform) - } - - // MARK: Task Creation - - /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override. - /// - /// - Parameters: - /// - request: `URLRequest` to use to create the `URLSessionTask`. - /// - session: `URLSession` which creates the `URLSessionTask`. - /// - /// - Returns: The `URLSessionTask` created. - func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { - fatalError("Subclasses must override.") - } - - // MARK: - Public API - - // These APIs are callable from any queue. - - // MARK: State - - /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. - /// - /// - Returns: The instance. - @discardableResult - public func cancel() -> Self { - $mutableState.write { mutableState in - guard mutableState.state.canTransitionTo(.cancelled) else { return } - - mutableState.state = .cancelled - - underlyingQueue.async { self.didCancel() } - - guard let task = mutableState.tasks.last, task.state != .completed else { - underlyingQueue.async { self.finish() } - return - } - - // Resume to ensure metrics are gathered. - task.resume() - task.cancel() - underlyingQueue.async { self.didCancelTask(task) } - } - - return self - } - - /// Suspends the instance. - /// - /// - Returns: The instance. - @discardableResult - public func suspend() -> Self { - $mutableState.write { mutableState in - guard mutableState.state.canTransitionTo(.suspended) else { return } - - mutableState.state = .suspended - - underlyingQueue.async { self.didSuspend() } - - guard let task = mutableState.tasks.last, task.state != .completed else { return } - - task.suspend() - underlyingQueue.async { self.didSuspendTask(task) } - } - - return self - } - - /// Resumes the instance. - /// - /// - Returns: The instance. - @discardableResult - public func resume() -> Self { - $mutableState.write { mutableState in - guard mutableState.state.canTransitionTo(.resumed) else { return } - - mutableState.state = .resumed - - underlyingQueue.async { self.didResume() } - - guard let task = mutableState.tasks.last, task.state != .completed else { return } - - task.resume() - underlyingQueue.async { self.didResumeTask(task) } - } - - return self - } - - // MARK: - Closure API - - /// Associates a credential using the provided values with the instance. - /// - /// - Parameters: - /// - username: The username. - /// - password: The password. - /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default. - /// - /// - Returns: The instance. - @discardableResult - public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { - let credential = URLCredential(user: username, password: password, persistence: persistence) - - return authenticate(with: credential) - } - - /// Associates the provided credential with the instance. - /// - /// - Parameter credential: The `URLCredential`. - /// - /// - Returns: The instance. - @discardableResult - public func authenticate(with credential: URLCredential) -> Self { - $mutableState.credential = credential - - return self - } - - /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server. - /// - /// - Note: Only the last closure provided is used. - /// - /// - Parameters: - /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. - /// - closure: The closure to be executed periodically as data is read from the server. - /// - /// - Returns: The instance. - @discardableResult - public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { - $mutableState.downloadProgressHandler = (handler: closure, queue: queue) - - return self - } - - /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server. - /// - /// - Note: Only the last closure provided is used. - /// - /// - Parameters: - /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. - /// - closure: The closure to be executed periodically as data is sent to the server. - /// - /// - Returns: The instance. - @discardableResult - public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { - $mutableState.uploadProgressHandler = (handler: closure, queue: queue) - - return self - } - - // MARK: Redirects - - /// Sets the redirect handler for the instance which will be used if a redirect response is encountered. - /// - /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash. - /// - /// - Parameter handler: The `RedirectHandler`. - /// - /// - Returns: The instance. - @discardableResult - public func redirect(using handler: RedirectHandler) -> Self { - $mutableState.write { mutableState in - precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") - mutableState.redirectHandler = handler - } - - return self - } - - // MARK: Cached Responses - - /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response. - /// - /// - Note: Attempting to set the cache handler more than once is a logic error and will crash. - /// - /// - Parameter handler: The `CachedResponseHandler`. - /// - /// - Returns: The instance. - @discardableResult - public func cacheResponse(using handler: CachedResponseHandler) -> Self { - $mutableState.write { mutableState in - precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") - mutableState.cachedResponseHandler = handler - } - - return self - } - - // MARK: - Lifetime APIs - - /// Sets a handler to be called when the cURL description of the request is available. - /// - /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which `handler` will be called. - /// - handler: Closure to be called when the cURL description is available. - /// - /// - Returns: The instance. - @discardableResult - public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self { - $mutableState.write { mutableState in - if mutableState.requests.last != nil { - queue.async { handler(self.cURLDescription()) } - } else { - mutableState.cURLHandler = (queue, handler) - } - } - - return self - } - - /// Sets a handler to be called when the cURL description of the request is available. - /// - /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. - /// - /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's - /// `underlyingQueue` by default. - /// - /// - Returns: The instance. - @discardableResult - public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { - cURLDescription(on: underlyingQueue, calling: handler) - - return self - } - - /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance. - /// - /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. - /// - handler: Closure to be called when a `URLRequest` is available. - /// - /// - Returns: The instance. - @discardableResult - public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self { - $mutableState.write { state in - if let request = state.requests.last { - queue.async { handler(request) } - } - - state.urlRequestHandler = (queue, handler) - } - - return self - } - - /// Sets a closure to be called whenever the instance creates a `URLSessionTask`. - /// - /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It - /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features. - /// Additionally, this closure may be called multiple times if the instance is retried. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. - /// - handler: Closure to be called when the `URLSessionTask` is available. - /// - /// - Returns: The instance. - @discardableResult - public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self { - $mutableState.write { state in - if let task = state.tasks.last { - queue.async { handler(task) } - } - - state.urlSessionTaskHandler = (queue, handler) - } - - return self - } - - // MARK: Cleanup - - /// Adds a `finishHandler` closure to be called when the request completes. - /// - /// - Parameter closure: Closure to be called when the request finishes. - func onFinish(perform finishHandler: @escaping () -> Void) { - guard !isFinished else { finishHandler(); return } - - $mutableState.write { state in - state.finishHandlers.append(finishHandler) - } - } - - /// Final cleanup step executed when the instance finishes response serialization. - func cleanup() { - let handlers = $mutableState.finishHandlers - handlers.forEach { $0() } - $mutableState.write { state in - state.finishHandlers.removeAll() - } - - delegate?.cleanup(after: self) - } -} - -extension Request { - /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`. - public enum ResponseDisposition { - /// Allow the request to continue normally. - case allow - /// Cancel the request, similar to calling `cancel()`. - case cancel - - var sessionDisposition: URLSession.ResponseDisposition { - switch self { - case .allow: return .allow - case .cancel: return .cancel - } - } - } -} - -// MARK: - Protocol Conformances - -extension Request: Equatable { - public static func ==(lhs: Request, rhs: Request) -> Bool { - lhs.id == rhs.id - } -} - -extension Request: Hashable { - public func hash(into hasher: inout Hasher) { - hasher.combine(id) - } -} - -extension Request: CustomStringConvertible { - /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been - /// created, as well as the response status code, if a response has been received. - public var description: String { - guard let request = performedRequests.last ?? lastRequest, - let url = request.url, - let method = request.httpMethod else { return "No request created yet." } - - let requestDescription = "\(method) \(url.absoluteString)" - - return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription - } -} - -extension Request { - /// cURL representation of the instance. - /// - /// - Returns: The cURL equivalent of the instance. - public func cURLDescription() -> String { - guard - let request = lastRequest, - let url = request.url, - let host = url.host, - let method = request.httpMethod else { return "$ curl command could not be created" } - - var components = ["$ curl -v"] - - components.append("-X \(method)") - - if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage { - let protectionSpace = URLProtectionSpace(host: host, - port: url.port ?? 0, - protocol: url.scheme, - realm: host, - authenticationMethod: NSURLAuthenticationMethodHTTPBasic) - - if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { - for credential in credentials { - guard let user = credential.user, let password = credential.password else { continue } - components.append("-u \(user):\(password)") - } - } else { - if let credential = credential, let user = credential.user, let password = credential.password { - components.append("-u \(user):\(password)") - } - } - } - - if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { - if - let cookieStorage = configuration.httpCookieStorage, - let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { - let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";") - - components.append("-b \"\(allCookies)\"") - } - } - - var headers = HTTPHeaders() - - if let sessionHeaders = delegate?.sessionConfiguration.headers { - for header in sessionHeaders where header.name != "Cookie" { - headers[header.name] = header.value - } - } - - for header in request.headers where header.name != "Cookie" { - headers[header.name] = header.value - } - - for header in headers { - let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"") - components.append("-H \"\(header.name): \(escapedValue)\"") - } - - if let httpBodyData = request.httpBody { - let httpBody = String(decoding: httpBodyData, as: UTF8.self) - var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") - escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") - - components.append("-d \"\(escapedBody)\"") - } - - components.append("\"\(url.absoluteString)\"") - - return components.joined(separator: " \\\n\t") - } -} - -/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`. -public protocol RequestDelegate: AnyObject { - /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s. - var sessionConfiguration: URLSessionConfiguration { get } - - /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler. - var startImmediately: Bool { get } - - /// Notifies the delegate the `Request` has reached a point where it needs cleanup. - /// - /// - Parameter request: The `Request` to cleanup after. - func cleanup(after request: Request) - - /// Asynchronously ask the delegate whether a `Request` will be retried. - /// - /// - Parameters: - /// - request: `Request` which failed. - /// - error: `Error` which produced the failure. - /// - completion: Closure taking the `RetryResult` for evaluation. - func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) - - /// Asynchronously retry the `Request`. - /// - /// - Parameters: - /// - request: `Request` which will be retried. - /// - timeDelay: `TimeInterval` after which the retry will be triggered. - func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) -} - -// MARK: - Subclasses - -// MARK: - DataRequest - -/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`. -public class DataRequest: Request { - /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. - public let convertible: URLRequestConvertible - /// `Data` read from the server so far. - public var data: Data? { $dataMutableState.data } - - private struct DataMutableState { - var data: Data? - var httpResponseHandler: (queue: DispatchQueue, - handler: (_ response: HTTPURLResponse, - _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)? - } - - @Protected - private var dataMutableState = DataMutableState() - - /// Creates a `DataRequest` using the provided parameters. - /// - /// - Parameters: - /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. - /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance. - /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. - /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets - /// `underlyingQueue`, but can be passed another queue from a `Session`. - /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. - /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. - /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. - init(id: UUID = UUID(), - convertible: URLRequestConvertible, - underlyingQueue: DispatchQueue, - serializationQueue: DispatchQueue, - eventMonitor: EventMonitor?, - interceptor: RequestInterceptor?, - delegate: RequestDelegate) { - self.convertible = convertible - - super.init(id: id, - underlyingQueue: underlyingQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: delegate) - } - - override func reset() { - super.reset() - - $dataMutableState.write { mutableState in - mutableState.data = nil - } - } - - /// Called when `Data` is received by this instance. - /// - /// - Note: Also calls `updateDownloadProgress`. - /// - /// - Parameter data: The `Data` received. - func didReceive(data: Data) { - $dataMutableState.write { mutableState in - if mutableState.data == nil { - mutableState.data = data - } else { - mutableState.data?.append(data) - } - } - - updateDownloadProgress() - } - - func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { - $dataMutableState.read { dataMutableState in - guard let httpResponseHandler = dataMutableState.httpResponseHandler else { - underlyingQueue.async { completionHandler(.allow) } - return - } - - httpResponseHandler.queue.async { - httpResponseHandler.handler(response) { disposition in - if disposition == .cancel { - self.$mutableState.write { mutableState in - mutableState.state = .cancelled - mutableState.error = mutableState.error ?? AFError.explicitlyCancelled - } - } - - self.underlyingQueue.async { - completionHandler(disposition.sessionDisposition) - } - } - } - } - } - - override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { - let copiedRequest = request - return session.dataTask(with: copiedRequest) - } - - /// Called to update the `downloadProgress` of the instance. - func updateDownloadProgress() { - let totalBytesReceived = Int64(data?.count ?? 0) - let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown - - downloadProgress.totalUnitCount = totalBytesExpected - downloadProgress.completedUnitCount = totalBytesReceived - - downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } - } - - /// Validates the request, using the specified closure. - /// - /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - Parameter validation: `Validation` closure used to validate the response. - /// - /// - Returns: The instance. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validator: () -> Void = { [unowned self] in - guard error == nil, let response = response else { return } - - let result = validation(request, response, data) - - if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } - - eventMonitor?.request(self, - didValidateRequest: request, - response: response, - data: data, - withResult: result) - } - - $validators.write { $0.append(validator) } - - return self - } - - /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion - /// handler to return a `ResponseDisposition` value. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. - /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided - /// MUST be called, otherwise the request will never complete. - /// - /// - Returns: The instance. - @_disfavoredOverload - @discardableResult - public func onHTTPResponse( - on queue: DispatchQueue = .main, - perform handler: @escaping (_ response: HTTPURLResponse, - _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void - ) -> Self { - $dataMutableState.write { mutableState in - mutableState.httpResponseHandler = (queue, handler) - } - - return self - } - - /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. - /// - handler: Closure called when the instance produces an `HTTPURLResponse`. - /// - /// - Returns: The instance. - @discardableResult - public func onHTTPResponse(on queue: DispatchQueue = .main, - perform handler: @escaping (HTTPURLResponse) -> Void) -> Self { - onHTTPResponse(on: queue) { response, completionHandler in - handler(response) - completionHandler(.allow) - } - - return self - } -} - -// MARK: - DataStreamRequest - -/// `Request` subclass which streams HTTP response `Data` through a `Handler` closure. -public final class DataStreamRequest: Request { - /// Closure type handling `DataStreamRequest.Stream` values. - public typealias Handler = (Stream) throws -> Void - - /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used - /// to stop the stream at any time. - public struct Stream { - /// Latest `Event` from the stream. - public let event: Event - /// Token used to cancel the stream. - public let token: CancellationToken - - /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. - public func cancel() { - token.cancel() - } - } - - /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed - /// `Data` or the completion of the stream. - public enum Event { - /// Output produced every time the instance receives additional `Data`. The associated value contains the - /// `Result` of processing the incoming `Data`. - case stream(Result) - /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error. - /// Associated `Completion` value contains the final state. - case complete(Completion) - } - - /// Value containing the state of a `DataStreamRequest` when the stream was completed. - public struct Completion { - /// Last `URLRequest` issued by the instance. - public let request: URLRequest? - /// Last `HTTPURLResponse` received by the instance. - public let response: HTTPURLResponse? - /// Last `URLSessionTaskMetrics` produced for the instance. - public let metrics: URLSessionTaskMetrics? - /// `AFError` produced for the instance, if any. - public let error: AFError? - } - - /// Type used to cancel an ongoing stream. - public struct CancellationToken { - weak var request: DataStreamRequest? - - init(_ request: DataStreamRequest) { - self.request = request - } - - /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. - public func cancel() { - request?.cancel() - } - } - - /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. - public let convertible: URLRequestConvertible - /// Whether or not the instance will be cancelled if stream parsing encounters an error. - public let automaticallyCancelOnStreamError: Bool - - /// Internal mutable state specific to this type. - struct StreamMutableState { - /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called. - var outputStream: OutputStream? - /// Stream closures called as `Data` is received. - var streams: [(_ data: Data) -> Void] = [] - /// Number of currently executing streams. Used to ensure completions are only fired after all streams are - /// enqueued. - var numberOfExecutingStreams = 0 - /// Completion calls enqueued while streams are still executing. - var enqueuedCompletionEvents: [() -> Void] = [] - /// Handler for any `HTTPURLResponse`s received. - var httpResponseHandler: (queue: DispatchQueue, - handler: (_ response: HTTPURLResponse, - _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)? - } - - @Protected - var streamMutableState = StreamMutableState() - - /// Creates a `DataStreamRequest` using the provided parameters. - /// - /// - Parameters: - /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` - /// by default. - /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this - /// instance. - /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error` - /// is thrown while serializing stream `Data`. - /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. - /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default - /// targets - /// `underlyingQueue`, but can be passed another queue from a `Session`. - /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. - /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. - /// - delegate: `RequestDelegate` that provides an interface to actions not performed by - /// the `Request`. - init(id: UUID = UUID(), - convertible: URLRequestConvertible, - automaticallyCancelOnStreamError: Bool, - underlyingQueue: DispatchQueue, - serializationQueue: DispatchQueue, - eventMonitor: EventMonitor?, - interceptor: RequestInterceptor?, - delegate: RequestDelegate) { - self.convertible = convertible - self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError - - super.init(id: id, - underlyingQueue: underlyingQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: delegate) - } - - override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { - let copiedRequest = request - return session.dataTask(with: copiedRequest) - } - - override func finish(error: AFError? = nil) { - $streamMutableState.write { state in - state.outputStream?.close() - } - - super.finish(error: error) - } - - func didReceive(data: Data) { - $streamMutableState.write { state in - #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. - if let stream = state.outputStream { - underlyingQueue.async { - var bytes = Array(data) - stream.write(&bytes, maxLength: bytes.count) - } - } - #endif - state.numberOfExecutingStreams += state.streams.count - let localState = state - underlyingQueue.async { localState.streams.forEach { $0(data) } } - } - } - - func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { - $streamMutableState.read { dataMutableState in - guard let httpResponseHandler = dataMutableState.httpResponseHandler else { - underlyingQueue.async { completionHandler(.allow) } - return - } - - httpResponseHandler.queue.async { - httpResponseHandler.handler(response) { disposition in - if disposition == .cancel { - self.$mutableState.write { mutableState in - mutableState.state = .cancelled - mutableState.error = mutableState.error ?? AFError.explicitlyCancelled - } - } - - self.underlyingQueue.async { - completionHandler(disposition.sessionDisposition) - } - } - } - } - } - - /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure. - /// - /// - Parameter validation: `Validation` closure used to validate the request and response. - /// - /// - Returns: The `DataStreamRequest`. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validator: () -> Void = { [unowned self] in - guard error == nil, let response = response else { return } - - let result = validation(request, response) - - if case let .failure(error) = result { - self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) - } - - eventMonitor?.request(self, - didValidateRequest: request, - response: response, - withResult: result) - } - - $validators.write { $0.append(validator) } - - return self - } - - #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. - /// Produces an `InputStream` that receives the `Data` received by the instance. - /// - /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`. - /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or - /// not the creating session has `startRequestsImmediately` set to `true`. - /// - /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`. - /// - /// - Returns: The `InputStream` bound to the internal `OutboundStream`. - public func asInputStream(bufferSize: Int = 1024) -> InputStream? { - defer { resume() } - - var inputStream: InputStream? - $streamMutableState.write { state in - Foundation.Stream.getBoundStreams(withBufferSize: bufferSize, - inputStream: &inputStream, - outputStream: &state.outputStream) - state.outputStream?.open() - } - - return inputStream - } - #endif - - /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion - /// handler to return a `ResponseDisposition` value. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. - /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided - /// MUST be called, otherwise the request will never complete. - /// - /// - Returns: The instance. - @_disfavoredOverload - @discardableResult - public func onHTTPResponse( - on queue: DispatchQueue = .main, - perform handler: @escaping (_ response: HTTPURLResponse, - _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void - ) -> Self { - $streamMutableState.write { mutableState in - mutableState.httpResponseHandler = (queue, handler) - } - - return self - } - - /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. - /// - handler: Closure called when the instance produces an `HTTPURLResponse`. - /// - /// - Returns: The instance. - @discardableResult - public func onHTTPResponse(on queue: DispatchQueue = .main, - perform handler: @escaping (HTTPURLResponse) -> Void) -> Self { - onHTTPResponse(on: queue) { response, completionHandler in - handler(response) - completionHandler(.allow) - } - - return self - } - - func capturingError(from closure: () throws -> Void) { - do { - try closure() - } catch { - self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) - cancel() - } - } - - func appendStreamCompletion(on queue: DispatchQueue, - stream: @escaping Handler) { - appendResponseSerializer { - self.underlyingQueue.async { - self.responseSerializerDidComplete { - self.$streamMutableState.write { state in - guard state.numberOfExecutingStreams == 0 else { - state.enqueuedCompletionEvents.append { - self.enqueueCompletion(on: queue, stream: stream) - } - - return - } - - self.enqueueCompletion(on: queue, stream: stream) - } - } - } - } - } - - func enqueueCompletion(on queue: DispatchQueue, - stream: @escaping Handler) { - queue.async { - do { - let completion = Completion(request: self.request, - response: self.response, - metrics: self.metrics, - error: self.error) - try stream(.init(event: .complete(completion), token: .init(self))) - } catch { - // Ignore error, as errors on Completion can't be handled anyway. - } - } - } -} - -extension DataStreamRequest.Stream { - /// Incoming `Result` values from `Event.stream`. - public var result: Result? { - guard case let .stream(result) = event else { return nil } - - return result - } - - /// `Success` value of the instance, if any. - public var value: Success? { - guard case let .success(value) = result else { return nil } - - return value - } - - /// `Failure` value of the instance, if any. - public var error: Failure? { - guard case let .failure(error) = result else { return nil } - - return error - } - - /// `Completion` value of the instance, if any. - public var completion: DataStreamRequest.Completion? { - guard case let .complete(completion) = event else { return nil } - - return completion - } -} - -// MARK: - DownloadRequest - -/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`. -public class DownloadRequest: Request { - /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination - /// `URL`. - public struct Options: OptionSet { - /// Specifies that intermediate directories for the destination URL should be created. - public static let createIntermediateDirectories = Options(rawValue: 1 << 0) - /// Specifies that any previous file at the destination `URL` should be removed. - public static let removePreviousFile = Options(rawValue: 1 << 1) - - public let rawValue: Int - - public init(rawValue: Int) { - self.rawValue = rawValue - } - } - - // MARK: Destination - - /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the - /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL - /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and - /// the options defining how the file should be moved. - /// - /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not - /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory. - public typealias Destination = (_ temporaryURL: URL, - _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) - - /// Creates a download file destination closure which uses the default file manager to move the temporary file to a - /// file URL in the first available directory with the specified search path directory and search path domain mask. - /// - /// - Parameters: - /// - directory: The search path directory. `.documentDirectory` by default. - /// - domain: The search path domain mask. `.userDomainMask` by default. - /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by - /// default. - /// - Returns: The `Destination` closure. - public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory, - in domain: FileManager.SearchPathDomainMask = .userDomainMask, - options: Options = []) -> Destination { - { temporaryURL, response in - let directoryURLs = FileManager.default.urls(for: directory, in: domain) - let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL - - return (url, options) - } - } - - /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends - /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files - /// with this destination must be additionally moved if they should survive the system reclamation of temporary - /// space. - static let defaultDestination: Destination = { url, _ in - (defaultDestinationURL(url), []) - } - - /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the - /// provided file name. - static let defaultDestinationURL: (URL) -> URL = { url in - let filename = "Alamofire_\(url.lastPathComponent)" - let destination = url.deletingLastPathComponent().appendingPathComponent(filename) - - return destination - } - - // MARK: Downloadable - - /// Type describing the source used to create the underlying `URLSessionDownloadTask`. - public enum Downloadable { - /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. - case request(URLRequestConvertible) - /// Download should be started from the associated resume `Data` value. - case resumeData(Data) - } - - // MARK: Mutable State - - /// Type containing all mutable state for `DownloadRequest` instances. - private struct DownloadRequestMutableState { - /// Possible resume `Data` produced when cancelling the instance. - var resumeData: Data? - /// `URL` to which `Data` is being downloaded. - var fileURL: URL? - } - - /// Protected mutable state specific to `DownloadRequest`. - @Protected - private var mutableDownloadState = DownloadRequestMutableState() - - /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download - /// using the `download(resumingWith data:)` API. - /// - /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel). - public var resumeData: Data? { - #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. - return $mutableDownloadState.resumeData ?? error?.downloadResumeData - #else - return $mutableDownloadState.resumeData - #endif - } - - /// If the download is successful, the `URL` where the file was downloaded. - public var fileURL: URL? { $mutableDownloadState.fileURL } - - // MARK: Initial State - - /// `Downloadable` value used for this instance. - public let downloadable: Downloadable - /// The `Destination` to which the downloaded file is moved. - let destination: Destination - - /// Creates a `DownloadRequest` using the provided parameters. - /// - /// - Parameters: - /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. - /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance. - /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. - /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets - /// `underlyingQueue`, but can be passed another queue from a `Session`. - /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. - /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. - /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request` - /// - destination: `Destination` closure used to move the downloaded file to its final location. - init(id: UUID = UUID(), - downloadable: Downloadable, - underlyingQueue: DispatchQueue, - serializationQueue: DispatchQueue, - eventMonitor: EventMonitor?, - interceptor: RequestInterceptor?, - delegate: RequestDelegate, - destination: @escaping Destination) { - self.downloadable = downloadable - self.destination = destination - - super.init(id: id, - underlyingQueue: underlyingQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: delegate) - } - - override func reset() { - super.reset() - - $mutableDownloadState.write { - $0.resumeData = nil - $0.fileURL = nil - } - } - - /// Called when a download has finished. - /// - /// - Parameters: - /// - task: `URLSessionTask` that finished the download. - /// - result: `Result` of the automatic move to `destination`. - func didFinishDownloading(using task: URLSessionTask, with result: Result) { - eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) - - switch result { - case let .success(url): $mutableDownloadState.fileURL = url - case let .failure(error): self.error = error - } - } - - /// Updates the `downloadProgress` using the provided values. - /// - /// - Parameters: - /// - bytesWritten: Total bytes written so far. - /// - totalBytesExpectedToWrite: Total bytes expected to write. - func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) { - downloadProgress.totalUnitCount = totalBytesExpectedToWrite - downloadProgress.completedUnitCount += bytesWritten - - downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } - } - - override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { - session.downloadTask(with: request) - } - - /// Creates a `URLSessionTask` from the provided resume data. - /// - /// - Parameters: - /// - data: `Data` used to resume the download. - /// - session: `URLSession` used to create the `URLSessionTask`. - /// - /// - Returns: The `URLSessionTask` created. - public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { - session.downloadTask(withResumeData: data) - } - - /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended. - /// - /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use - /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`. - /// - /// - Returns: The instance. - @discardableResult - override public func cancel() -> Self { - cancel(producingResumeData: false) - } - - /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be - /// resumed or suspended. - /// - /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if - /// available. - /// - /// - Returns: The instance. - @discardableResult - public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self { - cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil) - } - - /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed - /// or suspended. - /// - /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` - /// property. - /// - /// - Parameter completionHandler: The completion handler that is called when the download has been successfully - /// cancelled. It is not guaranteed to be called on a particular queue, so you may - /// want use an appropriate queue to perform your work. - /// - /// - Returns: The instance. - @discardableResult - public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self { - cancel(optionallyProducingResumeData: completionHandler) - } - - /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed, - /// cancellation is performed without producing resume data. - /// - /// - Parameter completionHandler: Optional resume data handler. - /// - /// - Returns: The instance. - private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self { - $mutableState.write { mutableState in - guard mutableState.state.canTransitionTo(.cancelled) else { return } - - mutableState.state = .cancelled - - underlyingQueue.async { self.didCancel() } - - guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { - underlyingQueue.async { self.finish() } - return - } - - if let completionHandler = completionHandler { - // Resume to ensure metrics are gathered. - task.resume() - task.cancel { resumeData in - self.$mutableDownloadState.resumeData = resumeData - self.underlyingQueue.async { self.didCancelTask(task) } - completionHandler(resumeData) - } - } else { - // Resume to ensure metrics are gathered. - task.resume() - task.cancel() - self.underlyingQueue.async { self.didCancelTask(task) } - } - } - - return self - } - - /// Validates the request, using the specified closure. - /// - /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - Parameter validation: `Validation` closure to validate the response. - /// - /// - Returns: The instance. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validator: () -> Void = { [unowned self] in - guard error == nil, let response = response else { return } - - let result = validation(request, response, fileURL) - - if case let .failure(error) = result { - self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) - } - - eventMonitor?.request(self, - didValidateRequest: request, - response: response, - fileURL: fileURL, - withResult: result) - } - - $validators.write { $0.append(validator) } - - return self - } -} - -// MARK: - UploadRequest - -/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`. -public class UploadRequest: DataRequest { - /// Type describing the origin of the upload, whether `Data`, file, or stream. - public enum Uploadable { - /// Upload from the provided `Data` value. - case data(Data) - /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be - /// automatically removed once uploaded. - case file(URL, shouldRemove: Bool) - /// Upload from the provided `InputStream`. - case stream(InputStream) - } - - // MARK: Initial State - - /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. - public let upload: UploadableConvertible - - /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written - /// to disk. - public let fileManager: FileManager - - // MARK: Mutable State - - /// `Uploadable` value used by the instance. - public var uploadable: Uploadable? - - /// Creates an `UploadRequest` using the provided parameters. - /// - /// - Parameters: - /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. - /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed. - /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. - /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets - /// `underlyingQueue`, but can be passed another queue from a `Session`. - /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. - /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. - /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form - /// encoded payloads written to disk. - /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. - init(id: UUID = UUID(), - convertible: UploadConvertible, - underlyingQueue: DispatchQueue, - serializationQueue: DispatchQueue, - eventMonitor: EventMonitor?, - interceptor: RequestInterceptor?, - fileManager: FileManager, - delegate: RequestDelegate) { - upload = convertible - self.fileManager = fileManager - - super.init(id: id, - convertible: convertible, - underlyingQueue: underlyingQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: delegate) - } - - /// Called when the `Uploadable` value has been created from the `UploadConvertible`. - /// - /// - Parameter uploadable: The `Uploadable` that was created. - func didCreateUploadable(_ uploadable: Uploadable) { - self.uploadable = uploadable - - eventMonitor?.request(self, didCreateUploadable: uploadable) - } - - /// Called when the `Uploadable` value could not be created. - /// - /// - Parameter error: `AFError` produced by the failure. - func didFailToCreateUploadable(with error: AFError) { - self.error = error - - eventMonitor?.request(self, didFailToCreateUploadableWithError: error) - - retryOrFinish(error: error) - } - - override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { - guard let uploadable = uploadable else { - fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.") - } - - switch uploadable { - case let .data(data): return session.uploadTask(with: request, from: data) - case let .file(url, _): return session.uploadTask(with: request, fromFile: url) - case .stream: return session.uploadTask(withStreamedRequest: request) - } - } - - override func reset() { - // Uploadable must be recreated on every retry. - uploadable = nil - - super.reset() - } - - /// Produces the `InputStream` from `uploadable`, if it can. - /// - /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash. - /// - /// - Returns: The `InputStream`. - func inputStream() -> InputStream { - guard let uploadable = uploadable else { - fatalError("Attempting to access the input stream but the uploadable doesn't exist.") - } - - guard case let .stream(stream) = uploadable else { - fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") - } - - eventMonitor?.request(self, didProvideInputStream: stream) - - return stream - } - - override public func cleanup() { - defer { super.cleanup() } - - guard - let uploadable = uploadable, - case let .file(url, shouldRemove) = uploadable, - shouldRemove - else { return } - - try? fileManager.removeItem(at: url) - } -} - -/// A type that can produce an `UploadRequest.Uploadable` value. -public protocol UploadableConvertible { - /// Produces an `UploadRequest.Uploadable` value from the instance. - /// - /// - Returns: The `UploadRequest.Uploadable`. - /// - Throws: Any `Error` produced during creation. - func createUploadable() throws -> UploadRequest.Uploadable -} - -extension UploadRequest.Uploadable: UploadableConvertible { - public func createUploadable() throws -> UploadRequest.Uploadable { - self - } -} - -/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. -public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {} diff --git a/Pods/Alamofire/Source/RequestCompression.swift b/Pods/Alamofire/Source/RequestCompression.swift deleted file mode 100644 index c543e06..0000000 --- a/Pods/Alamofire/Source/RequestCompression.swift +++ /dev/null @@ -1,153 +0,0 @@ -// -// RequestCompression.swift -// -// Copyright (c) 2023 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#if canImport(zlib) -import Foundation -import zlib - -/// `RequestAdapter` which compresses outgoing `URLRequest` bodies using the `deflate` `Content-Encoding` and adds the -/// appropriate header. -/// -/// - Note: Most requests to most APIs are small and so would only be slowed down by applying this adapter. Measure the -/// size of your request bodies and the performance impact of using this adapter before use. Using this adapter -/// with already compressed data, such as images, will, at best, have no effect. Additionally, body compression -/// is a synchronous operation, so measuring the performance impact may be important to determine whether you -/// want to use a dedicated `requestQueue` in your `Session` instance. Finally, not all servers support request -/// compression, so test with all of your server configurations before deploying. -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -public struct DeflateRequestCompressor: RequestInterceptor { - /// Type that determines the action taken when the `URLRequest` already has a `Content-Encoding` header. - public enum DuplicateHeaderBehavior { - /// Throws a `DuplicateHeaderError`. The default. - case error - /// Replaces the existing header value with `deflate`. - case replace - /// Silently skips compression when the header exists. - case skip - } - - /// `Error` produced when the outgoing `URLRequest` already has a `Content-Encoding` header, when the instance has - /// been configured to produce an error. - public struct DuplicateHeaderError: Error {} - - /// Behavior to use when the outgoing `URLRequest` already has a `Content-Encoding` header. - public let duplicateHeaderBehavior: DuplicateHeaderBehavior - /// Closure which determines whether the outgoing body data should be compressed. - public let shouldCompressBodyData: (_ bodyData: Data) -> Bool - - /// Creates an instance with the provided parameters. - /// - /// - Parameters: - /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. `.error` by default. - /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. - public init(duplicateHeaderBehavior: DuplicateHeaderBehavior = .error, - shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true }) { - self.duplicateHeaderBehavior = duplicateHeaderBehavior - self.shouldCompressBodyData = shouldCompressBodyData - } - - public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - // No need to compress unless we have body data. No support for compressing streams. - guard let bodyData = urlRequest.httpBody else { - completion(.success(urlRequest)) - return - } - - guard shouldCompressBodyData(bodyData) else { - completion(.success(urlRequest)) - return - } - - if urlRequest.headers.value(for: "Content-Encoding") != nil { - switch duplicateHeaderBehavior { - case .error: - completion(.failure(DuplicateHeaderError())) - return - case .replace: - // Header will be replaced once the body data is compressed. - break - case .skip: - completion(.success(urlRequest)) - return - } - } - - var compressedRequest = urlRequest - - do { - compressedRequest.httpBody = try deflate(bodyData) - compressedRequest.headers.update(.contentEncoding("deflate")) - completion(.success(compressedRequest)) - } catch { - completion(.failure(error)) - } - } - - func deflate(_ data: Data) throws -> Data { - var output = Data([0x78, 0x5E]) // Header - try output.append((data as NSData).compressed(using: .zlib) as Data) - var checksum = adler32Checksum(of: data).bigEndian - output.append(Data(bytes: &checksum, count: MemoryLayout.size)) - - return output - } - - func adler32Checksum(of data: Data) -> UInt32 { - #if swift(>=5.6) - data.withUnsafeBytes { buffer in - UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count))) - } - #else - data.withUnsafeBytes { buffer in - let buffer = buffer.bindMemory(to: UInt8.self) - return UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count))) - } - #endif - } -} - -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -extension RequestInterceptor where Self == DeflateRequestCompressor { - /// Create a `DeflateRequestCompressor` with default `duplicateHeaderBehavior` and `shouldCompressBodyData` values. - public static var deflateCompressor: DeflateRequestCompressor { - DeflateRequestCompressor() - } - - /// Creates a `DeflateRequestCompressor` with the provided `DuplicateHeaderBehavior` and `shouldCompressBodyData` - /// closure. - /// - /// - Parameters: - /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. - /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. - /// - /// - Returns: The `DeflateRequestCompressor`. - public static func deflateCompressor( - duplicateHeaderBehavior: DeflateRequestCompressor.DuplicateHeaderBehavior = .error, - shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true } - ) -> DeflateRequestCompressor { - DeflateRequestCompressor(duplicateHeaderBehavior: duplicateHeaderBehavior, - shouldCompressBodyData: shouldCompressBodyData) - } -} -#endif diff --git a/Pods/Alamofire/Source/RequestInterceptor.swift b/Pods/Alamofire/Source/RequestInterceptor.swift deleted file mode 100644 index 9acd986..0000000 --- a/Pods/Alamofire/Source/RequestInterceptor.swift +++ /dev/null @@ -1,351 +0,0 @@ -// -// RequestInterceptor.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Stores all state associated with a `URLRequest` being adapted. -public struct RequestAdapterState { - /// The `UUID` of the `Request` associated with the `URLRequest` to adapt. - public let requestID: UUID - - /// The `Session` associated with the `URLRequest` to adapt. - public let session: Session -} - -// MARK: - - -/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. -public protocol RequestAdapter { - /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. - /// - /// - Parameters: - /// - urlRequest: The `URLRequest` to adapt. - /// - session: The `Session` that will execute the `URLRequest`. - /// - completion: The completion handler that must be called when adaptation is complete. - func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) - - /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. - /// - /// - Parameters: - /// - urlRequest: The `URLRequest` to adapt. - /// - state: The `RequestAdapterState` associated with the `URLRequest`. - /// - completion: The completion handler that must be called when adaptation is complete. - func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) -} - -extension RequestAdapter { - public func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { - adapt(urlRequest, for: state.session, completion: completion) - } -} - -// MARK: - - -/// Outcome of determination whether retry is necessary. -public enum RetryResult { - /// Retry should be attempted immediately. - case retry - /// Retry should be attempted after the associated `TimeInterval`. - case retryWithDelay(TimeInterval) - /// Do not retry. - case doNotRetry - /// Do not retry due to the associated `Error`. - case doNotRetryWithError(Error) -} - -extension RetryResult { - var retryRequired: Bool { - switch self { - case .retry, .retryWithDelay: return true - default: return false - } - } - - var delay: TimeInterval? { - switch self { - case let .retryWithDelay(delay): return delay - default: return nil - } - } - - var error: Error? { - guard case let .doNotRetryWithError(error) = self else { return nil } - return error - } -} - -/// A type that determines whether a request should be retried after being executed by the specified session manager -/// and encountering an error. -public protocol RequestRetrier { - /// Determines whether the `Request` should be retried by calling the `completion` closure. - /// - /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs - /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly - /// cleaned up after. - /// - /// - Parameters: - /// - request: `Request` that failed due to the provided `Error`. - /// - session: `Session` that produced the `Request`. - /// - error: `Error` encountered while executing the `Request`. - /// - completion: Completion closure to be executed when a retry decision has been determined. - func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) -} - -// MARK: - - -/// Type that provides both `RequestAdapter` and `RequestRetrier` functionality. -public protocol RequestInterceptor: RequestAdapter, RequestRetrier {} - -extension RequestInterceptor { - public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - completion(.success(urlRequest)) - } - - public func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - completion(.doNotRetry) - } -} - -/// `RequestAdapter` closure definition. -public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result) -> Void) -> Void -/// `RequestRetrier` closure definition. -public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void - -// MARK: - - -/// Closure-based `RequestAdapter`. -open class Adapter: RequestInterceptor { - private let adaptHandler: AdaptHandler - - /// Creates an instance using the provided closure. - /// - /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation. - public init(_ adaptHandler: @escaping AdaptHandler) { - self.adaptHandler = adaptHandler - } - - open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - adaptHandler(urlRequest, session, completion) - } - - open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { - adaptHandler(urlRequest, state.session, completion) - } -} - -extension RequestAdapter where Self == Adapter { - /// Creates an `Adapter` using the provided `AdaptHandler` closure. - /// - /// - Parameter closure: `AdaptHandler` to use to adapt the request. - /// - Returns: The `Adapter`. - public static func adapter(using closure: @escaping AdaptHandler) -> Adapter { - Adapter(closure) - } -} - -// MARK: - - -/// Closure-based `RequestRetrier`. -open class Retrier: RequestInterceptor { - private let retryHandler: RetryHandler - - /// Creates an instance using the provided closure. - /// - /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry. - public init(_ retryHandler: @escaping RetryHandler) { - self.retryHandler = retryHandler - } - - open func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - retryHandler(request, session, error, completion) - } -} - -extension RequestRetrier where Self == Retrier { - /// Creates a `Retrier` using the provided `RetryHandler` closure. - /// - /// - Parameter closure: `RetryHandler` to use to retry the request. - /// - Returns: The `Retrier`. - public static func retrier(using closure: @escaping RetryHandler) -> Retrier { - Retrier(closure) - } -} - -// MARK: - - -/// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values. -open class Interceptor: RequestInterceptor { - /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails. - public let adapters: [RequestAdapter] - /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry. - public let retriers: [RequestRetrier] - - /// Creates an instance from `AdaptHandler` and `RetryHandler` closures. - /// - /// - Parameters: - /// - adaptHandler: `AdaptHandler` closure to be used. - /// - retryHandler: `RetryHandler` closure to be used. - public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) { - adapters = [Adapter(adaptHandler)] - retriers = [Retrier(retryHandler)] - } - - /// Creates an instance from `RequestAdapter` and `RequestRetrier` values. - /// - /// - Parameters: - /// - adapter: `RequestAdapter` value to be used. - /// - retrier: `RequestRetrier` value to be used. - public init(adapter: RequestAdapter, retrier: RequestRetrier) { - adapters = [adapter] - retriers = [retrier] - } - - /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values. - /// - /// - Parameters: - /// - adapters: `RequestAdapter` values to be used. - /// - retriers: `RequestRetrier` values to be used. - /// - interceptors: `RequestInterceptor`s to be used. - public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = [], interceptors: [RequestInterceptor] = []) { - self.adapters = adapters + interceptors - self.retriers = retriers + interceptors - } - - open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { - adapt(urlRequest, for: session, using: adapters, completion: completion) - } - - private func adapt(_ urlRequest: URLRequest, - for session: Session, - using adapters: [RequestAdapter], - completion: @escaping (Result) -> Void) { - var pendingAdapters = adapters - - guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } - - let adapter = pendingAdapters.removeFirst() - - adapter.adapt(urlRequest, for: session) { result in - switch result { - case let .success(urlRequest): - self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion) - case .failure: - completion(result) - } - } - } - - open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { - adapt(urlRequest, using: state, adapters: adapters, completion: completion) - } - - private func adapt(_ urlRequest: URLRequest, - using state: RequestAdapterState, - adapters: [RequestAdapter], - completion: @escaping (Result) -> Void) { - var pendingAdapters = adapters - - guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } - - let adapter = pendingAdapters.removeFirst() - - adapter.adapt(urlRequest, using: state) { result in - switch result { - case let .success(urlRequest): - self.adapt(urlRequest, using: state, adapters: pendingAdapters, completion: completion) - case .failure: - completion(result) - } - } - } - - open func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - retry(request, for: session, dueTo: error, using: retriers, completion: completion) - } - - private func retry(_ request: Request, - for session: Session, - dueTo error: Error, - using retriers: [RequestRetrier], - completion: @escaping (RetryResult) -> Void) { - var pendingRetriers = retriers - - guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return } - - let retrier = pendingRetriers.removeFirst() - - retrier.retry(request, for: session, dueTo: error) { result in - switch result { - case .retry, .retryWithDelay, .doNotRetryWithError: - completion(result) - case .doNotRetry: - // Only continue to the next retrier if retry was not triggered and no error was encountered - self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion) - } - } - } -} - -extension RequestInterceptor where Self == Interceptor { - /// Creates an `Interceptor` using the provided `AdaptHandler` and `RetryHandler` closures. - /// - /// - Parameters: - /// - adapter: `AdapterHandler`to use to adapt the request. - /// - retrier: `RetryHandler` to use to retry the request. - /// - Returns: The `Interceptor`. - public static func interceptor(adapter: @escaping AdaptHandler, retrier: @escaping RetryHandler) -> Interceptor { - Interceptor(adaptHandler: adapter, retryHandler: retrier) - } - - /// Creates an `Interceptor` using the provided `RequestAdapter` and `RequestRetrier` instances. - /// - Parameters: - /// - adapter: `RequestAdapter` to use to adapt the request - /// - retrier: `RequestRetrier` to use to retry the request. - /// - Returns: The `Interceptor`. - public static func interceptor(adapter: RequestAdapter, retrier: RequestRetrier) -> Interceptor { - Interceptor(adapter: adapter, retrier: retrier) - } - - /// Creates an `Interceptor` using the provided `RequestAdapter`s, `RequestRetrier`s, and `RequestInterceptor`s. - /// - Parameters: - /// - adapters: `RequestAdapter`s to use to adapt the request. These adapters will be run until one fails. - /// - retriers: `RequestRetrier`s to use to retry the request. These retriers will be run one at a time until - /// a retry is triggered. - /// - interceptors: `RequestInterceptor`s to use to intercept the request. - /// - Returns: The `Interceptor`. - public static func interceptor(adapters: [RequestAdapter] = [], - retriers: [RequestRetrier] = [], - interceptors: [RequestInterceptor] = []) -> Interceptor { - Interceptor(adapters: adapters, retriers: retriers, interceptors: interceptors) - } -} diff --git a/Pods/Alamofire/Source/RequestTaskMap.swift b/Pods/Alamofire/Source/RequestTaskMap.swift deleted file mode 100644 index 9955875..0000000 --- a/Pods/Alamofire/Source/RequestTaskMap.swift +++ /dev/null @@ -1,149 +0,0 @@ -// -// RequestTaskMap.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that maintains a two way, one to one map of `URLSessionTask`s to `Request`s. -struct RequestTaskMap { - private typealias Events = (completed: Bool, metricsGathered: Bool) - - private var tasksToRequests: [URLSessionTask: Request] - private var requestsToTasks: [Request: URLSessionTask] - private var taskEvents: [URLSessionTask: Events] - - var requests: [Request] { - Array(tasksToRequests.values) - } - - init(tasksToRequests: [URLSessionTask: Request] = [:], - requestsToTasks: [Request: URLSessionTask] = [:], - taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:]) { - self.tasksToRequests = tasksToRequests - self.requestsToTasks = requestsToTasks - self.taskEvents = taskEvents - } - - subscript(_ request: Request) -> URLSessionTask? { - get { requestsToTasks[request] } - set { - guard let newValue = newValue else { - guard let task = requestsToTasks[request] else { - fatalError("RequestTaskMap consistency error: no task corresponding to request found.") - } - - requestsToTasks.removeValue(forKey: request) - tasksToRequests.removeValue(forKey: task) - taskEvents.removeValue(forKey: task) - - return - } - - requestsToTasks[request] = newValue - tasksToRequests[newValue] = request - taskEvents[newValue] = (completed: false, metricsGathered: false) - } - } - - subscript(_ task: URLSessionTask) -> Request? { - get { tasksToRequests[task] } - set { - guard let newValue = newValue else { - guard let request = tasksToRequests[task] else { - fatalError("RequestTaskMap consistency error: no request corresponding to task found.") - } - - tasksToRequests.removeValue(forKey: task) - requestsToTasks.removeValue(forKey: request) - taskEvents.removeValue(forKey: task) - - return - } - - tasksToRequests[task] = newValue - requestsToTasks[newValue] = task - taskEvents[task] = (completed: false, metricsGathered: false) - } - } - - var count: Int { - precondition(tasksToRequests.count == requestsToTasks.count, - "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)") - - return tasksToRequests.count - } - - var eventCount: Int { - precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)") - - return taskEvents.count - } - - var isEmpty: Bool { - precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty, - "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)") - - return tasksToRequests.isEmpty - } - - var isEventsEmpty: Bool { - precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)") - - return taskEvents.isEmpty - } - - mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) -> Bool { - guard let events = taskEvents[task] else { - fatalError("RequestTaskMap consistency error: no events corresponding to task found.") - } - - switch (events.completed, events.metricsGathered) { - case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.") - case (false, false): taskEvents[task] = (completed: false, metricsGathered: true); return false - case (true, false): self[task] = nil; return true - } - } - - mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) -> Bool { - guard let events = taskEvents[task] else { - fatalError("RequestTaskMap consistency error: no events corresponding to task found.") - } - - switch (events.completed, events.metricsGathered) { - case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.") - #if os(Linux) || os(Android) // Linux doesn't gather metrics, so unconditionally remove the reference and return true. - default: self[task] = nil; return true - #else - case (false, false): - if #available(macOS 10.12, iOS 10, watchOS 7, tvOS 10, *) { - taskEvents[task] = (completed: true, metricsGathered: false); return false - } else { - // watchOS < 7 doesn't gather metrics, so unconditionally remove the reference and return true. - self[task] = nil; return true - } - case (false, true): - self[task] = nil; return true - #endif - } - } -} diff --git a/Pods/Alamofire/Source/Response.swift b/Pods/Alamofire/Source/Response.swift deleted file mode 100644 index d9ae9d8..0000000 --- a/Pods/Alamofire/Source/Response.swift +++ /dev/null @@ -1,453 +0,0 @@ -// -// Response.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type. -public typealias AFDataResponse = DataResponse -/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type. -public typealias AFDownloadResponse = DownloadResponse - -/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`. -public struct DataResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The data returned by the server. - public let data: Data? - - /// The final metrics of the response. - /// - /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` - /// - public let metrics: URLSessionTaskMetrics? - - /// The time taken to serialize the response. - public let serializationDuration: TimeInterval - - /// The result of response serialization. - public let result: Result - - /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Success? { result.success } - - /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Failure? { result.failure } - - /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization. - /// - /// - Parameters: - /// - request: The `URLRequest` sent to the server. - /// - response: The `HTTPURLResponse` from the server. - /// - data: The `Data` returned by the server. - /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`. - /// - serializationDuration: The duration taken by serialization. - /// - result: The `Result` of response serialization. - public init(request: URLRequest?, - response: HTTPURLResponse?, - data: Data?, - metrics: URLSessionTaskMetrics?, - serializationDuration: TimeInterval, - result: Result) { - self.request = request - self.response = response - self.data = data - self.metrics = metrics - self.serializationDuration = serializationDuration - self.result = result - } -} - -// MARK: - - -extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - "\(result)" - } - - /// The debug textual representation used when written to an output stream, which includes (if available) a summary - /// of the `URLRequest`, the request's headers and body (if decodable as a `String` below 100KB); the - /// `HTTPURLResponse`'s status code, headers, and body; the duration of the network and serialization actions; and - /// the `Result` of serialization. - public var debugDescription: String { - guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } - - let requestDescription = DebugDescription.description(of: urlRequest) - - let responseDescription = response.map { response in - let responseBodyDescription = DebugDescription.description(for: data, headers: response.headers) - - return """ - \(DebugDescription.description(of: response)) - \(responseBodyDescription.indentingNewlines()) - """ - } ?? "[Response]: None" - - let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" - - return """ - \(requestDescription) - \(responseDescription) - [Network Duration]: \(networkDuration) - [Serialization Duration]: \(serializationDuration)s - [Result]: \(result) - """ - } -} - -// MARK: - - -extension DataResponse { - /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleInt = possibleData.map { $0.count } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's - /// result is a failure, returns a response wrapping the same failure. - public func map(_ transform: (Success) -> NewSuccess) -> DataResponse { - DataResponse(request: request, - response: response, - data: data, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.map(transform)) - } - - /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result - /// value as a parameter. - /// - /// Use the `tryMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.tryMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's - /// result is a failure, returns the same failure. - public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DataResponse { - DataResponse(request: request, - response: response, - data: data, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.tryMap(transform)) - } - - /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `mapError` function with a closure that does not throw. For example: - /// - /// let possibleData: DataResponse = ... - /// let withMyError = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A closure that takes the error of the instance. - /// - /// - Returns: A `DataResponse` instance containing the result of the transform. - public func mapError(_ transform: (Failure) -> NewFailure) -> DataResponse { - DataResponse(request: request, - response: response, - data: data, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.mapError(transform)) - } - - /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `tryMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.tryMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `DataResponse` instance containing the result of the transform. - public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DataResponse { - DataResponse(request: request, - response: response, - data: data, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.tryMapError(transform)) - } -} - -// MARK: - - -/// Used to store all data associated with a serialized response of a download request. -public struct DownloadResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The final destination URL of the data returned from the server after it is moved. - public let fileURL: URL? - - /// The resume data generated if the request was cancelled. - public let resumeData: Data? - - /// The final metrics of the response. - /// - /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` - /// - public let metrics: URLSessionTaskMetrics? - - /// The time taken to serialize the response. - public let serializationDuration: TimeInterval - - /// The result of response serialization. - public let result: Result - - /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Success? { result.success } - - /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Failure? { result.failure } - - /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. - /// - /// - Parameters: - /// - request: The `URLRequest` sent to the server. - /// - response: The `HTTPURLResponse` from the server. - /// - fileURL: The final destination URL of the data returned from the server after it is moved. - /// - resumeData: The resume `Data` generated if the request was cancelled. - /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`. - /// - serializationDuration: The duration taken by serialization. - /// - result: The `Result` of response serialization. - public init(request: URLRequest?, - response: HTTPURLResponse?, - fileURL: URL?, - resumeData: Data?, - metrics: URLSessionTaskMetrics?, - serializationDuration: TimeInterval, - result: Result) { - self.request = request - self.response = response - self.fileURL = fileURL - self.resumeData = resumeData - self.metrics = metrics - self.serializationDuration = serializationDuration - self.result = result - } -} - -// MARK: - - -extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - "\(result)" - } - - /// The debug textual representation used when written to an output stream, which includes the URL request, the URL - /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization - /// actions, and the response serialization result. - public var debugDescription: String { - guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } - - let requestDescription = DebugDescription.description(of: urlRequest) - let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None" - let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" - let resumeDataDescription = resumeData.map { "\($0)" } ?? "None" - - return """ - \(requestDescription) - \(responseDescription) - [File URL]: \(fileURL?.path ?? "None") - [Resume Data]: \(resumeDataDescription) - [Network Duration]: \(networkDuration) - [Serialization Duration]: \(serializationDuration)s - [Result]: \(result) - """ - } -} - -// MARK: - - -extension DownloadResponse { - /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleInt = possibleData.map { $0.count } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's - /// result is a failure, returns a response wrapping the same failure. - public func map(_ transform: (Success) -> NewSuccess) -> DownloadResponse { - DownloadResponse(request: request, - response: response, - fileURL: fileURL, - resumeData: resumeData, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.map(transform)) - } - - /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `tryMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.tryMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this - /// instance's result is a failure, returns the same failure. - public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse { - DownloadResponse(request: request, - response: response, - fileURL: fileURL, - resumeData: resumeData, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.tryMap(transform)) - } - - /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `mapError` function with a closure that does not throw. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let withMyError = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A closure that takes the error of the instance. - /// - /// - Returns: A `DownloadResponse` instance containing the result of the transform. - public func mapError(_ transform: (Failure) -> NewFailure) -> DownloadResponse { - DownloadResponse(request: request, - response: response, - fileURL: fileURL, - resumeData: resumeData, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.mapError(transform)) - } - - /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `tryMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.tryMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `DownloadResponse` instance containing the result of the transform. - public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse { - DownloadResponse(request: request, - response: response, - fileURL: fileURL, - resumeData: resumeData, - metrics: metrics, - serializationDuration: serializationDuration, - result: result.tryMapError(transform)) - } -} - -private enum DebugDescription { - static func description(of request: URLRequest) -> String { - let requestSummary = "\(request.httpMethod!) \(request)" - let requestHeadersDescription = DebugDescription.description(for: request.headers) - let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers) - - return """ - [Request]: \(requestSummary) - \(requestHeadersDescription.indentingNewlines()) - \(requestBodyDescription.indentingNewlines()) - """ - } - - static func description(of response: HTTPURLResponse) -> String { - """ - [Response]: - [Status Code]: \(response.statusCode) - \(DebugDescription.description(for: response.headers).indentingNewlines()) - """ - } - - static func description(for headers: HTTPHeaders) -> String { - guard !headers.isEmpty else { return "[Headers]: None" } - - let headerDescription = "\(headers.sorted())".indentingNewlines() - return """ - [Headers]: - \(headerDescription) - """ - } - - static func description(for data: Data?, - headers: HTTPHeaders, - allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"], - maximumLength: Int = 100_000) -> String { - guard let data = data, !data.isEmpty else { return "[Body]: None" } - - guard - data.count <= maximumLength, - printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true) - else { return "[Body]: \(data.count) bytes" } - - return """ - [Body]: - \(String(decoding: data, as: UTF8.self) - .trimmingCharacters(in: .whitespacesAndNewlines) - .indentingNewlines()) - """ - } -} - -extension String { - fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String { - let spaces = String(repeating: " ", count: spaceCount) - return replacingOccurrences(of: "\n", with: "\n\(spaces)") - } -} diff --git a/Pods/Alamofire/Source/ResponseSerialization.swift b/Pods/Alamofire/Source/ResponseSerialization.swift deleted file mode 100644 index 0e718bd..0000000 --- a/Pods/Alamofire/Source/ResponseSerialization.swift +++ /dev/null @@ -1,1270 +0,0 @@ -// -// ResponseSerialization.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -// MARK: Protocols - -/// The type to which all data response serializers must conform in order to serialize a response. -public protocol DataResponseSerializerProtocol { - /// The type of serialized object to be created. - associatedtype SerializedObject - - /// Serialize the response `Data` into the provided type.. - /// - /// - Parameters: - /// - request: `URLRequest` which was used to perform the request, if any. - /// - response: `HTTPURLResponse` received from the server, if any. - /// - data: `Data` returned from the server, if any. - /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. - /// - /// - Returns: The `SerializedObject`. - /// - Throws: Any `Error` produced during serialization. - func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject -} - -/// The type to which all download response serializers must conform in order to serialize a response. -public protocol DownloadResponseSerializerProtocol { - /// The type of serialized object to be created. - associatedtype SerializedObject - - /// Serialize the downloaded response `Data` from disk into the provided type.. - /// - /// - Parameters: - /// - request: `URLRequest` which was used to perform the request, if any. - /// - response: `HTTPURLResponse` received from the server, if any. - /// - fileURL: File `URL` to which the response data was downloaded. - /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. - /// - /// - Returns: The `SerializedObject`. - /// - Throws: Any `Error` produced during serialization. - func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject -} - -/// A serializer that can handle both data and download responses. -public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { - /// `DataPreprocessor` used to prepare incoming `Data` for serialization. - var dataPreprocessor: DataPreprocessor { get } - /// `HTTPMethod`s for which empty response bodies are considered appropriate. - var emptyRequestMethods: Set { get } - /// HTTP response codes for which empty response bodies are considered appropriate. - var emptyResponseCodes: Set { get } -} - -/// Type used to preprocess `Data` before it handled by a serializer. -public protocol DataPreprocessor { - /// Process `Data` before it's handled by a serializer. - /// - Parameter data: The raw `Data` to process. - func preprocess(_ data: Data) throws -> Data -} - -/// `DataPreprocessor` that returns passed `Data` without any transform. -public struct PassthroughPreprocessor: DataPreprocessor { - public init() {} - - public func preprocess(_ data: Data) throws -> Data { data } -} - -/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header. -public struct GoogleXSSIPreprocessor: DataPreprocessor { - public init() {} - - public func preprocess(_ data: Data) throws -> Data { - (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data - } -} - -extension DataPreprocessor where Self == PassthroughPreprocessor { - /// Provides a `PassthroughPreprocessor` instance. - public static var passthrough: PassthroughPreprocessor { PassthroughPreprocessor() } -} - -extension DataPreprocessor where Self == GoogleXSSIPreprocessor { - /// Provides a `GoogleXSSIPreprocessor` instance. - public static var googleXSSI: GoogleXSSIPreprocessor { GoogleXSSIPreprocessor() } -} - -extension ResponseSerializer { - /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default. - public static var defaultDataPreprocessor: DataPreprocessor { PassthroughPreprocessor() } - /// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default. - public static var defaultEmptyRequestMethods: Set { [.head] } - /// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default. - public static var defaultEmptyResponseCodes: Set { [204, 205] } - - public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor } - public var emptyRequestMethods: Set { Self.defaultEmptyRequestMethods } - public var emptyResponseCodes: Set { Self.defaultEmptyResponseCodes } - - /// Determines whether the `request` allows empty response bodies, if `request` exists. - /// - /// - Parameter request: `URLRequest` to evaluate. - /// - /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`. - public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? { - request.flatMap(\.httpMethod) - .flatMap(HTTPMethod.init) - .map { emptyRequestMethods.contains($0) } - } - - /// Determines whether the `response` allows empty response bodies, if `response` exists`. - /// - /// - Parameter response: `HTTPURLResponse` to evaluate. - /// - /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`. - public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? { - response.map(\.statusCode) - .map { emptyResponseCodes.contains($0) } - } - - /// Determines whether `request` and `response` allow empty response bodies. - /// - /// - Parameters: - /// - request: `URLRequest` to evaluate. - /// - response: `HTTPURLResponse` to evaluate. - /// - /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise. - public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool { - (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true) - } -} - -/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds -/// the data read from disk into the data response serializer. -extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol { - public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject { - guard error == nil else { throw error! } - - guard let fileURL = fileURL else { - throw AFError.responseSerializationFailed(reason: .inputFileNil) - } - - let data: Data - do { - data = try Data(contentsOf: fileURL) - } catch { - throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)) - } - - do { - return try serialize(request: request, response: response, data: data, error: error) - } catch { - throw error - } - } -} - -// MARK: - Default - -extension DataRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) -> Self { - appendResponseSerializer { - // Start work that should be on the serialization queue. - let result = AFResult(value: self.data, error: self.error) - // End work that should be on the serialization queue. - - self.underlyingQueue.async { - let response = DataResponse(request: self.request, - response: self.response, - data: self.data, - metrics: self.metrics, - serializationDuration: 0, - result: result) - - self.eventMonitor?.request(self, didParseResponse: response) - - self.responseSerializerDidComplete { queue.async { completionHandler(response) } } - } - } - - return self - } - - private func _response(queue: DispatchQueue = .main, - responseSerializer: Serializer, - completionHandler: @escaping (AFDataResponse) -> Void) - -> Self { - appendResponseSerializer { - // Start work that should be on the serialization queue. - let start = ProcessInfo.processInfo.systemUptime - let result: AFResult = Result { - try responseSerializer.serialize(request: self.request, - response: self.response, - data: self.data, - error: self.error) - }.mapError { error in - error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) - } - - let end = ProcessInfo.processInfo.systemUptime - // End work that should be on the serialization queue. - - self.underlyingQueue.async { - let response = DataResponse(request: self.request, - response: self.response, - data: self.data, - metrics: self.metrics, - serializationDuration: end - start, - result: result) - - self.eventMonitor?.request(self, didParseResponse: response) - - guard !self.isCancelled, let serializerError = result.failure, let delegate = self.delegate else { - self.responseSerializerDidComplete { queue.async { completionHandler(response) } } - return - } - - delegate.retryResult(for: self, dueTo: serializerError) { retryResult in - var didComplete: (() -> Void)? - - defer { - if let didComplete = didComplete { - self.responseSerializerDidComplete { queue.async { didComplete() } } - } - } - - switch retryResult { - case .doNotRetry: - didComplete = { completionHandler(response) } - - case let .doNotRetryWithError(retryError): - let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) - - let response = DataResponse(request: self.request, - response: self.response, - data: self.data, - metrics: self.metrics, - serializationDuration: end - start, - result: result) - - didComplete = { completionHandler(response) } - - case .retry, .retryWithDelay: - delegate.retryRequest(self, withDelay: retryResult.delay) - } - } - } - } - - return self - } - - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default - /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, - responseSerializer: Serializer, - completionHandler: @escaping (AFDataResponse) -> Void) - -> Self { - _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) - } - - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default - /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, - responseSerializer: Serializer, - completionHandler: @escaping (AFDataResponse) -> Void) - -> Self { - _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) - } -} - -extension DownloadRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, - completionHandler: @escaping (AFDownloadResponse) -> Void) - -> Self { - appendResponseSerializer { - // Start work that should be on the serialization queue. - let result = AFResult(value: self.fileURL, error: self.error) - // End work that should be on the serialization queue. - - self.underlyingQueue.async { - let response = DownloadResponse(request: self.request, - response: self.response, - fileURL: self.fileURL, - resumeData: self.resumeData, - metrics: self.metrics, - serializationDuration: 0, - result: result) - - self.eventMonitor?.request(self, didParseResponse: response) - - self.responseSerializerDidComplete { queue.async { completionHandler(response) } } - } - } - - return self - } - - private func _response(queue: DispatchQueue = .main, - responseSerializer: Serializer, - completionHandler: @escaping (AFDownloadResponse) -> Void) - -> Self { - appendResponseSerializer { - // Start work that should be on the serialization queue. - let start = ProcessInfo.processInfo.systemUptime - let result: AFResult = Result { - try responseSerializer.serializeDownload(request: self.request, - response: self.response, - fileURL: self.fileURL, - error: self.error) - }.mapError { error in - error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) - } - let end = ProcessInfo.processInfo.systemUptime - // End work that should be on the serialization queue. - - self.underlyingQueue.async { - let response = DownloadResponse(request: self.request, - response: self.response, - fileURL: self.fileURL, - resumeData: self.resumeData, - metrics: self.metrics, - serializationDuration: end - start, - result: result) - - self.eventMonitor?.request(self, didParseResponse: response) - - guard let serializerError = result.failure, let delegate = self.delegate else { - self.responseSerializerDidComplete { queue.async { completionHandler(response) } } - return - } - - delegate.retryResult(for: self, dueTo: serializerError) { retryResult in - var didComplete: (() -> Void)? - - defer { - if let didComplete = didComplete { - self.responseSerializerDidComplete { queue.async { didComplete() } } - } - } - - switch retryResult { - case .doNotRetry: - didComplete = { completionHandler(response) } - - case let .doNotRetryWithError(retryError): - let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) - - let response = DownloadResponse(request: self.request, - response: self.response, - fileURL: self.fileURL, - resumeData: self.resumeData, - metrics: self.metrics, - serializationDuration: end - start, - result: result) - - didComplete = { completionHandler(response) } - - case .retry, .retryWithDelay: - delegate.retryRequest(self, withDelay: retryResult.delay) - } - } - } - } - - return self - } - - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - responseSerializer: The response serializer responsible for serializing the request, response, and data - /// contained in the destination `URL`. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, - responseSerializer: Serializer, - completionHandler: @escaping (AFDownloadResponse) -> Void) - -> Self { - _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) - } - - /// Adds a handler to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - responseSerializer: The response serializer responsible for serializing the request, response, and data - /// contained in the destination `URL`. - /// - completionHandler: The code to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func response(queue: DispatchQueue = .main, - responseSerializer: Serializer, - completionHandler: @escaping (AFDownloadResponse) -> Void) - -> Self { - _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) - } -} - -// MARK: - URL - -/// A `DownloadResponseSerializerProtocol` that performs only `Error` checking and ensures that a downloaded `fileURL` -/// is present. -public struct URLResponseSerializer: DownloadResponseSerializerProtocol { - /// Creates an instance. - public init() {} - - public func serializeDownload(request: URLRequest?, - response: HTTPURLResponse?, - fileURL: URL?, - error: Error?) throws -> URL { - guard error == nil else { throw error! } - - guard let url = fileURL else { - throw AFError.responseSerializationFailed(reason: .inputFileNil) - } - - return url - } -} - -extension DownloadResponseSerializerProtocol where Self == URLResponseSerializer { - /// Provides a `URLResponseSerializer` instance. - public static var url: URLResponseSerializer { URLResponseSerializer() } -} - -extension DownloadRequest { - /// Adds a handler using a `URLResponseSerializer` to be called once the request is finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is called. `.main` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseURL(queue: DispatchQueue = .main, - completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { - response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler) - } -} - -// MARK: - Data - -/// A `ResponseSerializer` that performs minimal response checking and returns any response `Data` as-is. By default, a -/// request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the -/// response has an HTTP status code valid for empty responses, then an empty `Data` value is returned. -public final class DataResponseSerializer: ResponseSerializer { - public let dataPreprocessor: DataPreprocessor - public let emptyResponseCodes: Set - public let emptyRequestMethods: Set - - /// Creates a `DataResponseSerializer` using the provided parameters. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) { - self.dataPreprocessor = dataPreprocessor - self.emptyResponseCodes = emptyResponseCodes - self.emptyRequestMethods = emptyRequestMethods - } - - public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data { - guard error == nil else { throw error! } - - guard var data = data, !data.isEmpty else { - guard emptyResponseAllowed(forRequest: request, response: response) else { - throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - } - - return Data() - } - - data = try dataPreprocessor.preprocess(data) - - return data - } -} - -extension ResponseSerializer where Self == DataResponseSerializer { - /// Provides a default `DataResponseSerializer` instance. - public static var data: DataResponseSerializer { DataResponseSerializer() } - - /// Creates a `DataResponseSerializer` using the provided parameters. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - /// - /// - Returns: The `DataResponseSerializer`. - public static func data(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponseSerializer { - DataResponseSerializer(dataPreprocessor: dataPreprocessor, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods) - } -} - -extension DataRequest { - /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is called. `.main` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the - /// `completionHandler`. `PassthroughPreprocessor()` by default. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseData(queue: DispatchQueue = .main, - dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self { - response(queue: queue, - responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - completionHandler: completionHandler) - } -} - -extension DownloadRequest { - /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is called. `.main` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the - /// `completionHandler`. `PassthroughPreprocessor()` by default. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseData(queue: DispatchQueue = .main, - dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, - completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { - response(queue: queue, - responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - completionHandler: completionHandler) - } -} - -// MARK: - String - -/// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no -/// data is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code -/// valid for empty responses, then an empty `String` is returned. -public final class StringResponseSerializer: ResponseSerializer { - public let dataPreprocessor: DataPreprocessor - /// Optional string encoding used to validate the response. - public let encoding: String.Encoding? - public let emptyResponseCodes: Set - public let emptyRequestMethods: Set - - /// Creates an instance with the provided values. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined - /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, - encoding: String.Encoding? = nil, - emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) { - self.dataPreprocessor = dataPreprocessor - self.encoding = encoding - self.emptyResponseCodes = emptyResponseCodes - self.emptyRequestMethods = emptyRequestMethods - } - - public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String { - guard error == nil else { throw error! } - - guard var data = data, !data.isEmpty else { - guard emptyResponseAllowed(forRequest: request, response: response) else { - throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - } - - return "" - } - - data = try dataPreprocessor.preprocess(data) - - var convertedEncoding = encoding - - if let encodingName = response?.textEncodingName, convertedEncoding == nil { - convertedEncoding = String.Encoding(ianaCharsetName: encodingName) - } - - let actualEncoding = convertedEncoding ?? .isoLatin1 - - guard let string = String(data: data, encoding: actualEncoding) else { - throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)) - } - - return string - } -} - -extension ResponseSerializer where Self == StringResponseSerializer { - /// Provides a default `StringResponseSerializer` instance. - public static var string: StringResponseSerializer { StringResponseSerializer() } - - /// Creates a `StringResponseSerializer` with the provided values. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined - /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - /// - /// - Returns: The `StringResponseSerializer`. - public static func string(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, - encoding: String.Encoding? = nil, - emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> StringResponseSerializer { - StringResponseSerializer(dataPreprocessor: dataPreprocessor, - encoding: encoding, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods) - } -} - -extension DataRequest { - /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the - /// `completionHandler`. `PassthroughPreprocessor()` by default. - /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined - /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseString(queue: DispatchQueue = .main, - dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, - encoding: String.Encoding? = nil, - emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self { - response(queue: queue, - responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, - encoding: encoding, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - completionHandler: completionHandler) - } -} - -extension DownloadRequest { - /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the - /// `completionHandler`. `PassthroughPreprocessor()` by default. - /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined - /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseString(queue: DispatchQueue = .main, - dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, - encoding: String.Encoding? = nil, - emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, - completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { - response(queue: queue, - responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, - encoding: encoding, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - completionHandler: completionHandler) - } -} - -// MARK: - JSON - -/// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning -/// `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the response has an -/// HTTP status code valid for empty responses, then an `NSNull` value is returned. -@available(*, deprecated, message: "JSONResponseSerializer deprecated and will be removed in Alamofire 6. Use DecodableResponseSerializer instead.") -public final class JSONResponseSerializer: ResponseSerializer { - public let dataPreprocessor: DataPreprocessor - public let emptyResponseCodes: Set - public let emptyRequestMethods: Set - /// `JSONSerialization.ReadingOptions` used when serializing a response. - public let options: JSONSerialization.ReadingOptions - - /// Creates an instance with the provided values. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - /// - options: The options to use. `.allowFragments` by default. - public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, - options: JSONSerialization.ReadingOptions = .allowFragments) { - self.dataPreprocessor = dataPreprocessor - self.emptyResponseCodes = emptyResponseCodes - self.emptyRequestMethods = emptyRequestMethods - self.options = options - } - - public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any { - guard error == nil else { throw error! } - - guard var data = data, !data.isEmpty else { - guard emptyResponseAllowed(forRequest: request, response: response) else { - throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - } - - return NSNull() - } - - data = try dataPreprocessor.preprocess(data) - - do { - return try JSONSerialization.jsonObject(with: data, options: options) - } catch { - throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)) - } - } -} - -extension DataRequest { - /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the - /// `completionHandler`. `PassthroughPreprocessor()` by default. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` - /// by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") - @discardableResult - public func responseJSON(queue: DispatchQueue = .main, - dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self { - response(queue: queue, - responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods, - options: options), - completionHandler: completionHandler) - } -} - -extension DownloadRequest { - /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. - /// - /// - Parameters: - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the - /// `completionHandler`. `PassthroughPreprocessor()` by default. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` - /// by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") - @discardableResult - public func responseJSON(queue: DispatchQueue = .main, - dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, - emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { - response(queue: queue, - responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods, - options: options), - completionHandler: completionHandler) - } -} - -// MARK: - Empty - -/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance. -public protocol EmptyResponse { - /// Empty value for the conforming type. - /// - /// - Returns: Value of `Self` to use for empty values. - static func emptyValue() -> Self -} - -/// Type representing an empty value. Use `Empty.value` to get the static instance. -public struct Empty: Codable { - /// Static `Empty` instance used for all `Empty` responses. - public static let value = Empty() -} - -extension Empty: EmptyResponse { - public static func emptyValue() -> Empty { - value - } -} - -// MARK: - DataDecoder Protocol - -/// Any type which can decode `Data` into a `Decodable` type. -public protocol DataDecoder { - /// Decode `Data` into the provided type. - /// - /// - Parameters: - /// - type: The `Type` to be decoded. - /// - data: The `Data` to be decoded. - /// - /// - Returns: The decoded value of type `D`. - /// - Throws: Any error that occurs during decode. - func decode(_ type: D.Type, from data: Data) throws -> D -} - -/// `JSONDecoder` automatically conforms to `DataDecoder`. -extension JSONDecoder: DataDecoder {} -/// `PropertyListDecoder` automatically conforms to `DataDecoder`. -extension PropertyListDecoder: DataDecoder {} - -// MARK: - Decodable - -/// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to -/// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data -/// is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code valid -/// for empty responses then an empty value will be returned. If the decoded type conforms to `EmptyResponse`, the -/// type's `emptyValue()` will be returned. If the decoded type is `Empty`, the `.value` instance is returned. If the -/// decoded type *does not* conform to `EmptyResponse` and isn't `Empty`, an error will be produced. -public final class DecodableResponseSerializer: ResponseSerializer { - public let dataPreprocessor: DataPreprocessor - /// The `DataDecoder` instance used to decode responses. - public let decoder: DataDecoder - public let emptyResponseCodes: Set - public let emptyRequestMethods: Set - - /// Creates an instance using the values provided. - /// - /// - Parameters: - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) { - self.dataPreprocessor = dataPreprocessor - self.decoder = decoder - self.emptyResponseCodes = emptyResponseCodes - self.emptyRequestMethods = emptyRequestMethods - } - - public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T { - guard error == nil else { throw error! } - - guard var data = data, !data.isEmpty else { - guard emptyResponseAllowed(forRequest: request, response: response) else { - throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) - } - - guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else { - throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)")) - } - - return emptyValue - } - - data = try dataPreprocessor.preprocess(data) - - do { - return try decoder.decode(T.self, from: data) - } catch { - throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) - } - } -} - -extension ResponseSerializer { - /// Creates a `DecodableResponseSerializer` using the values provided. - /// - /// - Parameters: - /// - type: `Decodable` type to decode from response data. - /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. - /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. - /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. - /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. - /// - /// - Returns: The `DecodableResponseSerializer`. - public static func decodable(of type: T.Type, - dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DecodableResponseSerializer where Self == DecodableResponseSerializer { - DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, - decoder: decoder, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods) - } -} - -extension DataRequest { - /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. - /// - /// - Parameters: - /// - type: `Decodable` type to decode from response data. - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the - /// `completionHandler`. `PassthroughPreprocessor()` by default. - /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseDecodable(of type: T.Type = T.self, - queue: DispatchQueue = .main, - dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, - completionHandler: @escaping (AFDataResponse) -> Void) -> Self { - response(queue: queue, - responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, - decoder: decoder, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - completionHandler: completionHandler) - } -} - -extension DownloadRequest { - /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. - /// - /// - Parameters: - /// - type: `Decodable` type to decode from response data. - /// - queue: The queue on which the completion handler is dispatched. `.main` by default. - /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the - /// `completionHandler`. `PassthroughPreprocessor()` by default. - /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. - /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. - /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. - /// - completionHandler: A closure to be executed once the request has finished. - /// - /// - Returns: The request. - @discardableResult - public func responseDecodable(of type: T.Type = T.self, - queue: DispatchQueue = .main, - dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, - decoder: DataDecoder = JSONDecoder(), - emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, - emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, - completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { - response(queue: queue, - responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, - decoder: decoder, - emptyResponseCodes: emptyResponseCodes, - emptyRequestMethods: emptyRequestMethods), - completionHandler: completionHandler) - } -} - -// MARK: - DataStreamRequest - -/// A type which can serialize incoming `Data`. -public protocol DataStreamSerializer { - /// Type produced from the serialized `Data`. - associatedtype SerializedObject - - /// Serializes incoming `Data` into a `SerializedObject` value. - /// - /// - Parameter data: `Data` to be serialized. - /// - /// - Throws: Any error produced during serialization. - func serialize(_ data: Data) throws -> SerializedObject -} - -/// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`. -public struct DecodableStreamSerializer: DataStreamSerializer { - /// `DataDecoder` used to decode incoming `Data`. - public let decoder: DataDecoder - /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`. - public let dataPreprocessor: DataPreprocessor - - /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`. - /// - Parameters: - /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. - /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the - /// `decoder`. `PassthroughPreprocessor()` by default. - public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) { - self.decoder = decoder - self.dataPreprocessor = dataPreprocessor - } - - public func serialize(_ data: Data) throws -> T { - let processedData = try dataPreprocessor.preprocess(data) - do { - return try decoder.decode(T.self, from: processedData) - } catch { - throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) - } - } -} - -/// `DataStreamSerializer` which performs no serialization on incoming `Data`. -public struct PassthroughStreamSerializer: DataStreamSerializer { - /// Creates an instance. - public init() {} - - public func serialize(_ data: Data) throws -> Data { data } -} - -/// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values. -public struct StringStreamSerializer: DataStreamSerializer { - /// Creates an instance. - public init() {} - - public func serialize(_ data: Data) throws -> String { - String(decoding: data, as: UTF8.self) - } -} - -extension DataStreamSerializer { - /// Creates a `DecodableStreamSerializer` instance with the provided `DataDecoder` and `DataPreprocessor`. - /// - /// - Parameters: - /// - type: `Decodable` type to decode from stream data. - /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. - /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the - /// `decoder`. `PassthroughPreprocessor()` by default. - public static func decodable(of type: T.Type, - decoder: DataDecoder = JSONDecoder(), - dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) -> Self where Self == DecodableStreamSerializer { - DecodableStreamSerializer(decoder: decoder, dataPreprocessor: dataPreprocessor) - } -} - -extension DataStreamSerializer where Self == PassthroughStreamSerializer { - /// Provides a `PassthroughStreamSerializer` instance. - public static var passthrough: PassthroughStreamSerializer { PassthroughStreamSerializer() } -} - -extension DataStreamSerializer where Self == StringStreamSerializer { - /// Provides a `StringStreamSerializer` instance. - public static var string: StringStreamSerializer { StringStreamSerializer() } -} - -extension DataStreamRequest { - /// Adds a `StreamHandler` which performs no parsing on incoming `Data`. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. - /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. - /// - /// - Returns: The `DataStreamRequest`. - @discardableResult - public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler) -> Self { - let parser = { [unowned self] (data: Data) in - queue.async { - self.capturingError { - try stream(.init(event: .stream(.success(data)), token: .init(self))) - } - - self.updateAndCompleteIfPossible() - } - } - - $streamMutableState.write { $0.streams.append(parser) } - appendStreamCompletion(on: queue, stream: stream) - - return self - } - - /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`. - /// - /// - Parameters: - /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`. - /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. - /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. - /// - /// - Returns: The `DataStreamRequest`. - @discardableResult - public func responseStream(using serializer: Serializer, - on queue: DispatchQueue = .main, - stream: @escaping Handler) -> Self { - let parser = { [unowned self] (data: Data) in - serializationQueue.async { - // Start work on serialization queue. - let result = Result { try serializer.serialize(data) } - .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) } - // End work on serialization queue. - self.underlyingQueue.async { - self.eventMonitor?.request(self, didParseStream: result) - - if result.isFailure, self.automaticallyCancelOnStreamError { - self.cancel() - } - - queue.async { - self.capturingError { - try stream(.init(event: .stream(result), token: .init(self))) - } - - self.updateAndCompleteIfPossible() - } - } - } - } - - $streamMutableState.write { $0.streams.append(parser) } - appendStreamCompletion(on: queue, stream: stream) - - return self - } - - /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. - /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. - /// - /// - Returns: The `DataStreamRequest`. - @discardableResult - public func responseStreamString(on queue: DispatchQueue = .main, - stream: @escaping Handler) -> Self { - let parser = { [unowned self] (data: Data) in - serializationQueue.async { - // Start work on serialization queue. - let string = String(decoding: data, as: UTF8.self) - // End work on serialization queue. - self.underlyingQueue.async { - self.eventMonitor?.request(self, didParseStream: .success(string)) - - queue.async { - self.capturingError { - try stream(.init(event: .stream(.success(string)), token: .init(self))) - } - - self.updateAndCompleteIfPossible() - } - } - } - } - - $streamMutableState.write { $0.streams.append(parser) } - appendStreamCompletion(on: queue, stream: stream) - - return self - } - - private func updateAndCompleteIfPossible() { - $streamMutableState.write { state in - state.numberOfExecutingStreams -= 1 - - guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return } - - let completionEvents = state.enqueuedCompletionEvents - self.underlyingQueue.async { completionEvents.forEach { $0() } } - state.enqueuedCompletionEvents.removeAll() - } - } - - /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`. - /// - /// - Parameters: - /// - type: `Decodable` type to parse incoming `Data` into. - /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. - /// - decoder: `DataDecoder` used to decode the incoming `Data`. - /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`. - /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. - /// - /// - Returns: The `DataStreamRequest`. - @discardableResult - public func responseStreamDecodable(of type: T.Type = T.self, - on queue: DispatchQueue = .main, - using decoder: DataDecoder = JSONDecoder(), - preprocessor: DataPreprocessor = PassthroughPreprocessor(), - stream: @escaping Handler) -> Self { - responseStream(using: DecodableStreamSerializer(decoder: decoder, dataPreprocessor: preprocessor), - stream: stream) - } -} diff --git a/Pods/Alamofire/Source/Result+Alamofire.swift b/Pods/Alamofire/Source/Result+Alamofire.swift deleted file mode 100644 index 39ac286..0000000 --- a/Pods/Alamofire/Source/Result+Alamofire.swift +++ /dev/null @@ -1,120 +0,0 @@ -// -// Result+Alamofire.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Default type of `Result` returned by Alamofire, with an `AFError` `Failure` type. -public typealias AFResult = Result - -// MARK: - Internal APIs - -extension Result { - /// Returns whether the instance is `.success`. - var isSuccess: Bool { - guard case .success = self else { return false } - return true - } - - /// Returns whether the instance is `.failure`. - var isFailure: Bool { - !isSuccess - } - - /// Returns the associated value if the result is a success, `nil` otherwise. - var success: Success? { - guard case let .success(value) = self else { return nil } - return value - } - - /// Returns the associated error value if the result is a failure, `nil` otherwise. - var failure: Failure? { - guard case let .failure(error) = self else { return nil } - return error - } - - /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise. - /// - /// - Parameters: - /// - value: A value. - /// - error: An `Error`. - init(value: Success, error: Failure?) { - if let error = error { - self = .failure(error) - } else { - self = .success(value) - } - } - - /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. - /// - /// Use the `tryMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: Result = .success(Data(...)) - /// let possibleObject = possibleData.tryMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance. - /// - /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the - /// same failure. - func tryMap(_ transform: (Success) throws -> NewSuccess) -> Result { - switch self { - case let .success(value): - do { - return try .success(transform(value)) - } catch { - return .failure(error) - } - case let .failure(error): - return .failure(error) - } - } - - /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `tryMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: Result = .success(Data(...)) - /// let possibleObject = possibleData.tryMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns - /// the same success. - func tryMapError(_ transform: (Failure) throws -> NewFailure) -> Result { - switch self { - case let .failure(error): - do { - return try .failure(transform(error)) - } catch { - return .failure(error) - } - case let .success(value): - return .success(value) - } - } -} diff --git a/Pods/Alamofire/Source/RetryPolicy.swift b/Pods/Alamofire/Source/RetryPolicy.swift deleted file mode 100644 index bb52c6c..0000000 --- a/Pods/Alamofire/Source/RetryPolicy.swift +++ /dev/null @@ -1,430 +0,0 @@ -// -// RetryPolicy.swift -// -// Copyright (c) 2019-2020 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes -/// as well as certain types of networking errors. -open class RetryPolicy: RequestInterceptor { - /// The default retry limit for retry policies. - public static let defaultRetryLimit: UInt = 2 - - /// The default exponential backoff base for retry policies (must be a minimum of 2). - public static let defaultExponentialBackoffBase: UInt = 2 - - /// The default exponential backoff scale for retry policies. - public static let defaultExponentialBackoffScale: Double = 0.5 - - /// The default HTTP methods to retry. - /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information. - public static let defaultRetryableHTTPMethods: Set = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent - .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent - .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent - .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent - .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent - .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent - ] - - /// The default HTTP status codes to retry. - /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information. - public static let defaultRetryableHTTPStatusCodes: Set = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9) - 500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1) - 502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3) - 503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4) - 504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5) - ] - - /// The default URL error codes to retry. - public static let defaultRetryableURLErrorCodes: Set = [ // [Security] App Transport Security disallowed a connection because there is no secure network connection. - // - [Disabled] ATS settings do not change at runtime. - // .appTransportSecurityRequiresSecureConnection, - - // [System] An app or app extension attempted to connect to a background session that is already connected to a - // process. - // - [Enabled] The other process could release the background session. - .backgroundSessionInUseByAnotherProcess, - - // [System] The shared container identifier of the URL session configuration is needed but has not been set. - // - [Disabled] Cannot change at runtime. - // .backgroundSessionRequiresSharedContainer, - - // [System] The app is suspended or exits while a background data task is processing. - // - [Enabled] App can be foregrounded or launched to recover. - .backgroundSessionWasDisconnected, - - // [Network] The URL Loading system received bad data from the server. - // - [Enabled] Server could return valid data when retrying. - .badServerResponse, - - // [Resource] A malformed URL prevented a URL request from being initiated. - // - [Disabled] URL was most likely constructed incorrectly. - // .badURL, - - // [System] A connection was attempted while a phone call is active on a network that does not support - // simultaneous phone and data communication (EDGE or GPRS). - // - [Enabled] Phone call could be ended to allow request to recover. - .callIsActive, - - // [Client] An asynchronous load has been canceled. - // - [Disabled] Request was cancelled by the client. - // .cancelled, - - // [File System] A download task couldn’t close the downloaded file on disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotCloseFile, - - // [Network] An attempt to connect to a host failed. - // - [Enabled] Server or DNS lookup could recover during retry. - .cannotConnectToHost, - - // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotCreateFile, - - // [Data] Content data received during a connection request had an unknown content encoding. - // - [Disabled] Server is unlikely to modify the content encoding during a retry. - // .cannotDecodeContentData, - - // [Data] Content data received during a connection request could not be decoded for a known content encoding. - // - [Disabled] Server is unlikely to modify the content encoding during a retry. - // .cannotDecodeRawData, - - // [Network] The host name for a URL could not be resolved. - // - [Enabled] Server or DNS lookup could recover during retry. - .cannotFindHost, - - // [Network] A request to load an item only from the cache could not be satisfied. - // - [Enabled] Cache could be populated during a retry. - .cannotLoadFromNetwork, - - // [File System] A download task was unable to move a downloaded file on disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotMoveFile, - - // [File System] A download task was unable to open the downloaded file on disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotOpenFile, - - // [Data] A task could not parse a response. - // - [Disabled] Invalid response is unlikely to recover with retry. - // .cannotParseResponse, - - // [File System] A download task was unable to remove a downloaded file from disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotRemoveFile, - - // [File System] A download task was unable to write to the downloaded file on disk. - // - [Disabled] File system error is unlikely to recover with retry. - // .cannotWriteToFile, - - // [Security] A client certificate was rejected. - // - [Disabled] Client certificate is unlikely to change with retry. - // .clientCertificateRejected, - - // [Security] A client certificate was required to authenticate an SSL connection during a request. - // - [Disabled] Client certificate is unlikely to be provided with retry. - // .clientCertificateRequired, - - // [Data] The length of the resource data exceeds the maximum allowed. - // - [Disabled] Resource will likely still exceed the length maximum on retry. - // .dataLengthExceedsMaximum, - - // [System] The cellular network disallowed a connection. - // - [Enabled] WiFi connection could be established during retry. - .dataNotAllowed, - - // [Network] The host address could not be found via DNS lookup. - // - [Enabled] DNS lookup could succeed during retry. - .dnsLookupFailed, - - // [Data] A download task failed to decode an encoded file during the download. - // - [Enabled] Server could correct the decoding issue with retry. - .downloadDecodingFailedMidStream, - - // [Data] A download task failed to decode an encoded file after downloading. - // - [Enabled] Server could correct the decoding issue with retry. - .downloadDecodingFailedToComplete, - - // [File System] A file does not exist. - // - [Disabled] File system error is unlikely to recover with retry. - // .fileDoesNotExist, - - // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file, - // but a directory. - // - [Disabled] FTP directory is not likely to change to a file during a retry. - // .fileIsDirectory, - - // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been - // exceeded (currently 16). - // - [Disabled] The redirect loop is unlikely to be resolved within the retry window. - // .httpTooManyRedirects, - - // [System] The attempted connection required activating a data context while roaming, but international roaming - // is disabled. - // - [Enabled] WiFi connection could be established during retry. - .internationalRoamingOff, - - // [Connectivity] A client or server connection was severed in the middle of an in-progress load. - // - [Enabled] A network connection could be established during retry. - .networkConnectionLost, - - // [File System] A resource couldn’t be read because of insufficient permissions. - // - [Disabled] Permissions are unlikely to be granted during retry. - // .noPermissionsToReadFile, - - // [Connectivity] A network resource was requested, but an internet connection has not been established and - // cannot be established automatically. - // - [Enabled] A network connection could be established during retry. - .notConnectedToInternet, - - // [Resource] A redirect was specified by way of server response code, but the server did not accompany this - // code with a redirect URL. - // - [Disabled] The redirect URL is unlikely to be supplied during a retry. - // .redirectToNonExistentLocation, - - // [Client] A body stream is needed but the client did not provide one. - // - [Disabled] The client will be unlikely to supply a body stream during retry. - // .requestBodyStreamExhausted, - - // [Resource] A requested resource couldn’t be retrieved. - // - [Disabled] The resource is unlikely to become available during the retry window. - // .resourceUnavailable, - - // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more - // specifically. - // - [Enabled] The secure connection could be established during a retry given the lack of specificity - // provided by the error. - .secureConnectionFailed, - - // [Security] A server certificate had a date which indicates it has expired, or is not yet valid. - // - [Enabled] The server certificate could become valid within the retry window. - .serverCertificateHasBadDate, - - // [Security] A server certificate was not signed by any root server. - // - [Disabled] The server certificate is unlikely to change during the retry window. - // .serverCertificateHasUnknownRoot, - - // [Security] A server certificate is not yet valid. - // - [Enabled] The server certificate could become valid within the retry window. - .serverCertificateNotYetValid, - - // [Security] A server certificate was signed by a root server that isn’t trusted. - // - [Disabled] The server certificate is unlikely to become trusted within the retry window. - // .serverCertificateUntrusted, - - // [Network] An asynchronous operation timed out. - // - [Enabled] The request timed out for an unknown reason and should be retried. - .timedOut - - // [System] The URL Loading System encountered an error that it can’t interpret. - // - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry. - // .unknown, - - // [Resource] A properly formed URL couldn’t be handled by the framework. - // - [Disabled] The URL is unlikely to change during a retry. - // .unsupportedURL, - - // [Client] Authentication is required to access a resource. - // - [Disabled] The user authentication is unlikely to be provided by retrying. - // .userAuthenticationRequired, - - // [Client] An asynchronous request for authentication has been canceled by the user. - // - [Disabled] The user cancelled authentication and explicitly took action to not retry. - // .userCancelledAuthentication, - - // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection - // gracefully without sending any data. - // - [Disabled] The server is unlikely to provide data during the retry window. - // .zeroByteResource, - ] - - /// The total number of times the request is allowed to be retried. - public let retryLimit: UInt - - /// The base of the exponential backoff policy (should always be greater than or equal to 2). - public let exponentialBackoffBase: UInt - - /// The scale of the exponential backoff. - public let exponentialBackoffScale: Double - - /// The HTTP methods that are allowed to be retried. - public let retryableHTTPMethods: Set - - /// The HTTP status codes that are automatically retried by the policy. - public let retryableHTTPStatusCodes: Set - - /// The URL error codes that are automatically retried by the policy. - public let retryableURLErrorCodes: Set - - /// Creates a `RetryPolicy` from the specified parameters. - /// - /// - Parameters: - /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. - /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. - /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. - /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. - /// `RetryPolicy.defaultRetryableHTTPMethods` by default. - /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. - /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. - /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. - /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. - public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, - exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, - exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, - retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, - retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, - retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) { - precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.") - - self.retryLimit = retryLimit - self.exponentialBackoffBase = exponentialBackoffBase - self.exponentialBackoffScale = exponentialBackoffScale - self.retryableHTTPMethods = retryableHTTPMethods - self.retryableHTTPStatusCodes = retryableHTTPStatusCodes - self.retryableURLErrorCodes = retryableURLErrorCodes - } - - open func retry(_ request: Request, - for session: Session, - dueTo error: Error, - completion: @escaping (RetryResult) -> Void) { - if request.retryCount < retryLimit, shouldRetry(request: request, dueTo: error) { - completion(.retryWithDelay(pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale)) - } else { - completion(.doNotRetry) - } - } - - /// Determines whether or not to retry the provided `Request`. - /// - /// - Parameters: - /// - request: `Request` that failed due to the provided `Error`. - /// - error: `Error` encountered while executing the `Request`. - /// - /// - Returns: `Bool` determining whether or not to retry the `Request`. - open func shouldRetry(request: Request, dueTo error: Error) -> Bool { - guard let httpMethod = request.request?.method, retryableHTTPMethods.contains(httpMethod) else { return false } - - if let statusCode = request.response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) { - return true - } else { - let errorCode = (error as? URLError)?.code - let afErrorCode = (error.asAFError?.underlyingError as? URLError)?.code - - guard let code = errorCode ?? afErrorCode else { return false } - - return retryableURLErrorCodes.contains(code) - } - } -} - -extension RequestInterceptor where Self == RetryPolicy { - /// Provides a default `RetryPolicy` instance. - public static var retryPolicy: RetryPolicy { RetryPolicy() } - - /// Creates an `RetryPolicy` from the specified parameters. - /// - /// - Parameters: - /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. - /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. - /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. - /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. - /// `RetryPolicy.defaultRetryableHTTPMethods` by default. - /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. - /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. - /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. - /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. - /// - /// - Returns: The `RetryPolicy` - public static func retryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, - exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, - exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, - retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, - retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, - retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) -> RetryPolicy { - RetryPolicy(retryLimit: retryLimit, - exponentialBackoffBase: exponentialBackoffBase, - exponentialBackoffScale: exponentialBackoffScale, - retryableHTTPMethods: retryableHTTPMethods, - retryableHTTPStatusCodes: retryableHTTPStatusCodes, - retryableURLErrorCodes: retryableURLErrorCodes) - } -} - -// MARK: - - -/// A retry policy that automatically retries idempotent requests for network connection lost errors. For more -/// information about retrying network connection lost errors, please refer to Apple's -/// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html). -open class ConnectionLostRetryPolicy: RetryPolicy { - /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. - /// - /// - Parameters: - /// - retryLimit: The total number of times the request is allowed to be retried. - /// `RetryPolicy.defaultRetryLimit` by default. - /// - exponentialBackoffBase: The base of the exponential backoff policy. - /// `RetryPolicy.defaultExponentialBackoffBase` by default. - /// - exponentialBackoffScale: The scale of the exponential backoff. - /// `RetryPolicy.defaultExponentialBackoffScale` by default. - /// - retryableHTTPMethods: The idempotent http methods to retry. - /// `RetryPolicy.defaultRetryableHTTPMethods` by default. - public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, - exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, - exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, - retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) { - super.init(retryLimit: retryLimit, - exponentialBackoffBase: exponentialBackoffBase, - exponentialBackoffScale: exponentialBackoffScale, - retryableHTTPMethods: retryableHTTPMethods, - retryableHTTPStatusCodes: [], - retryableURLErrorCodes: [.networkConnectionLost]) - } -} - -extension RequestInterceptor where Self == ConnectionLostRetryPolicy { - /// Provides a default `ConnectionLostRetryPolicy` instance. - public static var connectionLostRetryPolicy: ConnectionLostRetryPolicy { ConnectionLostRetryPolicy() } - - /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. - /// - /// - Parameters: - /// - retryLimit: The total number of times the request is allowed to be retried. - /// `RetryPolicy.defaultRetryLimit` by default. - /// - exponentialBackoffBase: The base of the exponential backoff policy. - /// `RetryPolicy.defaultExponentialBackoffBase` by default. - /// - exponentialBackoffScale: The scale of the exponential backoff. - /// `RetryPolicy.defaultExponentialBackoffScale` by default. - /// - retryableHTTPMethods: The idempotent http methods to retry. - /// - /// - Returns: The `ConnectionLostRetryPolicy`. - public static func connectionLostRetryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, - exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, - exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, - retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) -> ConnectionLostRetryPolicy { - ConnectionLostRetryPolicy(retryLimit: retryLimit, - exponentialBackoffBase: exponentialBackoffBase, - exponentialBackoffScale: exponentialBackoffScale, - retryableHTTPMethods: retryableHTTPMethods) - } -} diff --git a/Pods/Alamofire/Source/ServerTrustEvaluation.swift b/Pods/Alamofire/Source/ServerTrustEvaluation.swift deleted file mode 100644 index e490ab4..0000000 --- a/Pods/Alamofire/Source/ServerTrustEvaluation.swift +++ /dev/null @@ -1,772 +0,0 @@ -// -// ServerTrustEvaluation.swift -// -// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts. -open class ServerTrustManager { - /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default. - public let allHostsMustBeEvaluated: Bool - - /// The dictionary of policies mapped to a particular host. - public let evaluators: [String: ServerTrustEvaluating] - - /// Initializes the `ServerTrustManager` instance with the given evaluators. - /// - /// Since different servers and web services can have different leaf certificates, intermediate and even root - /// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This - /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key - /// pinning for host3 and disabling evaluation for host4. - /// - /// - Parameters: - /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true` - /// by default. - /// - evaluators: A dictionary of evaluators mapped to hosts. - public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) { - self.allHostsMustBeEvaluated = allHostsMustBeEvaluated - self.evaluators = evaluators - } - - #if canImport(Security) - /// Returns the `ServerTrustEvaluating` value for the given host, if one is set. - /// - /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override - /// this method and implement more complex mapping implementations such as wildcards. - /// - /// - Parameter host: The host to use when searching for a matching policy. - /// - /// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise. - /// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching - /// evaluators are found. - open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? { - guard let evaluator = evaluators[host] else { - if allHostsMustBeEvaluated { - throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host)) - } - - return nil - } - - return evaluator - } - #endif -} - -/// A protocol describing the API used to evaluate server trusts. -public protocol ServerTrustEvaluating { - #if !canImport(Security) - // Implement this once other platforms have API for evaluating server trusts. - #else - /// Evaluates the given `SecTrust` value for the given `host`. - /// - /// - Parameters: - /// - trust: The `SecTrust` value to evaluate. - /// - host: The host for which to evaluate the `SecTrust` value. - /// - /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`. - func evaluate(_ trust: SecTrust, forHost host: String) throws - #endif -} - -// MARK: - Server Trust Evaluators - -#if canImport(Security) -/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the -/// host provided by the challenge. Applications are encouraged to always validate the host in production environments -/// to guarantee the validity of the server's certificate chain. -public final class DefaultTrustEvaluator: ServerTrustEvaluating { - private let validateHost: Bool - - /// Creates a `DefaultTrustEvaluator`. - /// - /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default. - public init(validateHost: Bool = true) { - self.validateHost = validateHost - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - if validateHost { - try trust.af.performValidation(forHost: host) - } - - try trust.af.performDefaultValidation(forHost: host) - } -} - -/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate -/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. -/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS -/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production -/// environments to guarantee the validity of the server's certificate chain. -public final class RevocationTrustEvaluator: ServerTrustEvaluating { - /// Represents the options to be use when evaluating the status of a certificate. - /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants). - public struct Options: OptionSet { - /// Perform revocation checking using the CRL (Certification Revocation List) method. - public static let crl = Options(rawValue: kSecRevocationCRLMethod) - /// Consult only locally cached replies; do not use network access. - public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled) - /// Perform revocation checking using OCSP (Online Certificate Status Protocol). - public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod) - /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred. - public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL) - /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a - /// "best attempt" basis, where failure to reach the server is not considered fatal. - public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse) - /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the - /// certificate and the value of `preferCRL`. - public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod) - - /// The raw value of the option. - public let rawValue: CFOptionFlags - - /// Creates an `Options` value with the given `CFOptionFlags`. - /// - /// - Parameter rawValue: The `CFOptionFlags` value to initialize with. - public init(rawValue: CFOptionFlags) { - self.rawValue = rawValue - } - } - - private let performDefaultValidation: Bool - private let validateHost: Bool - private let options: Options - - /// Creates a `RevocationTrustEvaluator` using the provided parameters. - /// - /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use - /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. - /// - /// - Parameters: - /// - performDefaultValidation: Determines whether default validation should be performed in addition to - /// evaluating the pinned certificates. `true` by default. - /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to - /// performing the default evaluation, even if `performDefaultValidation` is `false`. - /// `true` by default. - /// - options: The `Options` to use to check the revocation status of the certificate. `.any` by - /// default. - public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) { - self.performDefaultValidation = performDefaultValidation - self.validateHost = validateHost - self.options = options - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - if performDefaultValidation { - try trust.af.performDefaultValidation(forHost: host) - } - - if validateHost { - try trust.af.performValidation(forHost: host) - } - - #if swift(>=5.9) - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { - try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) - } else { - try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in - AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) - } - } - #else - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) - } else { - try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in - AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) - } - } - #endif - } -} - -extension ServerTrustEvaluating where Self == RevocationTrustEvaluator { - /// Provides a default `RevocationTrustEvaluator` instance. - public static var revocationChecking: RevocationTrustEvaluator { RevocationTrustEvaluator() } - - /// Creates a `RevocationTrustEvaluator` using the provided parameters. - /// - /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use - /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. - /// - /// - Parameters: - /// - performDefaultValidation: Determines whether default validation should be performed in addition to - /// evaluating the pinned certificates. `true` by default. - /// - validateHost: Determines whether or not the evaluator should validate the host, in addition - /// to performing the default evaluation, even if `performDefaultValidation` is - /// `false`. `true` by default. - /// - options: The `Options` to use to check the revocation status of the certificate. `.any` - /// by default. - /// - Returns: The `RevocationTrustEvaluator`. - public static func revocationChecking(performDefaultValidation: Bool = true, - validateHost: Bool = true, - options: RevocationTrustEvaluator.Options = .any) -> RevocationTrustEvaluator { - RevocationTrustEvaluator(performDefaultValidation: performDefaultValidation, - validateHost: validateHost, - options: options) - } -} - -/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned -/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate -/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -/// Applications are encouraged to always validate the host and require a valid certificate chain in production -/// environments. -public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating { - private let certificates: [SecCertificate] - private let acceptSelfSignedCertificates: Bool - private let performDefaultValidation: Bool - private let validateHost: Bool - - /// Creates a `PinnedCertificatesTrustEvaluator` from the provided parameters. - /// - /// - Parameters: - /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` - /// certificates in `Bundle.main` by default. - /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing - /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE - /// FALSE IN PRODUCTION! - /// - performDefaultValidation: Determines whether default validation should be performed in addition to - /// evaluating the pinned certificates. `true` by default. - /// - validateHost: Determines whether or not the evaluator should validate the host, in addition - /// to performing the default evaluation, even if `performDefaultValidation` is - /// `false`. `true` by default. - public init(certificates: [SecCertificate] = Bundle.main.af.certificates, - acceptSelfSignedCertificates: Bool = false, - performDefaultValidation: Bool = true, - validateHost: Bool = true) { - self.certificates = certificates - self.acceptSelfSignedCertificates = acceptSelfSignedCertificates - self.performDefaultValidation = performDefaultValidation - self.validateHost = validateHost - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - guard !certificates.isEmpty else { - throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) - } - - if acceptSelfSignedCertificates { - try trust.af.setAnchorCertificates(certificates) - } - - if performDefaultValidation { - try trust.af.performDefaultValidation(forHost: host) - } - - if validateHost { - try trust.af.performValidation(forHost: host) - } - - let serverCertificatesData = Set(trust.af.certificateData) - let pinnedCertificatesData = Set(certificates.af.data) - let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData) - if !pinnedCertificatesInServerData { - throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host, - trust: trust, - pinnedCertificates: certificates, - serverCertificates: trust.af.certificates)) - } - } -} - -extension ServerTrustEvaluating where Self == PinnedCertificatesTrustEvaluator { - /// Provides a default `PinnedCertificatesTrustEvaluator` instance. - public static var pinnedCertificates: PinnedCertificatesTrustEvaluator { PinnedCertificatesTrustEvaluator() } - - /// Creates a `PinnedCertificatesTrustEvaluator` using the provided parameters. - /// - /// - Parameters: - /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` - /// certificates in `Bundle.main` by default. - /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing - /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE - /// FALSE IN PRODUCTION! - /// - performDefaultValidation: Determines whether default validation should be performed in addition to - /// evaluating the pinned certificates. `true` by default. - /// - validateHost: Determines whether or not the evaluator should validate the host, in addition - /// to performing the default evaluation, even if `performDefaultValidation` is - /// `false`. `true` by default. - public static func pinnedCertificates(certificates: [SecCertificate] = Bundle.main.af.certificates, - acceptSelfSignedCertificates: Bool = false, - performDefaultValidation: Bool = true, - validateHost: Bool = true) -> PinnedCertificatesTrustEvaluator { - PinnedCertificatesTrustEvaluator(certificates: certificates, - acceptSelfSignedCertificates: acceptSelfSignedCertificates, - performDefaultValidation: performDefaultValidation, - validateHost: validateHost) - } -} - -/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned -/// public keys match one of the server certificate public keys. By validating both the certificate chain and host, -/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. -/// Applications are encouraged to always validate the host and require a valid certificate chain in production -/// environments. -public final class PublicKeysTrustEvaluator: ServerTrustEvaluating { - private let keys: [SecKey] - private let performDefaultValidation: Bool - private let validateHost: Bool - - /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. - /// - /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use - /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. - /// - /// - Parameters: - /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all - /// certificates included in the main bundle. - /// - performDefaultValidation: Determines whether default validation should be performed in addition to - /// evaluating the pinned certificates. `true` by default. - /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to - /// performing the default evaluation, even if `performDefaultValidation` is `false`. - /// `true` by default. - public init(keys: [SecKey] = Bundle.main.af.publicKeys, - performDefaultValidation: Bool = true, - validateHost: Bool = true) { - self.keys = keys - self.performDefaultValidation = performDefaultValidation - self.validateHost = validateHost - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - guard !keys.isEmpty else { - throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound) - } - - if performDefaultValidation { - try trust.af.performDefaultValidation(forHost: host) - } - - if validateHost { - try trust.af.performValidation(forHost: host) - } - - let pinnedKeysInServerKeys: Bool = { - for serverPublicKey in trust.af.publicKeys { - if keys.contains(serverPublicKey) { - return true - } - } - return false - }() - - if !pinnedKeysInServerKeys { - throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host, - trust: trust, - pinnedKeys: keys, - serverKeys: trust.af.publicKeys)) - } - } -} - -extension ServerTrustEvaluating where Self == PublicKeysTrustEvaluator { - /// Provides a default `PublicKeysTrustEvaluator` instance. - public static var publicKeys: PublicKeysTrustEvaluator { PublicKeysTrustEvaluator() } - - /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. - /// - /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use - /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. - /// - /// - Parameters: - /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all - /// certificates included in the main bundle. - /// - performDefaultValidation: Determines whether default validation should be performed in addition to - /// evaluating the pinned certificates. `true` by default. - /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to - /// performing the default evaluation, even if `performDefaultValidation` is `false`. - /// `true` by default. - public static func publicKeys(keys: [SecKey] = Bundle.main.af.publicKeys, - performDefaultValidation: Bool = true, - validateHost: Bool = true) -> PublicKeysTrustEvaluator { - PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: performDefaultValidation, validateHost: validateHost) - } -} - -/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the -/// evaluators consider it valid. -public final class CompositeTrustEvaluator: ServerTrustEvaluating { - private let evaluators: [ServerTrustEvaluating] - - /// Creates a `CompositeTrustEvaluator` from the provided evaluators. - /// - /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. - public init(evaluators: [ServerTrustEvaluating]) { - self.evaluators = evaluators - } - - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - try evaluators.evaluate(trust, forHost: host) - } -} - -extension ServerTrustEvaluating where Self == CompositeTrustEvaluator { - /// Creates a `CompositeTrustEvaluator` from the provided evaluators. - /// - /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. - public static func composite(evaluators: [ServerTrustEvaluating]) -> CompositeTrustEvaluator { - CompositeTrustEvaluator(evaluators: evaluators) - } -} - -/// Disables all evaluation which in turn will always consider any server trust as valid. -/// -/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test -/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). -/// -/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** -@available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.") -public typealias DisabledEvaluator = DisabledTrustEvaluator - -/// Disables all evaluation which in turn will always consider any server trust as valid. -/// -/// -/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test -/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). -/// -/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** -public final class DisabledTrustEvaluator: ServerTrustEvaluating { - /// Creates an instance. - public init() {} - - public func evaluate(_ trust: SecTrust, forHost host: String) throws {} -} - -// MARK: - Extensions - -extension Array where Element == ServerTrustEvaluating { - #if os(Linux) || os(Windows) || os(Android) - // Add this same convenience method for Linux/Windows. - #else - /// Evaluates the given `SecTrust` value for the given `host`. - /// - /// - Parameters: - /// - trust: The `SecTrust` value to evaluate. - /// - host: The host for which to evaluate the `SecTrust` value. - /// - /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`. - public func evaluate(_ trust: SecTrust, forHost host: String) throws { - for evaluator in self { - try evaluator.evaluate(trust, forHost: host) - } - } - #endif -} - -extension Bundle: AlamofireExtended {} -extension AlamofireExtension where ExtendedType: Bundle { - /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle. - public var certificates: [SecCertificate] { - paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in - guard - let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, - let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil } - - return certificate - } - } - - /// Returns all public keys for the valid certificates in the bundle. - public var publicKeys: [SecKey] { - certificates.af.publicKeys - } - - /// Returns all pathnames for the resources identified by the provided file extensions. - /// - /// - Parameter types: The filename extensions locate. - /// - /// - Returns: All pathnames for the given filename extensions. - public func paths(forResourcesOfTypes types: [String]) -> [String] { - Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) })) - } -} - -extension SecTrust: AlamofireExtended {} -extension AlamofireExtension where ExtendedType == SecTrust { - /// Evaluates `self` after applying the `SecPolicy` value provided. - /// - /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation. - /// - /// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation. - @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) - public func evaluate(afterApplying policy: SecPolicy) throws { - try apply(policy: policy).af.evaluate() - } - - /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed. - /// - /// - Parameters: - /// - policy: The `SecPolicy` used to evaluate `self`. - /// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`. - /// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails. - @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") - @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)") - @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") - @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)") - public func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { - try apply(policy: policy).af.validate(errorProducer: errorProducer) - } - - /// Applies a `SecPolicy` to `self`, throwing if it fails. - /// - /// - Parameter policy: The `SecPolicy`. - /// - /// - Returns: `self`, with the policy applied. - /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason. - public func apply(policy: SecPolicy) throws -> SecTrust { - let status = SecTrustSetPolicies(type, policy) - - guard status.af.isSuccess else { - throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type, - policy: policy, - status: status)) - } - - return type - } - - /// Evaluate `self`, throwing an `Error` if evaluation fails. - /// - /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from - /// the underlying evaluation. - @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) - public func evaluate() throws { - var error: CFError? - let evaluationSucceeded = SecTrustEvaluateWithError(type, &error) - - if !evaluationSucceeded { - throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error)) - } - } - - /// Validate `self`, passing any failure values through `errorProducer`. - /// - /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an - /// `Error`. - /// - Throws: The `Error` produced by the `errorProducer` closure. - @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()") - @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()") - @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()") - @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()") - public func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { - var result = SecTrustResultType.invalid - let status = SecTrustEvaluate(type, &result) - - guard status.af.isSuccess && result.af.isSuccess else { - throw errorProducer(status, result) - } - } - - /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain. - /// - /// - Parameter certificates: The `SecCertificate`s to add to the chain. - /// - Throws: Any error produced when applying the new certificate chain. - public func setAnchorCertificates(_ certificates: [SecCertificate]) throws { - // Add additional anchor certificates. - let status = SecTrustSetAnchorCertificates(type, certificates as CFArray) - guard status.af.isSuccess else { - throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status, - certificates: certificates)) - } - - // Trust only the set anchor certs. - let onlyStatus = SecTrustSetAnchorCertificatesOnly(type, true) - guard onlyStatus.af.isSuccess else { - throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: onlyStatus, - certificates: certificates)) - } - } - - /// The public keys contained in `self`. - public var publicKeys: [SecKey] { - certificates.af.publicKeys - } - - /// The `SecCertificate`s contained in `self`. - public var certificates: [SecCertificate] { - #if swift(>=5.9) - if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, visionOS 1, *) { - return (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? [] - } else { - return (0..=5.5.1) // Xcode 13.1 / 2021 SDKs. - if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { - return (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? [] - } else { - return (0..=5.9) - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { - try evaluate(afterApplying: SecPolicy.af.default) - } else { - try validate(policy: SecPolicy.af.default) { status, result in - AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result))) - } - } - #else - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - try evaluate(afterApplying: SecPolicy.af.default) - } else { - try validate(policy: SecPolicy.af.default) { status, result in - AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result))) - } - } - #endif - } - - /// Validates `self` after applying `SecPolicy.af.hostname(host)`, which performs the default validation as well as - /// hostname validation. - /// - /// - Parameter host: The hostname to use in the validation. - /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason. - public func performValidation(forHost host: String) throws { - #if swift(>=5.9) - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { - try evaluate(afterApplying: SecPolicy.af.hostname(host)) - } else { - try validate(policy: SecPolicy.af.hostname(host)) { status, result in - AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result))) - } - } - #else - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { - try evaluate(afterApplying: SecPolicy.af.hostname(host)) - } else { - try validate(policy: SecPolicy.af.hostname(host)) { status, result in - AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result))) - } - } - #endif - } -} - -extension SecPolicy: AlamofireExtended {} -extension AlamofireExtension where ExtendedType == SecPolicy { - /// Creates a `SecPolicy` instance which will validate server certificates but not require a host name match. - public static let `default` = SecPolicyCreateSSL(true, nil) - - /// Creates a `SecPolicy` instance which will validate server certificates and much match the provided hostname. - /// - /// - Parameter hostname: The hostname to validate against. - /// - /// - Returns: The `SecPolicy`. - public static func hostname(_ hostname: String) -> SecPolicy { - SecPolicyCreateSSL(true, hostname as CFString) - } - - /// Creates a `SecPolicy` which checks the revocation of certificates. - /// - /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation. - /// - /// - Returns: The `SecPolicy`. - /// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed` - /// if the policy cannot be created. - public static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy { - guard let policy = SecPolicyCreateRevocation(options.rawValue) else { - throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed) - } - - return policy - } -} - -extension Array: AlamofireExtended {} -extension AlamofireExtension where ExtendedType == [SecCertificate] { - /// All `Data` values for the contained `SecCertificate`s. - public var data: [Data] { - type.map { SecCertificateCopyData($0) as Data } - } - - /// All public `SecKey` values for the contained `SecCertificate`s. - public var publicKeys: [SecKey] { - type.compactMap(\.af.publicKey) - } -} - -extension SecCertificate: AlamofireExtended {} -extension AlamofireExtension where ExtendedType == SecCertificate { - /// The public key for `self`, if it can be extracted. - /// - /// - Note: On 2020 OSes and newer, only RSA and ECDSA keys are supported. - /// - public var publicKey: SecKey? { - let policy = SecPolicyCreateBasicX509() - var trust: SecTrust? - let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust) - - guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil } - - #if swift(>=5.9) - if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, visionOS 1, *) { - return SecTrustCopyKey(createdTrust) - } else { - return SecTrustCopyPublicKey(createdTrust) - } - #else - if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) { - return SecTrustCopyKey(createdTrust) - } else { - return SecTrustCopyPublicKey(createdTrust) - } - #endif - } -} - -extension OSStatus: AlamofireExtended {} -extension AlamofireExtension where ExtendedType == OSStatus { - /// Returns whether `self` is `errSecSuccess`. - public var isSuccess: Bool { type == errSecSuccess } -} - -extension SecTrustResultType: AlamofireExtended {} -extension AlamofireExtension where ExtendedType == SecTrustResultType { - /// Returns whether `self is `.unspecified` or `.proceed`. - public var isSuccess: Bool { - type == .unspecified || type == .proceed - } -} -#endif diff --git a/Pods/Alamofire/Source/Session.swift b/Pods/Alamofire/Source/Session.swift deleted file mode 100644 index 4232f85..0000000 --- a/Pods/Alamofire/Source/Session.swift +++ /dev/null @@ -1,1264 +0,0 @@ -// -// Session.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common -/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response -/// cache handling. -open class Session { - /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified. - public static let `default` = Session() - - /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's - /// `delegate` handles `URLSessionDelegate` callbacks. - /// - /// - Note: This instance should **NOT** be used to interact with the underlying `URLSessionTask`s. Doing so will - /// break internal Alamofire logic that tracks those tasks. - /// - public let session: URLSession - /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction. - public let delegate: SessionDelegate - /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue. - public let rootQueue: DispatchQueue - /// Value determining whether this instance automatically calls `resume()` on all created `Request`s. - public let startRequestsImmediately: Bool - /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its - /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile - /// and test before introducing an additional queue. - public let requestQueue: DispatchQueue - /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this - /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined - /// to be a bottleneck. Always profile and test before introducing an additional queue. - public let serializationQueue: DispatchQueue - /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a - /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value. - public let interceptor: RequestInterceptor? - /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning. - public let serverTrustManager: ServerTrustManager? - /// `RedirectHandler` instance used to provide customization for request redirection. - public let redirectHandler: RedirectHandler? - /// `CachedResponseHandler` instance used to provide customization of cached response handling. - public let cachedResponseHandler: CachedResponseHandler? - /// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s. - public let eventMonitor: CompositeEventMonitor - /// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default. - public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()] - - /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them. - var requestTaskMap = RequestTaskMap() - /// `Set` of currently active `Request`s. - var activeRequests: Set = [] - /// Completion events awaiting `URLSessionTaskMetrics`. - var waitingCompletions: [URLSessionTask: () -> Void] = [:] - - /// Creates a `Session` from a `URLSession` and other parameters. - /// - /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and - /// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer. - /// - /// - Parameters: - /// - session: Underlying `URLSession` for this instance. - /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` - /// interaction. - /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a - /// serial queue. - /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` - /// by default. If set to `false`, all `Request`s created must have `.resume()` called. - /// on them for them to start. - /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue - /// will use the `rootQueue` as its `target`. A separate queue can be used if it's - /// determined request creation is a bottleneck, but that should only be done after - /// careful testing and profiling. `nil` by default. - /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this - /// queue will use the `rootQueue` as its `target`. A separate queue can be used if - /// it's determined response serialization is a bottleneck, but that should only be - /// done after careful testing and profiling. `nil` by default. - /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` - /// by default. - /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` - /// by default. - /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by - /// default. - /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. - /// `nil` by default. - /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a - /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. - public init(session: URLSession, - delegate: SessionDelegate, - rootQueue: DispatchQueue, - startRequestsImmediately: Bool = true, - requestQueue: DispatchQueue? = nil, - serializationQueue: DispatchQueue? = nil, - interceptor: RequestInterceptor? = nil, - serverTrustManager: ServerTrustManager? = nil, - redirectHandler: RedirectHandler? = nil, - cachedResponseHandler: CachedResponseHandler? = nil, - eventMonitors: [EventMonitor] = []) { - precondition(session.configuration.identifier == nil, - "Alamofire does not support background URLSessionConfigurations.") - precondition(session.delegateQueue.underlyingQueue === rootQueue, - "Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.") - - self.session = session - self.delegate = delegate - self.rootQueue = rootQueue - self.startRequestsImmediately = startRequestsImmediately - self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue) - self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue) - self.interceptor = interceptor - self.serverTrustManager = serverTrustManager - self.redirectHandler = redirectHandler - self.cachedResponseHandler = cachedResponseHandler - eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors) - delegate.eventMonitor = eventMonitor - delegate.stateProvider = self - } - - /// Creates a `Session` from a `URLSessionConfiguration`. - /// - /// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its - /// `delegateQueue`, and is the recommended initializer for most uses. - /// - /// - Parameters: - /// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes - /// to this value after being passed to this initializer will have no effect. - /// `URLSessionConfiguration.af.default` by default. - /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` - /// interaction. `SessionDelegate()` by default. - /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a - /// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default. - /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` - /// by default. If set to `false`, all `Request`s created must have `.resume()` called. - /// on them for them to start. - /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue - /// will use the `rootQueue` as its `target`. A separate queue can be used if it's - /// determined request creation is a bottleneck, but that should only be done after - /// careful testing and profiling. `nil` by default. - /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this - /// queue will use the `rootQueue` as its `target`. A separate queue can be used if - /// it's determined response serialization is a bottleneck, but that should only be - /// done after careful testing and profiling. `nil` by default. - /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` - /// by default. - /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` - /// by default. - /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by - /// default. - /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. - /// `nil` by default. - /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a - /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. - public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default, - delegate: SessionDelegate = SessionDelegate(), - rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"), - startRequestsImmediately: Bool = true, - requestQueue: DispatchQueue? = nil, - serializationQueue: DispatchQueue? = nil, - interceptor: RequestInterceptor? = nil, - serverTrustManager: ServerTrustManager? = nil, - redirectHandler: RedirectHandler? = nil, - cachedResponseHandler: CachedResponseHandler? = nil, - eventMonitors: [EventMonitor] = []) { - precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.") - - // Retarget the incoming rootQueue for safety, unless it's the main queue, which we know is safe. - let serialRootQueue = (rootQueue === DispatchQueue.main) ? rootQueue : DispatchQueue(label: rootQueue.label, - target: rootQueue) - let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: serialRootQueue, name: "\(serialRootQueue.label).sessionDelegate") - let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue) - - self.init(session: session, - delegate: delegate, - rootQueue: serialRootQueue, - startRequestsImmediately: startRequestsImmediately, - requestQueue: requestQueue, - serializationQueue: serializationQueue, - interceptor: interceptor, - serverTrustManager: serverTrustManager, - redirectHandler: redirectHandler, - cachedResponseHandler: cachedResponseHandler, - eventMonitors: eventMonitors) - } - - deinit { - finishRequestsForDeinit() - session.invalidateAndCancel() - } - - // MARK: - All Requests API - - /// Perform an action on all active `Request`s. - /// - /// - Note: The provided `action` closure is performed asynchronously, meaning that some `Request`s may complete and - /// be unavailable by time it runs. Additionally, this action is performed on the instances's `rootQueue`, - /// so care should be taken that actions are fast. Once the work on the `Request`s is complete, any - /// additional work should be performed on another queue. - /// - /// - Parameters: - /// - action: Closure to perform with all `Request`s. - public func withAllRequests(perform action: @escaping (Set) -> Void) { - rootQueue.async { - action(self.activeRequests) - } - } - - /// Cancel all active `Request`s, optionally calling a completion handler when complete. - /// - /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled - /// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to - /// completion when cancelled. - /// - /// - Parameters: - /// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default. - /// - completion: Closure to be called when all `Request`s have been cancelled. - public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) { - withAllRequests { requests in - requests.forEach { $0.cancel() } - queue.async { - completion?() - } - } - } - - // MARK: - DataRequest - - /// Closure which provides a `URLRequest` for mutation. - public typealias RequestModifier = (inout URLRequest) throws -> Void - - struct RequestConvertible: URLRequestConvertible { - let url: URLConvertible - let method: HTTPMethod - let parameters: Parameters? - let encoding: ParameterEncoding - let headers: HTTPHeaders? - let requestModifier: RequestModifier? - - func asURLRequest() throws -> URLRequest { - var request = try URLRequest(url: url, method: method, headers: headers) - try requestModifier?(&request) - - return try encoding.encode(request, with: parameters) - } - } - - /// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by - /// default. - /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. - /// `URLEncoding.default` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided - /// parameters. `nil` by default. - /// - /// - Returns: The created `DataRequest`. - open func request(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - requestModifier: RequestModifier? = nil) -> DataRequest { - let convertible = RequestConvertible(url: convertible, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers, - requestModifier: requestModifier) - - return request(convertible, interceptor: interceptor) - } - - struct RequestEncodableConvertible: URLRequestConvertible { - let url: URLConvertible - let method: HTTPMethod - let parameters: Parameters? - let encoder: ParameterEncoder - let headers: HTTPHeaders? - let requestModifier: RequestModifier? - - func asURLRequest() throws -> URLRequest { - var request = try URLRequest(url: url, method: method, headers: headers) - try requestModifier?(&request) - - return try parameters.map { try encoder.encode($0, into: request) } ?? request - } - } - - /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. - /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. - /// `URLEncodedFormParameterEncoder.default` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from - /// the provided parameters. `nil` by default. - /// - /// - Returns: The created `DataRequest`. - open func request(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - requestModifier: RequestModifier? = nil) -> DataRequest { - let convertible = RequestEncodableConvertible(url: convertible, - method: method, - parameters: parameters, - encoder: encoder, - headers: headers, - requestModifier: requestModifier) - - return request(convertible, interceptor: interceptor) - } - - /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - /// - Returns: The created `DataRequest`. - open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { - let request = DataRequest(convertible: convertible, - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: self) - - perform(request) - - return request - } - - // MARK: - DataStreamRequest - - /// Creates a `DataStreamRequest` from the passed components, `Encodable` parameters, and `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. - /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the - /// `URLRequest`. - /// `URLEncodedFormParameterEncoder.default` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` - /// is thrown while serializing stream `Data`. `false` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` - /// by default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from - /// the provided parameters. `nil` by default. - /// - /// - Returns: The created `DataStream` request. - open func streamRequest(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, - headers: HTTPHeaders? = nil, - automaticallyCancelOnStreamError: Bool = false, - interceptor: RequestInterceptor? = nil, - requestModifier: RequestModifier? = nil) -> DataStreamRequest { - let convertible = RequestEncodableConvertible(url: convertible, - method: method, - parameters: parameters, - encoder: encoder, - headers: headers, - requestModifier: requestModifier) - - return streamRequest(convertible, - automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, - interceptor: interceptor) - } - - /// Creates a `DataStreamRequest` from the passed components and `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` - /// is thrown while serializing stream `Data`. `false` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` - /// by default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from - /// the provided parameters. `nil` by default. - /// - /// - Returns: The created `DataStream` request. - open func streamRequest(_ convertible: URLConvertible, - method: HTTPMethod = .get, - headers: HTTPHeaders? = nil, - automaticallyCancelOnStreamError: Bool = false, - interceptor: RequestInterceptor? = nil, - requestModifier: RequestModifier? = nil) -> DataStreamRequest { - let convertible = RequestEncodableConvertible(url: convertible, - method: method, - parameters: Empty?.none, - encoder: URLEncodedFormParameterEncoder.default, - headers: headers, - requestModifier: requestModifier) - - return streamRequest(convertible, - automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, - interceptor: interceptor) - } - - /// Creates a `DataStreamRequest` from the passed `URLRequestConvertible` value and `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` - /// is thrown while serializing stream `Data`. `false` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` - /// by default. - /// - /// - Returns: The created `DataStreamRequest`. - open func streamRequest(_ convertible: URLRequestConvertible, - automaticallyCancelOnStreamError: Bool = false, - interceptor: RequestInterceptor? = nil) -> DataStreamRequest { - let request = DataStreamRequest(convertible: convertible, - automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: self) - - perform(request) - - return request - } - - // MARK: - DownloadRequest - - /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and - /// `Destination`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by - /// default. - /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. - /// Defaults to `URLEncoding.default`. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided - /// parameters. `nil` by default. - /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file - /// should be moved. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - open func download(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - requestModifier: RequestModifier? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - let convertible = RequestConvertible(url: convertible, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers, - requestModifier: requestModifier) - - return download(convertible, interceptor: interceptor, to: destination) - } - - /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and - /// a `RequestInterceptor`. - /// - /// - Parameters: - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. - /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default. - /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. - /// Defaults to `URLEncodedFormParameterEncoder.default`. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided - /// parameters. `nil` by default. - /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file - /// should be moved. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - open func download(_ convertible: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - requestModifier: RequestModifier? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - let convertible = RequestEncodableConvertible(url: convertible, - method: method, - parameters: parameters, - encoder: encoder, - headers: headers, - requestModifier: requestModifier) - - return download(convertible, interceptor: interceptor, to: destination) - } - - /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`. - /// - /// - Parameters: - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file - /// should be moved. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - open func download(_ convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - let request = DownloadRequest(downloadable: .request(convertible), - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: self, - destination: destination ?? DownloadRequest.defaultDestination) - - perform(request) - - return request - } - - /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as - /// well as a `RequestInterceptor`, and a `Destination`. - /// - /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by - /// Alamofire. The file will not be deleted until the system purges the temporary files. - /// - /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), - /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` - /// generation logic where the data is written incorrectly and will always fail to resume the download. For more - /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462). - /// - /// - Parameters: - /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file - /// should be moved. `nil` by default. - /// - /// - Returns: The created `DownloadRequest`. - open func download(resumingWith data: Data, - interceptor: RequestInterceptor? = nil, - to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { - let request = DownloadRequest(downloadable: .resumeData(data), - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - delegate: self, - destination: destination ?? DownloadRequest.defaultDestination) - - perform(request) - - return request - } - - // MARK: - UploadRequest - - struct ParameterlessRequestConvertible: URLRequestConvertible { - let url: URLConvertible - let method: HTTPMethod - let headers: HTTPHeaders? - let requestModifier: RequestModifier? - - func asURLRequest() throws -> URLRequest { - var request = try URLRequest(url: url, method: method, headers: headers) - try requestModifier?(&request) - - return request - } - } - - struct Upload: UploadConvertible { - let request: URLRequestConvertible - let uploadable: UploadableConvertible - - func createUploadable() throws -> UploadRequest.Uploadable { - try uploadable.createUploadable() - } - - func asURLRequest() throws -> URLRequest { - try request.asURLRequest() - } - } - - // MARK: Data - - /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. - /// - /// - Parameters: - /// - data: The `Data` to upload. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided - /// parameters. `nil` by default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ data: Data, - to convertible: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default, - requestModifier: RequestModifier? = nil) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: convertible, - method: method, - headers: headers, - requestModifier: requestModifier) - - return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`. - /// - /// - Parameters: - /// - data: The `Data` to upload. - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ data: Data, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: File - - /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided - /// components and `RequestInterceptor`. - /// - /// - Parameters: - /// - fileURL: The `URL` of the file to upload. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided - /// parameters. `nil` by default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ fileURL: URL, - to convertible: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default, - requestModifier: RequestModifier? = nil) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: convertible, - method: method, - headers: headers, - requestModifier: requestModifier) - - return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - fileURL: The `URL` of the file to upload. - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ fileURL: URL, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: InputStream - - /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - stream: The `InputStream` that provides the data to upload. - /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided - /// parameters. `nil` by default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ stream: InputStream, - to convertible: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default, - requestModifier: RequestModifier? = nil) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: convertible, - method: method, - headers: headers, - requestModifier: requestModifier) - - return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and - /// `RequestInterceptor`. - /// - /// - Parameters: - /// - stream: The `InputStream` that provides the data to upload. - /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(_ stream: InputStream, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: MultipartFormData - - /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided - /// `URLRequest` components and `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` building closure. - /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is - /// written to disk before being uploaded. `.default` instance by default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the - /// provided parameters. `nil` by default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, - to url: URLConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default, - requestModifier: RequestModifier? = nil) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: url, - method: method, - headers: headers, - requestModifier: requestModifier) - - let formData = MultipartFormData(fileManager: fileManager) - multipartFormData(formData) - - return upload(multipartFormData: formData, - with: convertible, - usingThreshold: encodingMemoryThreshold, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible` - /// value, and a `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` building closure. - /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is - /// written to disk before being uploaded. `.default` instance by default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, - with request: URLRequestConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - let formData = MultipartFormData(fileManager: fileManager) - multipartFormData(formData) - - return upload(multipartFormData: formData, - with: request, - usingThreshold: encodingMemoryThreshold, - interceptor: interceptor, - fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components - /// and `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` instance to upload. - /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. - /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is - /// written to disk before being uploaded. `.default` instance by default. - /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the - /// provided parameters. `nil` by default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(multipartFormData: MultipartFormData, - to url: URLConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default, - requestModifier: RequestModifier? = nil) -> UploadRequest { - let convertible = ParameterlessRequestConvertible(url: url, - method: method, - headers: headers, - requestModifier: requestModifier) - - let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, - request: convertible, - multipartFormData: multipartFormData) - - return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) - } - - /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible` - /// value and `RequestInterceptor`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// - Parameters: - /// - multipartFormData: `MultipartFormData` instance to upload. - /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. - /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or - /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by - /// default. - /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. - /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by - /// default. - /// - /// - Returns: The created `UploadRequest`. - open func upload(multipartFormData: MultipartFormData, - with request: URLRequestConvertible, - usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, - interceptor: RequestInterceptor? = nil, - fileManager: FileManager = .default) -> UploadRequest { - let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, - request: request, - multipartFormData: multipartFormData) - - return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) - } - - // MARK: - Internal API - - // MARK: Uploadable - - func upload(_ uploadable: UploadRequest.Uploadable, - with convertible: URLRequestConvertible, - interceptor: RequestInterceptor?, - fileManager: FileManager) -> UploadRequest { - let uploadable = Upload(request: convertible, uploadable: uploadable) - - return upload(uploadable, interceptor: interceptor, fileManager: fileManager) - } - - func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest { - let request = UploadRequest(convertible: upload, - underlyingQueue: rootQueue, - serializationQueue: serializationQueue, - eventMonitor: eventMonitor, - interceptor: interceptor, - fileManager: fileManager, - delegate: self) - - perform(request) - - return request - } - - // MARK: Perform - - /// Starts performing the provided `Request`. - /// - /// - Parameter request: The `Request` to perform. - func perform(_ request: Request) { - rootQueue.async { - guard !request.isCancelled else { return } - - self.activeRequests.insert(request) - - self.requestQueue.async { - // Leaf types must come first, otherwise they will cast as their superclass. - switch request { - case let r as UploadRequest: self.performUploadRequest(r) // UploadRequest must come before DataRequest due to subtype relationship. - case let r as DataRequest: self.performDataRequest(r) - case let r as DownloadRequest: self.performDownloadRequest(r) - case let r as DataStreamRequest: self.performDataStreamRequest(r) - default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") - } - } - } - } - - func performDataRequest(_ request: DataRequest) { - dispatchPrecondition(condition: .onQueue(requestQueue)) - - performSetupOperations(for: request, convertible: request.convertible) - } - - func performDataStreamRequest(_ request: DataStreamRequest) { - dispatchPrecondition(condition: .onQueue(requestQueue)) - - performSetupOperations(for: request, convertible: request.convertible) - } - - func performUploadRequest(_ request: UploadRequest) { - dispatchPrecondition(condition: .onQueue(requestQueue)) - - performSetupOperations(for: request, convertible: request.convertible) { - do { - let uploadable = try request.upload.createUploadable() - self.rootQueue.async { request.didCreateUploadable(uploadable) } - return true - } catch { - self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) } - return false - } - } - } - - func performDownloadRequest(_ request: DownloadRequest) { - dispatchPrecondition(condition: .onQueue(requestQueue)) - - switch request.downloadable { - case let .request(convertible): - performSetupOperations(for: request, convertible: convertible) - case let .resumeData(resumeData): - rootQueue.async { self.didReceiveResumeData(resumeData, for: request) } - } - } - - func performSetupOperations(for request: Request, - convertible: URLRequestConvertible, - shouldCreateTask: @escaping () -> Bool = { true }) { - dispatchPrecondition(condition: .onQueue(requestQueue)) - - let initialRequest: URLRequest - - do { - initialRequest = try convertible.asURLRequest() - try initialRequest.validate() - } catch { - rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) } - return - } - - rootQueue.async { request.didCreateInitialURLRequest(initialRequest) } - - guard !request.isCancelled else { return } - - guard let adapter = adapter(for: request) else { - guard shouldCreateTask() else { return } - rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) } - return - } - - let adapterState = RequestAdapterState(requestID: request.id, session: self) - - adapter.adapt(initialRequest, using: adapterState) { result in - do { - let adaptedRequest = try result.get() - try adaptedRequest.validate() - - self.rootQueue.async { request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) } - - guard shouldCreateTask() else { return } - - self.rootQueue.async { self.didCreateURLRequest(adaptedRequest, for: request) } - } catch { - self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) } - } - } - } - - // MARK: - Task Handling - - func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) { - dispatchPrecondition(condition: .onQueue(rootQueue)) - - request.didCreateURLRequest(urlRequest) - - guard !request.isCancelled else { return } - - let task = request.task(for: urlRequest, using: session) - requestTaskMap[request] = task - request.didCreateTask(task) - - updateStatesForTask(task, request: request) - } - - func didReceiveResumeData(_ data: Data, for request: DownloadRequest) { - dispatchPrecondition(condition: .onQueue(rootQueue)) - - guard !request.isCancelled else { return } - - let task = request.task(forResumeData: data, using: session) - requestTaskMap[request] = task - request.didCreateTask(task) - - updateStatesForTask(task, request: request) - } - - func updateStatesForTask(_ task: URLSessionTask, request: Request) { - dispatchPrecondition(condition: .onQueue(rootQueue)) - - request.withState { state in - switch state { - case .initialized, .finished: - // Do nothing. - break - case .resumed: - task.resume() - rootQueue.async { request.didResumeTask(task) } - case .suspended: - task.suspend() - rootQueue.async { request.didSuspendTask(task) } - case .cancelled: - // Resume to ensure metrics are gathered. - task.resume() - task.cancel() - rootQueue.async { request.didCancelTask(task) } - } - } - } - - // MARK: - Adapters and Retriers - - func adapter(for request: Request) -> RequestAdapter? { - if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { - return Interceptor(adapters: [requestInterceptor, sessionInterceptor]) - } else { - return request.interceptor ?? interceptor - } - } - - func retrier(for request: Request) -> RequestRetrier? { - if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { - return Interceptor(retriers: [requestInterceptor, sessionInterceptor]) - } else { - return request.interceptor ?? interceptor - } - } - - // MARK: - Invalidation - - func finishRequestsForDeinit() { - requestTaskMap.requests.forEach { request in - rootQueue.async { - request.finish(error: AFError.sessionDeinitialized) - } - } - } -} - -// MARK: - RequestDelegate - -extension Session: RequestDelegate { - public var sessionConfiguration: URLSessionConfiguration { - session.configuration - } - - public var startImmediately: Bool { startRequestsImmediately } - - public func cleanup(after request: Request) { - activeRequests.remove(request) - } - - public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) { - guard let retrier = retrier(for: request) else { - rootQueue.async { completion(.doNotRetry) } - return - } - - retrier.retry(request, for: self, dueTo: error) { retryResult in - self.rootQueue.async { - guard let retryResultError = retryResult.error else { completion(retryResult); return } - - let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error) - completion(.doNotRetryWithError(retryError)) - } - } - } - - public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) { - rootQueue.async { - let retry: () -> Void = { - guard !request.isCancelled else { return } - - request.prepareForRetry() - self.perform(request) - } - - if let retryDelay = timeDelay { - self.rootQueue.after(retryDelay) { retry() } - } else { - retry() - } - } - } -} - -// MARK: - SessionStateProvider - -extension Session: SessionStateProvider { - func request(for task: URLSessionTask) -> Request? { - dispatchPrecondition(condition: .onQueue(rootQueue)) - - return requestTaskMap[task] - } - - func didGatherMetricsForTask(_ task: URLSessionTask) { - dispatchPrecondition(condition: .onQueue(rootQueue)) - - let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task) - - if didDisassociate { - waitingCompletions[task]?() - waitingCompletions[task] = nil - } - } - - func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) { - dispatchPrecondition(condition: .onQueue(rootQueue)) - - let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task) - - if didDisassociate { - completion() - } else { - waitingCompletions[task] = completion - } - } - - func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? { - dispatchPrecondition(condition: .onQueue(rootQueue)) - - return requestTaskMap[task]?.credential ?? - session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace) - } - - func cancelRequestsForSessionInvalidation(with error: Error?) { - dispatchPrecondition(condition: .onQueue(rootQueue)) - - requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) } - } -} diff --git a/Pods/Alamofire/Source/SessionDelegate.swift b/Pods/Alamofire/Source/SessionDelegate.swift deleted file mode 100644 index af45b27..0000000 --- a/Pods/Alamofire/Source/SessionDelegate.swift +++ /dev/null @@ -1,355 +0,0 @@ -// -// SessionDelegate.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. -open class SessionDelegate: NSObject { - private let fileManager: FileManager - - weak var stateProvider: SessionStateProvider? - var eventMonitor: EventMonitor? - - /// Creates an instance from the given `FileManager`. - /// - /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files. - /// `.default` by default. - public init(fileManager: FileManager = .default) { - self.fileManager = fileManager - } - - /// Internal method to find and cast requests while maintaining some integrity checking. - /// - /// - Parameters: - /// - task: The `URLSessionTask` for which to find the associated `Request`. - /// - type: The `Request` subclass type to cast any `Request` associate with `task`. - func request(for task: URLSessionTask, as type: R.Type) -> R? { - guard let provider = stateProvider else { - assertionFailure("StateProvider is nil.") - return nil - } - - return provider.request(for: task) as? R - } -} - -/// Type which provides various `Session` state values. -protocol SessionStateProvider: AnyObject { - var serverTrustManager: ServerTrustManager? { get } - var redirectHandler: RedirectHandler? { get } - var cachedResponseHandler: CachedResponseHandler? { get } - - func request(for task: URLSessionTask) -> Request? - func didGatherMetricsForTask(_ task: URLSessionTask) - func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) - func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? - func cancelRequestsForSessionInvalidation(with error: Error?) -} - -// MARK: URLSessionDelegate - -extension SessionDelegate: URLSessionDelegate { - open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) - - stateProvider?.cancelRequestsForSessionInvalidation(with: error) - } -} - -// MARK: URLSessionTaskDelegate - -extension SessionDelegate: URLSessionTaskDelegate { - /// Result of a `URLAuthenticationChallenge` evaluation. - typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?) - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { - eventMonitor?.urlSession(session, task: task, didReceive: challenge) - - let evaluation: ChallengeEvaluation - switch challenge.protectionSpace.authenticationMethod { - case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, - NSURLAuthenticationMethodNegotiate: - evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) - #if canImport(Security) - case NSURLAuthenticationMethodServerTrust: - evaluation = attemptServerTrustAuthentication(with: challenge) - case NSURLAuthenticationMethodClientCertificate: - evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) - #endif - default: - evaluation = (.performDefaultHandling, nil, nil) - } - - if let error = evaluation.error { - stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) - } - - completionHandler(evaluation.disposition, evaluation.credential) - } - - #if canImport(Security) - /// Evaluates the server trust `URLAuthenticationChallenge` received. - /// - /// - Parameter challenge: The `URLAuthenticationChallenge`. - /// - /// - Returns: The `ChallengeEvaluation`. - func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { - let host = challenge.protectionSpace.host - - guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, - let trust = challenge.protectionSpace.serverTrust - else { - return (.performDefaultHandling, nil, nil) - } - - do { - guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { - return (.performDefaultHandling, nil, nil) - } - - try evaluator.evaluate(trust, forHost: host) - - return (.useCredential, URLCredential(trust: trust), nil) - } catch { - return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) - } - } - #endif - - /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. - /// - /// - Parameters: - /// - challenge: The `URLAuthenticationChallenge`. - /// - task: The `URLSessionTask` which received the challenge. - /// - /// - Returns: The `ChallengeEvaluation`. - func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge, - belongingTo task: URLSessionTask) -> ChallengeEvaluation { - guard challenge.previousFailureCount == 0 else { - return (.rejectProtectionSpace, nil, nil) - } - - guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { - return (.performDefaultHandling, nil, nil) - } - - return (.useCredential, credential, nil) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - eventMonitor?.urlSession(session, - task: task, - didSendBodyData: bytesSent, - totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend) - - stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { - eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) - - guard let request = request(for: task, as: UploadRequest.self) else { - assertionFailure("needNewBodyStream did not find UploadRequest.") - completionHandler(nil) - return - } - - completionHandler(request.inputStream()) - } - - open func urlSession(_ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) { - eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request) - - if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { - redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) - } else { - completionHandler(request) - } - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) - - stateProvider?.request(for: task)?.didGatherMetrics(metrics) - - stateProvider?.didGatherMetricsForTask(task) - } - - open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) - - let request = stateProvider?.request(for: task) - - stateProvider?.didCompleteTask(task) { - request?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) - } - } - - @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) - open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { - eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task) - } -} - -// MARK: URLSessionDataDelegate - -extension SessionDelegate: URLSessionDataDelegate { - open func urlSession(_ session: URLSession, - dataTask: URLSessionDataTask, - didReceive response: URLResponse, - completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { - eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: response) - - guard let response = response as? HTTPURLResponse else { completionHandler(.allow); return } - - if let request = request(for: dataTask, as: DataRequest.self) { - request.didReceiveResponse(response, completionHandler: completionHandler) - } else if let request = request(for: dataTask, as: DataStreamRequest.self) { - request.didReceiveResponse(response, completionHandler: completionHandler) - } else { - assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive response") - completionHandler(.allow) - return - } - } - - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) - - if let request = request(for: dataTask, as: DataRequest.self) { - request.didReceive(data: data) - } else if let request = request(for: dataTask, as: DataStreamRequest.self) { - request.didReceive(data: data) - } else { - assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive data") - return - } - } - - open func urlSession(_ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse, - completionHandler: @escaping (CachedURLResponse?) -> Void) { - eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) - - if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { - handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) - } else { - completionHandler(proposedResponse) - } - } -} - -// MARK: URLSessionDownloadDelegate - -extension SessionDelegate: URLSessionDownloadDelegate { - open func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - eventMonitor?.urlSession(session, - downloadTask: downloadTask, - didResumeAtOffset: fileOffset, - expectedTotalBytes: expectedTotalBytes) - guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { - assertionFailure("downloadTask did not find DownloadRequest.") - return - } - - downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, - totalBytesExpectedToWrite: expectedTotalBytes) - } - - open func urlSession(_ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - eventMonitor?.urlSession(session, - downloadTask: downloadTask, - didWriteData: bytesWritten, - totalBytesWritten: totalBytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite) - guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { - assertionFailure("downloadTask did not find DownloadRequest.") - return - } - - downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite) - } - - open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { - eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) - - guard let request = request(for: downloadTask, as: DownloadRequest.self) else { - assertionFailure("downloadTask did not find DownloadRequest.") - return - } - - let (destination, options): (URL, DownloadRequest.Options) - if let response = request.response { - (destination, options) = request.destination(location, response) - } else { - // If there's no response this is likely a local file download, so generate the temporary URL directly. - (destination, options) = (DownloadRequest.defaultDestinationURL(location), []) - } - - eventMonitor?.request(request, didCreateDestinationURL: destination) - - do { - if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { - try fileManager.removeItem(at: destination) - } - - if options.contains(.createIntermediateDirectories) { - let directory = destination.deletingLastPathComponent() - try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) - } - - try fileManager.moveItem(at: location, to: destination) - - request.didFinishDownloading(using: downloadTask, with: .success(destination)) - } catch { - request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, - source: location, - destination: destination))) - } - } -} diff --git a/Pods/Alamofire/Source/StringEncoding+Alamofire.swift b/Pods/Alamofire/Source/StringEncoding+Alamofire.swift deleted file mode 100644 index 8fa6133..0000000 --- a/Pods/Alamofire/Source/StringEncoding+Alamofire.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// StringEncoding+Alamofire.swift -// -// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension String.Encoding { - /// Creates an encoding from the IANA charset name. - /// - /// - Notes: These mappings match those [provided by CoreFoundation](https://opensource.apple.com/source/CF/CF-476.18/CFStringUtilities.c.auto.html) - /// - /// - Parameter name: IANA charset name. - init?(ianaCharsetName name: String) { - switch name.lowercased() { - case "utf-8": - self = .utf8 - case "iso-8859-1": - self = .isoLatin1 - case "unicode-1-1", "iso-10646-ucs-2", "utf-16": - self = .utf16 - case "utf-16be": - self = .utf16BigEndian - case "utf-16le": - self = .utf16LittleEndian - case "utf-32": - self = .utf32 - case "utf-32be": - self = .utf32BigEndian - case "utf-32le": - self = .utf32LittleEndian - default: - return nil - } - } -} diff --git a/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift b/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift deleted file mode 100644 index 455c4bc..0000000 --- a/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift +++ /dev/null @@ -1,105 +0,0 @@ -// -// URLConvertible+URLRequestConvertible.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Types adopting the `URLConvertible` protocol can be used to construct `URL`s, which can then be used to construct -/// `URLRequests`. -public protocol URLConvertible { - /// Returns a `URL` from the conforming instance or throws. - /// - /// - Returns: The `URL` created from the instance. - /// - Throws: Any error thrown while creating the `URL`. - func asURL() throws -> URL -} - -extension String: URLConvertible { - /// Returns a `URL` if `self` can be used to initialize a `URL` instance, otherwise throws. - /// - /// - Returns: The `URL` initialized with `self`. - /// - Throws: An `AFError.invalidURL` instance. - public func asURL() throws -> URL { - guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } - - return url - } -} - -extension URL: URLConvertible { - /// Returns `self`. - public func asURL() throws -> URL { self } -} - -extension URLComponents: URLConvertible { - /// Returns a `URL` if the `self`'s `url` is not nil, otherwise throws. - /// - /// - Returns: The `URL` from the `url` property. - /// - Throws: An `AFError.invalidURL` instance. - public func asURL() throws -> URL { - guard let url = url else { throw AFError.invalidURL(url: self) } - - return url - } -} - -// MARK: - - -/// Types adopting the `URLRequestConvertible` protocol can be used to safely construct `URLRequest`s. -public protocol URLRequestConvertible { - /// Returns a `URLRequest` or throws if an `Error` was encountered. - /// - /// - Returns: A `URLRequest`. - /// - Throws: Any error thrown while constructing the `URLRequest`. - func asURLRequest() throws -> URLRequest -} - -extension URLRequestConvertible { - /// The `URLRequest` returned by discarding any `Error` encountered. - public var urlRequest: URLRequest? { try? asURLRequest() } -} - -extension URLRequest: URLRequestConvertible { - /// Returns `self`. - public func asURLRequest() throws -> URLRequest { self } -} - -// MARK: - - -extension URLRequest { - /// Creates an instance with the specified `url`, `method`, and `headers`. - /// - /// - Parameters: - /// - url: The `URLConvertible` value. - /// - method: The `HTTPMethod`. - /// - headers: The `HTTPHeaders`, `nil` by default. - /// - Throws: Any error thrown while converting the `URLConvertible` to a `URL`. - public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { - let url = try url.asURL() - - self.init(url: url) - - httpMethod = method.rawValue - allHTTPHeaderFields = headers?.dictionary - } -} diff --git a/Pods/Alamofire/Source/URLEncodedFormEncoder.swift b/Pods/Alamofire/Source/URLEncodedFormEncoder.swift deleted file mode 100644 index dcb5991..0000000 --- a/Pods/Alamofire/Source/URLEncodedFormEncoder.swift +++ /dev/null @@ -1,1083 +0,0 @@ -// -// URLEncodedFormEncoder.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// An object that encodes instances into URL-encoded query strings. -/// -/// `ArrayEncoding` can be used to configure how `Array` values are encoded. By default, the `.brackets` encoding is -/// used, encoding array values with brackets for each value. e.g `array[]=1&array[]=2`. -/// -/// `BoolEncoding` can be used to configure how `Bool` values are encoded. By default, the `.numeric` encoding is used, -/// encoding `true` as `1` and `false` as `0`. -/// -/// `DataEncoding` can be used to configure how `Data` values are encoded. By default, the `.deferredToData` encoding is -/// used, which encodes `Data` values using their default `Encodable` implementation. -/// -/// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` -/// encoding is used, which encodes `Date`s using their default `Encodable` implementation. -/// -/// `KeyEncoding` can be used to configure how keys are encoded. By default, the `.useDefaultKeys` encoding is used, -/// which encodes the keys directly from the `Encodable` implementation. -/// -/// `KeyPathEncoding` can be used to configure how paths within nested objects are encoded. By default, the `.brackets` -/// encoding is used, which encodes each sub-key in brackets. e.g. `parent[child][grandchild]=value`. -/// -/// `NilEncoding` can be used to configure how `nil` `Optional` values are encoded. By default, the `.dropKey` encoding -/// is used, which drops `nil` key / value pairs from the output entirely. -/// -/// `SpaceEncoding` can be used to configure how spaces are encoded. By default, the `.percentEscaped` encoding is used, -/// replacing spaces with `%20`. -/// -/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. -public final class URLEncodedFormEncoder { - /// Encoding to use for `Array` values. - public enum ArrayEncoding { - /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding. - case brackets - /// No brackets are appended to the key and the key is encoded as is. - case noBrackets - /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. - case indexInBrackets - /// Provide a custom array key encoding with the given closure. - case custom((_ key: String, _ index: Int) -> String) - - /// Encodes the key according to the encoding. - /// - /// - Parameters: - /// - key: The `key` to encode. - /// - index: When this enum instance is `.indexInBrackets`, the `index` to encode. - /// - /// - Returns: The encoded key. - func encode(_ key: String, atIndex index: Int) -> String { - switch self { - case .brackets: return "\(key)[]" - case .noBrackets: return key - case .indexInBrackets: return "\(key)[\(index)]" - case let .custom(encoding): return encoding(key, index) - } - } - } - - /// Encoding to use for `Bool` values. - public enum BoolEncoding { - /// Encodes `true` as `1`, `false` as `0`. - case numeric - /// Encodes `true` as "true", `false` as "false". This is the default encoding. - case literal - - /// Encodes the given `Bool` as a `String`. - /// - /// - Parameter value: The `Bool` to encode. - /// - /// - Returns: The encoded `String`. - func encode(_ value: Bool) -> String { - switch self { - case .numeric: return value ? "1" : "0" - case .literal: return value ? "true" : "false" - } - } - } - - /// Encoding to use for `Data` values. - public enum DataEncoding { - /// Defers encoding to the `Data` type. - case deferredToData - /// Encodes `Data` as a Base64-encoded string. This is the default encoding. - case base64 - /// Encode the `Data` as a custom value encoded by the given closure. - case custom((Data) throws -> String) - - /// Encodes `Data` according to the encoding. - /// - /// - Parameter data: The `Data` to encode. - /// - /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its - /// `Encodable` implementation. - func encode(_ data: Data) throws -> String? { - switch self { - case .deferredToData: return nil - case .base64: return data.base64EncodedString() - case let .custom(encoding): return try encoding(data) - } - } - } - - /// Encoding to use for `Date` values. - public enum DateEncoding { - /// ISO8601 and RFC3339 formatter. - private static let iso8601Formatter: ISO8601DateFormatter = { - let formatter = ISO8601DateFormatter() - formatter.formatOptions = .withInternetDateTime - return formatter - }() - - /// Defers encoding to the `Date` type. This is the default encoding. - case deferredToDate - /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970. - case secondsSince1970 - /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970. - case millisecondsSince1970 - /// Encodes `Date`s according to the ISO8601 and RFC3339 standards. - case iso8601 - /// Encodes `Date`s using the given `DateFormatter`. - case formatted(DateFormatter) - /// Encodes `Date`s using the given closure. - case custom((Date) throws -> String) - - /// Encodes the date according to the encoding. - /// - /// - Parameter date: The `Date` to encode. - /// - /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its - /// `Encodable` implementation. - func encode(_ date: Date) throws -> String? { - switch self { - case .deferredToDate: - return nil - case .secondsSince1970: - return String(date.timeIntervalSince1970) - case .millisecondsSince1970: - return String(date.timeIntervalSince1970 * 1000.0) - case .iso8601: - return DateEncoding.iso8601Formatter.string(from: date) - case let .formatted(formatter): - return formatter.string(from: date) - case let .custom(closure): - return try closure(date) - } - } - } - - /// Encoding to use for keys. - /// - /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128) - /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102). - public enum KeyEncoding { - /// Use the keys specified by each type. This is the default encoding. - case useDefaultKeys - /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key. - /// - /// Capital characters are determined by testing membership in - /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` - /// (Unicode General Categories Lu and Lt). - /// The conversion to lower case uses `Locale.system`, also known as - /// the ICU "root" locale. This means the result is consistent - /// regardless of the current user's locale and language preferences. - /// - /// Converting from camel case to snake case: - /// 1. Splits words at the boundary of lower-case to upper-case - /// 2. Inserts `_` between words - /// 3. Lowercases the entire string - /// 4. Preserves starting and ending `_`. - /// - /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. - /// - /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. - case convertToSnakeCase - /// Same as convertToSnakeCase, but using `-` instead of `_`. - /// For example `oneTwoThree` becomes `one-two-three`. - case convertToKebabCase - /// Capitalize the first letter only. - /// For example `oneTwoThree` becomes `OneTwoThree`. - case capitalized - /// Uppercase all letters. - /// For example `oneTwoThree` becomes `ONETWOTHREE`. - case uppercased - /// Lowercase all letters. - /// For example `oneTwoThree` becomes `onetwothree`. - case lowercased - /// A custom encoding using the provided closure. - case custom((String) -> String) - - func encode(_ key: String) -> String { - switch self { - case .useDefaultKeys: return key - case .convertToSnakeCase: return convertToSnakeCase(key) - case .convertToKebabCase: return convertToKebabCase(key) - case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst()) - case .uppercased: return key.uppercased() - case .lowercased: return key.lowercased() - case let .custom(encoding): return encoding(key) - } - } - - private func convertToSnakeCase(_ key: String) -> String { - convert(key, usingSeparator: "_") - } - - private func convertToKebabCase(_ key: String) -> String { - convert(key, usingSeparator: "-") - } - - private func convert(_ key: String, usingSeparator separator: String) -> String { - guard !key.isEmpty else { return key } - - var words: [Range] = [] - // The general idea of this algorithm is to split words on - // transition from lower to upper case, then on transition of >1 - // upper case characters to lowercase - // - // myProperty -> my_property - // myURLProperty -> my_url_property - // - // It is assumed, per Swift naming conventions, that the first character of the key is lowercase. - var wordStart = key.startIndex - var searchRange = key.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before - // the lower case character. - let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound) - words.append(upperCaseRange.lowerBound.. String - - /// Creates an instance with the encoding closure called for each sub-key in a key path. - /// - /// - Parameter encoding: Closure used to perform the encoding. - public init(encoding: @escaping (_ subkey: String) -> String) { - self.encoding = encoding - } - - func encodeKeyPath(_ keyPath: String) -> String { - encoding(keyPath) - } - } - - /// Encoding to use for `nil` values. - public struct NilEncoding { - /// Encodes `nil` by dropping the entire key / value pair. - public static let dropKey = NilEncoding { nil } - /// Encodes `nil` by dropping only the value. e.g. `value1=one&nilValue=&value2=two`. - public static let dropValue = NilEncoding { "" } - /// Encodes `nil` as `null`. - public static let null = NilEncoding { "null" } - - private let encoding: () -> String? - - /// Creates an instance with the encoding closure called for `nil` values. - /// - /// - Parameter encoding: Closure used to perform the encoding. - public init(encoding: @escaping () -> String?) { - self.encoding = encoding - } - - func encodeNil() -> String? { - encoding() - } - } - - /// Encoding to use for spaces. - public enum SpaceEncoding { - /// Encodes spaces using percent escaping (`%20`). - case percentEscaped - /// Encodes spaces as `+`. - case plusReplaced - - /// Encodes the string according to the encoding. - /// - /// - Parameter string: The `String` to encode. - /// - /// - Returns: The encoded `String`. - func encode(_ string: String) -> String { - switch self { - case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20") - case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+") - } - } - } - - /// `URLEncodedFormEncoder` error. - public enum Error: Swift.Error { - /// An invalid root object was created by the encoder. Only keyed values are valid. - case invalidRootObject(String) - - var localizedDescription: String { - switch self { - case let .invalidRootObject(object): - return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead." - } - } - } - - /// Whether or not to sort the encoded key value pairs. - /// - /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, - /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to - /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order. - public let alphabetizeKeyValuePairs: Bool - /// The `ArrayEncoding` to use. - public let arrayEncoding: ArrayEncoding - /// The `BoolEncoding` to use. - public let boolEncoding: BoolEncoding - /// THe `DataEncoding` to use. - public let dataEncoding: DataEncoding - /// The `DateEncoding` to use. - public let dateEncoding: DateEncoding - /// The `KeyEncoding` to use. - public let keyEncoding: KeyEncoding - /// The `KeyPathEncoding` to use. - public let keyPathEncoding: KeyPathEncoding - /// The `NilEncoding` to use. - public let nilEncoding: NilEncoding - /// The `SpaceEncoding` to use. - public let spaceEncoding: SpaceEncoding - /// The `CharacterSet` of allowed (non-escaped) characters. - public var allowedCharacters: CharacterSet - - /// Creates an instance from the supplied parameters. - /// - /// - Parameters: - /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default. - /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default. - /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default. - /// - dataEncoding: The `DataEncoding` to use. `.base64` by default. - /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default. - /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default. - /// - nilEncoding: The `NilEncoding` to use. `.drop` by default. - /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default. - /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by - /// default. - public init(alphabetizeKeyValuePairs: Bool = true, - arrayEncoding: ArrayEncoding = .brackets, - boolEncoding: BoolEncoding = .numeric, - dataEncoding: DataEncoding = .base64, - dateEncoding: DateEncoding = .deferredToDate, - keyEncoding: KeyEncoding = .useDefaultKeys, - keyPathEncoding: KeyPathEncoding = .brackets, - nilEncoding: NilEncoding = .dropKey, - spaceEncoding: SpaceEncoding = .percentEscaped, - allowedCharacters: CharacterSet = .afURLQueryAllowed) { - self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs - self.arrayEncoding = arrayEncoding - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - self.keyEncoding = keyEncoding - self.keyPathEncoding = keyPathEncoding - self.nilEncoding = nilEncoding - self.spaceEncoding = spaceEncoding - self.allowedCharacters = allowedCharacters - } - - func encode(_ value: Encodable) throws -> URLEncodedFormComponent { - let context = URLEncodedFormContext(.object([])) - let encoder = _URLEncodedFormEncoder(context: context, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - try value.encode(to: encoder) - - return context.component - } - - /// Encodes the `value` as a URL form encoded `String`. - /// - /// - Parameter value: The `Encodable` value.` - /// - /// - Returns: The encoded `String`. - /// - Throws: An `Error` or `EncodingError` instance if encoding fails. - public func encode(_ value: Encodable) throws -> String { - let component: URLEncodedFormComponent = try encode(value) - - guard case let .object(object) = component else { - throw Error.invalidRootObject("\(component)") - } - - let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs, - arrayEncoding: arrayEncoding, - keyEncoding: keyEncoding, - keyPathEncoding: keyPathEncoding, - spaceEncoding: spaceEncoding, - allowedCharacters: allowedCharacters) - let query = serializer.serialize(object) - - return query - } - - /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the - /// `.utf8` data. - /// - /// - Parameter value: The `Encodable` value. - /// - /// - Returns: The encoded `Data`. - /// - /// - Throws: An `Error` or `EncodingError` instance if encoding fails. - public func encode(_ value: Encodable) throws -> Data { - let string: String = try encode(value) - - return Data(string.utf8) - } -} - -final class _URLEncodedFormEncoder { - var codingPath: [CodingKey] - // Returns an empty dictionary, as this encoder doesn't support userInfo. - var userInfo: [CodingUserInfoKey: Any] { [:] } - - let context: URLEncodedFormContext - - private let boolEncoding: URLEncodedFormEncoder.BoolEncoding - private let dataEncoding: URLEncodedFormEncoder.DataEncoding - private let dateEncoding: URLEncodedFormEncoder.DateEncoding - private let nilEncoding: URLEncodedFormEncoder.NilEncoding - - init(context: URLEncodedFormContext, - codingPath: [CodingKey] = [], - boolEncoding: URLEncodedFormEncoder.BoolEncoding, - dataEncoding: URLEncodedFormEncoder.DataEncoding, - dateEncoding: URLEncodedFormEncoder.DateEncoding, - nilEncoding: URLEncodedFormEncoder.NilEncoding) { - self.context = context - self.codingPath = codingPath - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - self.nilEncoding = nilEncoding - } -} - -extension _URLEncodedFormEncoder: Encoder { - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { - let container = _URLEncodedFormEncoder.KeyedContainer(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - return KeyedEncodingContainer(container) - } - - func unkeyedContainer() -> UnkeyedEncodingContainer { - _URLEncodedFormEncoder.UnkeyedContainer(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - } - - func singleValueContainer() -> SingleValueEncodingContainer { - _URLEncodedFormEncoder.SingleValueContainer(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - } -} - -final class URLEncodedFormContext { - var component: URLEncodedFormComponent - - init(_ component: URLEncodedFormComponent) { - self.component = component - } -} - -enum URLEncodedFormComponent { - typealias Object = [(key: String, value: URLEncodedFormComponent)] - - case string(String) - case array([URLEncodedFormComponent]) - case object(Object) - - /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible. - var array: [URLEncodedFormComponent]? { - switch self { - case let .array(array): return array - default: return nil - } - } - - /// Converts self to an `Object` or returns `nil` if not convertible. - var object: Object? { - switch self { - case let .object(object): return object - default: return nil - } - } - - /// Sets self to the supplied value at a given path. - /// - /// data.set(to: "hello", at: ["path", "to", "value"]) - /// - /// - parameters: - /// - value: Value of `Self` to set at the supplied path. - /// - path: `CodingKey` path to update with the supplied value. - public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) { - set(&self, to: value, at: path) - } - - /// Recursive backing method to `set(to:at:)`. - private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) { - guard !path.isEmpty else { - context = value - return - } - - let end = path[0] - var child: URLEncodedFormComponent - switch path.count { - case 1: - child = value - case 2...: - if let index = end.intValue { - let array = context.array ?? [] - if array.count > index { - child = array[index] - } else { - child = .array([]) - } - set(&child, to: value, at: Array(path[1...])) - } else { - child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init()) - set(&child, to: value, at: Array(path[1...])) - } - default: fatalError("Unreachable") - } - - if let index = end.intValue { - if var array = context.array { - if array.count > index { - array[index] = child - } else { - array.append(child) - } - context = .array(array) - } else { - context = .array([child]) - } - } else { - if var object = context.object { - if let index = object.firstIndex(where: { $0.key == end.stringValue }) { - object[index] = (key: end.stringValue, value: child) - } else { - object.append((key: end.stringValue, value: child)) - } - context = .object(object) - } else { - context = .object([(key: end.stringValue, value: child)]) - } - } - } -} - -struct AnyCodingKey: CodingKey, Hashable { - let stringValue: String - let intValue: Int? - - init?(stringValue: String) { - self.stringValue = stringValue - intValue = nil - } - - init?(intValue: Int) { - stringValue = "\(intValue)" - self.intValue = intValue - } - - init(_ base: Key) where Key: CodingKey { - if let intValue = base.intValue { - self.init(intValue: intValue)! - } else { - self.init(stringValue: base.stringValue)! - } - } -} - -extension _URLEncodedFormEncoder { - final class KeyedContainer where Key: CodingKey { - var codingPath: [CodingKey] - - private let context: URLEncodedFormContext - private let boolEncoding: URLEncodedFormEncoder.BoolEncoding - private let dataEncoding: URLEncodedFormEncoder.DataEncoding - private let dateEncoding: URLEncodedFormEncoder.DateEncoding - private let nilEncoding: URLEncodedFormEncoder.NilEncoding - - init(context: URLEncodedFormContext, - codingPath: [CodingKey], - boolEncoding: URLEncodedFormEncoder.BoolEncoding, - dataEncoding: URLEncodedFormEncoder.DataEncoding, - dateEncoding: URLEncodedFormEncoder.DateEncoding, - nilEncoding: URLEncodedFormEncoder.NilEncoding) { - self.context = context - self.codingPath = codingPath - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - self.nilEncoding = nilEncoding - } - - private func nestedCodingPath(for key: CodingKey) -> [CodingKey] { - codingPath + [key] - } - } -} - -extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol { - func encodeNil(forKey key: Key) throws { - guard let nilValue = nilEncoding.encodeNil() else { return } - - try encode(nilValue, forKey: key) - } - - func encode(_ value: T, forKey key: Key) throws where T: Encodable { - var container = nestedSingleValueEncoder(for: key) - try container.encode(value) - } - - func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer { - let container = _URLEncodedFormEncoder.SingleValueContainer(context: context, - codingPath: nestedCodingPath(for: key), - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - - return container - } - - func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { - let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context, - codingPath: nestedCodingPath(for: key), - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - - return container - } - - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey: CodingKey { - let container = _URLEncodedFormEncoder.KeyedContainer(context: context, - codingPath: nestedCodingPath(for: key), - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - - return KeyedEncodingContainer(container) - } - - func superEncoder() -> Encoder { - _URLEncodedFormEncoder(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - } - - func superEncoder(forKey key: Key) -> Encoder { - _URLEncodedFormEncoder(context: context, - codingPath: nestedCodingPath(for: key), - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - } -} - -extension _URLEncodedFormEncoder { - final class SingleValueContainer { - var codingPath: [CodingKey] - - private var canEncodeNewValue = true - - private let context: URLEncodedFormContext - private let boolEncoding: URLEncodedFormEncoder.BoolEncoding - private let dataEncoding: URLEncodedFormEncoder.DataEncoding - private let dateEncoding: URLEncodedFormEncoder.DateEncoding - private let nilEncoding: URLEncodedFormEncoder.NilEncoding - - init(context: URLEncodedFormContext, - codingPath: [CodingKey], - boolEncoding: URLEncodedFormEncoder.BoolEncoding, - dataEncoding: URLEncodedFormEncoder.DataEncoding, - dateEncoding: URLEncodedFormEncoder.DateEncoding, - nilEncoding: URLEncodedFormEncoder.NilEncoding) { - self.context = context - self.codingPath = codingPath - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - self.nilEncoding = nilEncoding - } - - private func checkCanEncode(value: Any?) throws { - guard canEncodeNewValue else { - let context = EncodingError.Context(codingPath: codingPath, - debugDescription: "Attempt to encode value through single value container when previously value already encoded.") - throw EncodingError.invalidValue(value as Any, context) - } - } - } -} - -extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer { - func encodeNil() throws { - guard let nilValue = nilEncoding.encodeNil() else { return } - - try encode(nilValue) - } - - func encode(_ value: Bool) throws { - try encode(value, as: String(boolEncoding.encode(value))) - } - - func encode(_ value: String) throws { - try encode(value, as: value) - } - - func encode(_ value: Double) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Float) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int8) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int16) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int32) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: Int64) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt8) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt16) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt32) throws { - try encode(value, as: String(value)) - } - - func encode(_ value: UInt64) throws { - try encode(value, as: String(value)) - } - - private func encode(_ value: T, as string: String) throws where T: Encodable { - try checkCanEncode(value: value) - defer { canEncodeNewValue = false } - - context.component.set(to: .string(string), at: codingPath) - } - - func encode(_ value: T) throws where T: Encodable { - switch value { - case let date as Date: - guard let string = try dateEncoding.encode(date) else { - try attemptToEncode(value) - return - } - - try encode(value, as: string) - case let data as Data: - guard let string = try dataEncoding.encode(data) else { - try attemptToEncode(value) - return - } - - try encode(value, as: string) - case let decimal as Decimal: - // Decimal's `Encodable` implementation returns an object, not a single value, so override it. - try encode(value, as: String(describing: decimal)) - default: - try attemptToEncode(value) - } - } - - private func attemptToEncode(_ value: T) throws where T: Encodable { - try checkCanEncode(value: value) - defer { canEncodeNewValue = false } - - let encoder = _URLEncodedFormEncoder(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - try value.encode(to: encoder) - } -} - -extension _URLEncodedFormEncoder { - final class UnkeyedContainer { - var codingPath: [CodingKey] - - var count = 0 - var nestedCodingPath: [CodingKey] { - codingPath + [AnyCodingKey(intValue: count)!] - } - - private let context: URLEncodedFormContext - private let boolEncoding: URLEncodedFormEncoder.BoolEncoding - private let dataEncoding: URLEncodedFormEncoder.DataEncoding - private let dateEncoding: URLEncodedFormEncoder.DateEncoding - private let nilEncoding: URLEncodedFormEncoder.NilEncoding - - init(context: URLEncodedFormContext, - codingPath: [CodingKey], - boolEncoding: URLEncodedFormEncoder.BoolEncoding, - dataEncoding: URLEncodedFormEncoder.DataEncoding, - dateEncoding: URLEncodedFormEncoder.DateEncoding, - nilEncoding: URLEncodedFormEncoder.NilEncoding) { - self.context = context - self.codingPath = codingPath - self.boolEncoding = boolEncoding - self.dataEncoding = dataEncoding - self.dateEncoding = dateEncoding - self.nilEncoding = nilEncoding - } - } -} - -extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer { - func encodeNil() throws { - guard let nilValue = nilEncoding.encodeNil() else { return } - - try encode(nilValue) - } - - func encode(_ value: T) throws where T: Encodable { - var container = nestedSingleValueContainer() - try container.encode(value) - } - - func nestedSingleValueContainer() -> SingleValueEncodingContainer { - defer { count += 1 } - - return _URLEncodedFormEncoder.SingleValueContainer(context: context, - codingPath: nestedCodingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - } - - func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey: CodingKey { - defer { count += 1 } - let container = _URLEncodedFormEncoder.KeyedContainer(context: context, - codingPath: nestedCodingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - - return KeyedEncodingContainer(container) - } - - func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { - defer { count += 1 } - - return _URLEncodedFormEncoder.UnkeyedContainer(context: context, - codingPath: nestedCodingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - } - - func superEncoder() -> Encoder { - defer { count += 1 } - - return _URLEncodedFormEncoder(context: context, - codingPath: codingPath, - boolEncoding: boolEncoding, - dataEncoding: dataEncoding, - dateEncoding: dateEncoding, - nilEncoding: nilEncoding) - } -} - -final class URLEncodedFormSerializer { - private let alphabetizeKeyValuePairs: Bool - private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding - private let keyEncoding: URLEncodedFormEncoder.KeyEncoding - private let keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding - private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding - private let allowedCharacters: CharacterSet - - init(alphabetizeKeyValuePairs: Bool, - arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, - keyEncoding: URLEncodedFormEncoder.KeyEncoding, - keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding, - spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, - allowedCharacters: CharacterSet) { - self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs - self.arrayEncoding = arrayEncoding - self.keyEncoding = keyEncoding - self.keyPathEncoding = keyPathEncoding - self.spaceEncoding = spaceEncoding - self.allowedCharacters = allowedCharacters - } - - func serialize(_ object: URLEncodedFormComponent.Object) -> String { - var output: [String] = [] - for (key, component) in object { - let value = serialize(component, forKey: key) - output.append(value) - } - output = alphabetizeKeyValuePairs ? output.sorted() : output - - return output.joinedWithAmpersands() - } - - func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { - switch component { - case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))" - case let .array(array): return serialize(array, forKey: key) - case let .object(object): return serialize(object, forKey: key) - } - } - - func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String { - var segments: [String] = object.map { subKey, value in - let keyPath = keyPathEncoding.encodeKeyPath(subKey) - return serialize(value, forKey: key + keyPath) - } - segments = alphabetizeKeyValuePairs ? segments.sorted() : segments - - return segments.joinedWithAmpersands() - } - - func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { - var segments: [String] = array.enumerated().map { index, component in - let keyPath = arrayEncoding.encode(key, atIndex: index) - return serialize(component, forKey: keyPath) - } - segments = alphabetizeKeyValuePairs ? segments.sorted() : segments - - return segments.joinedWithAmpersands() - } - - func escape(_ query: String) -> String { - var allowedCharactersWithSpace = allowedCharacters - allowedCharactersWithSpace.insert(charactersIn: " ") - let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query - let spaceEncodedQuery = spaceEncoding.encode(escapedQuery) - - return spaceEncodedQuery - } -} - -extension Array where Element == String { - func joinedWithAmpersands() -> String { - joined(separator: "&") - } -} - -extension CharacterSet { - /// Creates a CharacterSet from RFC 3986 allowed characters. - /// - /// RFC 3986 states that the following characters are "reserved" characters. - /// - /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" - /// - /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow - /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" - /// should be percent-escaped in the query string. - public static let afURLQueryAllowed: CharacterSet = { - let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 - let subDelimitersToEncode = "!$&'()*+,;=" - let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") - - return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters) - }() -} diff --git a/Pods/Alamofire/Source/URLRequest+Alamofire.swift b/Pods/Alamofire/Source/URLRequest+Alamofire.swift deleted file mode 100644 index ab72fb5..0000000 --- a/Pods/Alamofire/Source/URLRequest+Alamofire.swift +++ /dev/null @@ -1,39 +0,0 @@ -// -// URLRequest+Alamofire.swift -// -// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension URLRequest { - /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type. - public var method: HTTPMethod? { - get { httpMethod.map(HTTPMethod.init) } - set { httpMethod = newValue?.rawValue } - } - - public func validate() throws { - if method == .get, let bodyData = httpBody { - throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData)) - } - } -} diff --git a/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift b/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift deleted file mode 100644 index 292a8fe..0000000 --- a/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// URLSessionConfiguration+Alamofire.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension URLSessionConfiguration: AlamofireExtended {} -extension AlamofireExtension where ExtendedType: URLSessionConfiguration { - /// Alamofire's default configuration. Same as `URLSessionConfiguration.default` but adds Alamofire default - /// `Accept-Language`, `Accept-Encoding`, and `User-Agent` headers. - public static var `default`: URLSessionConfiguration { - let configuration = URLSessionConfiguration.default - configuration.headers = .default - - return configuration - } - - /// `.ephemeral` configuration with Alamofire's default `Accept-Language`, `Accept-Encoding`, and `User-Agent` - /// headers. - public static var ephemeral: URLSessionConfiguration { - let configuration = URLSessionConfiguration.ephemeral - configuration.headers = .default - - return configuration - } -} diff --git a/Pods/Alamofire/Source/Validation.swift b/Pods/Alamofire/Source/Validation.swift deleted file mode 100644 index 2cf23fb..0000000 --- a/Pods/Alamofire/Source/Validation.swift +++ /dev/null @@ -1,302 +0,0 @@ -// -// Validation.swift -// -// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension Request { - // MARK: Helper Types - - fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason - - /// Used to represent whether a validation succeeded or failed. - public typealias ValidationResult = Result - - fileprivate struct MIMEType { - let type: String - let subtype: String - - var isWildcard: Bool { type == "*" && subtype == "*" } - - init?(_ string: String) { - let components: [String] = { - let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) - let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] - - return split.components(separatedBy: "/") - }() - - if let type = components.first, let subtype = components.last { - self.type = type - self.subtype = subtype - } else { - return nil - } - } - - func matches(_ mime: MIMEType) -> Bool { - switch (type, subtype) { - case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): - return true - default: - return false - } - } - } - - // MARK: Properties - - fileprivate var acceptableStatusCodes: Range { 200..<300 } - - fileprivate var acceptableContentTypes: [String] { - if let accept = request?.value(forHTTPHeaderField: "Accept") { - return accept.components(separatedBy: ",") - } - - return ["*/*"] - } - - // MARK: Status Code - - fileprivate func validate(statusCode acceptableStatusCodes: S, - response: HTTPURLResponse) - -> ValidationResult - where S.Iterator.Element == Int { - if acceptableStatusCodes.contains(response.statusCode) { - return .success(()) - } else { - let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) - return .failure(AFError.responseValidationFailed(reason: reason)) - } - } - - // MARK: Content Type - - fileprivate func validate(contentType acceptableContentTypes: S, - response: HTTPURLResponse, - data: Data?) - -> ValidationResult - where S.Iterator.Element == String { - guard let data = data, !data.isEmpty else { return .success(()) } - - return validate(contentType: acceptableContentTypes, response: response) - } - - fileprivate func validate(contentType acceptableContentTypes: S, - response: HTTPURLResponse) - -> ValidationResult - where S.Iterator.Element == String { - guard - let responseContentType = response.mimeType, - let responseMIMEType = MIMEType(responseContentType) - else { - for contentType in acceptableContentTypes { - if let mimeType = MIMEType(contentType), mimeType.isWildcard { - return .success(()) - } - } - - let error: AFError = { - let reason: ErrorReason = .missingContentType(acceptableContentTypes: acceptableContentTypes.sorted()) - return AFError.responseValidationFailed(reason: reason) - }() - - return .failure(error) - } - - for contentType in acceptableContentTypes { - if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { - return .success(()) - } - } - - let error: AFError = { - let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: acceptableContentTypes.sorted(), - responseContentType: responseContentType) - - return AFError.responseValidationFailed(reason: reason) - }() - - return .failure(error) - } -} - -// MARK: - - -extension DataRequest { - /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the - /// request was valid. - public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult - - /// Validates that the response has a status code in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. - /// - /// - Returns: The instance. - @discardableResult - public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - validate { [unowned self] _, response, _ in - self.validate(statusCode: acceptableStatusCodes, response: response) - } - } - - /// Validates that the response has a content type in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - /// - /// - returns: The request. - @discardableResult - public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { - validate { [unowned self] _, response, data in - self.validate(contentType: acceptableContentTypes(), response: response, data: data) - } - } - - /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content - /// type matches any specified in the Accept HTTP header field. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - returns: The request. - @discardableResult - public func validate() -> Self { - let contentTypes: () -> [String] = { [unowned self] in - acceptableContentTypes - } - return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) - } -} - -extension DataStreamRequest { - /// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the - /// request was valid. - public typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult - - /// Validates that the response has a status code in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. - /// - /// - Returns: The instance. - @discardableResult - public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - validate { [unowned self] _, response in - self.validate(statusCode: acceptableStatusCodes, response: response) - } - } - - /// Validates that the response has a content type in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - /// - /// - returns: The request. - @discardableResult - public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { - validate { [unowned self] _, response in - self.validate(contentType: acceptableContentTypes(), response: response) - } - } - - /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content - /// type matches any specified in the Accept HTTP header field. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - Returns: The instance. - @discardableResult - public func validate() -> Self { - let contentTypes: () -> [String] = { [unowned self] in - acceptableContentTypes - } - return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) - } -} - -// MARK: - - -extension DownloadRequest { - /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a - /// destination URL, and returns whether the request was valid. - public typealias Validation = (_ request: URLRequest?, - _ response: HTTPURLResponse, - _ fileURL: URL?) - -> ValidationResult - - /// Validates that the response has a status code in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. - /// - /// - Returns: The instance. - @discardableResult - public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - validate { [unowned self] _, response, _ in - self.validate(statusCode: acceptableStatusCodes, response: response) - } - } - - /// Validates that the response has a content type in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - /// - /// - returns: The request. - @discardableResult - public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { - validate { [unowned self] _, response, fileURL in - guard let validFileURL = fileURL else { - return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) - } - - do { - let data = try Data(contentsOf: validFileURL) - return self.validate(contentType: acceptableContentTypes(), response: response, data: data) - } catch { - return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) - } - } - } - - /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content - /// type matches any specified in the Accept HTTP header field. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - returns: The request. - @discardableResult - public func validate() -> Self { - let contentTypes = { [unowned self] in - acceptableContentTypes - } - return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) - } -} diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock deleted file mode 100644 index eea3d86..0000000 --- a/Pods/Manifest.lock +++ /dev/null @@ -1,20 +0,0 @@ -PODS: - - Alamofire (5.8.0) - - SwiftyJSON (5.0.1) - -DEPENDENCIES: - - Alamofire (~> 5.2) - - SwiftyJSON (~> 5.0) - -SPEC REPOS: - trunk: - - Alamofire - - SwiftyJSON - -SPEC CHECKSUMS: - Alamofire: 0e92e751b3e9e66d7982db43919d01f313b8eb91 - SwiftyJSON: 2f33a42c6fbc52764d96f13368585094bfd8aa5e - -PODFILE CHECKSUM: 5e61afd8812c9454d63f39ebb91e91b56a2d87b4 - -COCOAPODS: 1.12.1 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj deleted file mode 100644 index 9f704b8..0000000 --- a/Pods/Pods.xcodeproj/project.pbxproj +++ /dev/null @@ -1,939 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 55; - objects = { - -/* Begin PBXBuildFile section */ - 04A8430BFC619C34E5F4D3878D094380 /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80E500F0F145B765C8790D12014D5762 /* CachedResponseHandler.swift */; }; - 079F0820555C5B86C9FBD5EC6344137F /* Protected.swift in Sources */ = {isa = PBXBuildFile; fileRef = 136D69898625D4CE7169E6FC93CC5B3B /* Protected.swift */; }; - 11CCD832BD537718892C6A216A38490A /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D31DB1760C5695EE9B439DD62108846 /* URLRequest+Alamofire.swift */; }; - 197457852FC83E905248660B0F930452 /* AuthenticationInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DFBA534907823891A87B63D3CF1314 /* AuthenticationInterceptor.swift */; }; - 1AFD57838680DF58184FF94D14C7F3FF /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A1895CFA307AEA25985B669A053E29D /* RequestInterceptor.swift */; }; - 282FCD4EA8B05830E9108690B8CD336B /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1121250A1C77343D21882F241A51679 /* Session.swift */; }; - 2F89511EA6BE9B4E192272E9060674A7 /* Pods-DiaryApp-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 45EC6EEE1BE9C1F9BCA56EDF3650F910 /* Pods-DiaryApp-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 320C0D7A88AA812EFB20016BA1F5D7AE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A11577B72AA4553089ABB084F728B215 /* AFError.swift */; }; - 325CCDB295FFA016638075B5D2CEDD5C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; - 385BC4B250B6A6DB8AAAEA77D5B7A46F /* Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3078E923BB50C0CBFFAFCBF33A1D5A7B /* Combine.swift */; }; - 3A59D8FBAF9A54906E3644AC80465AFB /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD82A81AA05DD999D73E18F84E60D42E /* Notifications.swift */; }; - 3FA127A261BB563409868A0DC21807B2 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C199D0E86CE0A8AAD5CF013719B559E /* ResponseSerialization.swift */; }; - 482B74C0548970BB9C095E2D8530E421 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE95150D59D402944D22D64270CC596 /* ParameterEncoding.swift */; }; - 529173B31EFCD3D199E79866AFBEC86C /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBCEFF14802034F762E9D9AEBCE2911E /* HTTPHeaders.swift */; }; - 5B92A66A66BD639411C3D839A0F87B0C /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B697EA074391CA1E5281F6C42FEC222 /* Request.swift */; }; - 5E363952D297EEBFDC960AF93D5C1090 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; - 5FA526557719FDBE81B1974B113CF600 /* SwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B5D675CC25C04904109F8207299DFED0 /* SwiftyJSON-dummy.m */; }; - 643A7AFFB7AEB70B2B9B7E0926055023 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE519701FB770D29ACC8A8D8231EDE60 /* RetryPolicy.swift */; }; - 67B10FEAA3B7E5387D20E76B1085E94D /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6B65762324B6D2294DFE96F6546298A /* URLSessionConfiguration+Alamofire.swift */; }; - 6CB17C9753A4EAD270D129B366F9FEC5 /* Pods-DiaryApp-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D73D7B0EEC2266B6A2CB0C66355A76FA /* Pods-DiaryApp-dummy.m */; }; - 732C29255F73EF3D83D49BD4F8FEAA8F /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5190045555EB63C0CE433336B62F1EFE /* MultipartUpload.swift */; }; - 737747B9A98257DB58112C3A23686669 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A6AB9F7BED5CEAD6061F8E84B98A9AA /* MultipartFormData.swift */; }; - 77AB6AF4BFC6DE016DA7C057B5799C84 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55AC0B3E5EFE171CF2531104772E1A19 /* ServerTrustEvaluation.swift */; }; - 78B1DD1219182494A6AFAD26AAB20AA6 /* Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30A33AEB1ECAC7269C4B74174CF55AEC /* Concurrency.swift */; }; - 7D64BC3E6CAA4AB54EAC0AAADE93F578 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = D51D195FCE9098E02B61633008659F56 /* OperationQueue+Alamofire.swift */; }; - 81E6A0FF7F286008345ECFA3A2103FA8 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30C7AB0C34B2F81D314EF29DB2479728 /* Alamofire.swift */; }; - 82FD97FBBEFE51E2D3B434AF4954FC93 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC533D2C2706EF4D05C39CB8608073C0 /* EventMonitor.swift */; }; - 8E698F134A953250D5834C8B83CDAD34 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA9F3FE74C26CA6150E487EC73B4C6CF /* DispatchQueue+Alamofire.swift */; }; - 8E85763AE29BEF0A46EE875B8F069E8E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; - A115142039C23F91827E6961CC479F05 /* SwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = FC6755DCDD561DDF29441E07C4A243D9 /* SwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - A3CEE8324948497036C4E123B21CBC59 /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7B2B42AD4CEF88F4CCC378D6688B7CC /* SwiftyJSON.swift */; }; - A523488C60BF961290D0B1ABB9ADACEC /* RequestCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B55A86AD74401D249D77D562AB87E21 /* RequestCompression.swift */; }; - AA721ECC2B36AFB7D9FE70C83E6D63F9 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED8C6118D389689E913B1D9A16AE20E4 /* Response.swift */; }; - B17D933C8F8BC6A4F91AA620D7D7A870 /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75F57608866ED7F1B0AECAAD3E8D1480 /* ParameterEncoder.swift */; }; - BAB17A1C6CAD14B3788973EAF8466C93 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC95874ACDA952F59C68A1E198C45E6D /* NetworkReachabilityManager.swift */; }; - C04739CBCEE445B66192BFA708655EDF /* StringEncoding+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 501AA2DD4A61A385DAAA2B5D51AFFAA4 /* StringEncoding+Alamofire.swift */; }; - C8269B42DED12AB1F275648D0BD32E45 /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A08D0CF6B90AA621D958AD039F7F545 /* URLEncodedFormEncoder.swift */; }; - D0560E8E2E5EB407B5D8E0381BF453FA /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AD70DF61CE4EBB95681B2CB1D677753 /* URLConvertible+URLRequestConvertible.swift */; }; - D09FBBADAF7C5C757AA5AB5DFE54BD25 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A99447FC5354951E2B4EE89B31510C70 /* Alamofire-dummy.m */; }; - D368E6F70C5E6998548A72E65F92432D /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74391BDD82CE581AF8EEB0CA18A048B1 /* Validation.swift */; }; - D7BCBE1EB4A638403C265CE2199EFF1B /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D3D57353834825F7B52B816066B7789 /* CFNetwork.framework */; }; - E6251F02EE12804D1B66AE32E716E664 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18D1E41CFC45E859349C7E0368EE9DF1 /* SessionDelegate.swift */; }; - ECE6F23823454A8FDB3F97CE1A7CD182 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3BE26BD10803C330C2253D9B9BB3998 /* RedirectHandler.swift */; }; - ECF2F956B37A4C28B228BC291A57AD6E /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9D1F9ED142F768BE9209BE2650C151C /* RequestTaskMap.swift */; }; - F038D81F7ABAA15CF03246AD4BF334F7 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A08F78C71A4CC559CCAC71F103EB26F /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - F2415AE8678DE2698B7AD7D88B1A5C0F /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91302FA166B81FAAA21B862AE8C809AE /* AlamofireExtended.swift */; }; - F66CC47AD425C8D57BD149AFD09C2AFE /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6122F7837BC3657FB979A4B70F075644 /* HTTPMethod.swift */; }; - F6E94E8EE1CE35F49B9091BE8748587B /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBF6EFE675654E66327281E6A7801356 /* Result+Alamofire.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 25EE24530F5DE77C2138C3C848364587 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; - remoteInfo = Alamofire; - }; - 9A946D9941B776AE87D1C60FE7A1CA37 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = D118A6A04828FD3CDA8640CD2B6796D2; - remoteInfo = SwiftyJSON; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 08D72F04F55B8DAC1106A210D8946EC8 /* SwiftyJSON.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.debug.xcconfig; sourceTree = ""; }; - 0A08F78C71A4CC559CCAC71F103EB26F /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; - 136D69898625D4CE7169E6FC93CC5B3B /* Protected.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Protected.swift; path = Source/Protected.swift; sourceTree = ""; }; - 14AAF947BF52795074BC4C048D87CBF2 /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; - 18D1E41CFC45E859349C7E0368EE9DF1 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; - 1BF9CC04B4FD0CD457FA84A78FF7568A /* Pods-DiaryApp.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-DiaryApp.release.xcconfig"; sourceTree = ""; }; - 1C199D0E86CE0A8AAD5CF013719B559E /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; - 2A6AB9F7BED5CEAD6061F8E84B98A9AA /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; - 2CE95150D59D402944D22D64270CC596 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; - 2E0ECA398B6DC3827602F405677B2C28 /* SwiftyJSON.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.release.xcconfig; sourceTree = ""; }; - 3078E923BB50C0CBFFAFCBF33A1D5A7B /* Combine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Combine.swift; path = Source/Combine.swift; sourceTree = ""; }; - 30A33AEB1ECAC7269C4B74174CF55AEC /* Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concurrency.swift; path = Source/Concurrency.swift; sourceTree = ""; }; - 30C7AB0C34B2F81D314EF29DB2479728 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; - 3B697EA074391CA1E5281F6C42FEC222 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; - 40A2EBF5257D2162748FB0D6BAAC62BE /* Alamofire.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.release.xcconfig; sourceTree = ""; }; - 45EC6EEE1BE9C1F9BCA56EDF3650F910 /* Pods-DiaryApp-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-DiaryApp-umbrella.h"; sourceTree = ""; }; - 4B55A86AD74401D249D77D562AB87E21 /* RequestCompression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestCompression.swift; path = Source/RequestCompression.swift; sourceTree = ""; }; - 501AA2DD4A61A385DAAA2B5D51AFFAA4 /* StringEncoding+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "StringEncoding+Alamofire.swift"; path = "Source/StringEncoding+Alamofire.swift"; sourceTree = ""; }; - 5190045555EB63C0CE433336B62F1EFE /* MultipartUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartUpload.swift; path = Source/MultipartUpload.swift; sourceTree = ""; }; - 528324114E67C28E10AD71BF531E9A0E /* SwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SwiftyJSON.modulemap; sourceTree = ""; }; - 55AC0B3E5EFE171CF2531104772E1A19 /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustEvaluation.swift; path = Source/ServerTrustEvaluation.swift; sourceTree = ""; }; - 571EB0F4A1903700A7631F3C8D497307 /* Pods-DiaryApp-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-DiaryApp-acknowledgements.plist"; sourceTree = ""; }; - 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 5F9C2818D0015901A6056D4A5F086DD3 /* Pods-DiaryApp */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-DiaryApp"; path = Pods_DiaryApp.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 6122F7837BC3657FB979A4B70F075644 /* HTTPMethod.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPMethod.swift; path = Source/HTTPMethod.swift; sourceTree = ""; }; - 74391BDD82CE581AF8EEB0CA18A048B1 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - 75F57608866ED7F1B0AECAAD3E8D1480 /* ParameterEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoder.swift; path = Source/ParameterEncoder.swift; sourceTree = ""; }; - 75F5B7EF640D4B1A9C333EADBD359F47 /* SwiftyJSON-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SwiftyJSON-Info.plist"; sourceTree = ""; }; - 7A08D0CF6B90AA621D958AD039F7F545 /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLEncodedFormEncoder.swift; path = Source/URLEncodedFormEncoder.swift; sourceTree = ""; }; - 7A1895CFA307AEA25985B669A053E29D /* RequestInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestInterceptor.swift; path = Source/RequestInterceptor.swift; sourceTree = ""; }; - 80E500F0F145B765C8790D12014D5762 /* CachedResponseHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CachedResponseHandler.swift; path = Source/CachedResponseHandler.swift; sourceTree = ""; }; - 8AD70DF61CE4EBB95681B2CB1D677753 /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLConvertible+URLRequestConvertible.swift"; path = "Source/URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; - 8D3D57353834825F7B52B816066B7789 /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; - 91302FA166B81FAAA21B862AE8C809AE /* AlamofireExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireExtended.swift; path = Source/AlamofireExtended.swift; sourceTree = ""; }; - 9D31DB1760C5695EE9B439DD62108846 /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Alamofire.swift"; path = "Source/URLRequest+Alamofire.swift"; sourceTree = ""; }; - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 9DEFECFEAF0C978DF44C124E0BD594E7 /* SwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-prefix.pch"; sourceTree = ""; }; - A11577B72AA4553089ABB084F728B215 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; - A15528F1A1F70BECF6479F15B930BB57 /* Pods-DiaryApp-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-DiaryApp-frameworks.sh"; sourceTree = ""; }; - A249A2B83CC3ECEF2DA592160DFE283D /* Pods-DiaryApp.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-DiaryApp.debug.xcconfig"; sourceTree = ""; }; - A7B2B42AD4CEF88F4CCC378D6688B7CC /* SwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftyJSON.swift; path = Source/SwiftyJSON/SwiftyJSON.swift; sourceTree = ""; }; - A99447FC5354951E2B4EE89B31510C70 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; - B4E635F2092C404FC9100DA1B41920FA /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; - B5D675CC25C04904109F8207299DFED0 /* SwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftyJSON-dummy.m"; sourceTree = ""; }; - BA9F3FE74C26CA6150E487EC73B4C6CF /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; - BBCEFF14802034F762E9D9AEBCE2911E /* HTTPHeaders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHeaders.swift; path = Source/HTTPHeaders.swift; sourceTree = ""; }; - C0DFBA534907823891A87B63D3CF1314 /* AuthenticationInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AuthenticationInterceptor.swift; path = Source/AuthenticationInterceptor.swift; sourceTree = ""; }; - C77EAAD4714B2D83B1C0661732B06E6A /* Pods-DiaryApp.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-DiaryApp.modulemap"; sourceTree = ""; }; - CB489F9A2BACE59A9F683A85F52505C3 /* Pods-DiaryApp-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-DiaryApp-acknowledgements.markdown"; sourceTree = ""; }; - CC533D2C2706EF4D05C39CB8608073C0 /* EventMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventMonitor.swift; path = Source/EventMonitor.swift; sourceTree = ""; }; - CC95874ACDA952F59C68A1E198C45E6D /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; - CD79008838AE61E32FFD1716929AC2F1 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; - D51D195FCE9098E02B61633008659F56 /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "OperationQueue+Alamofire.swift"; path = "Source/OperationQueue+Alamofire.swift"; sourceTree = ""; }; - D73D7B0EEC2266B6A2CB0C66355A76FA /* Pods-DiaryApp-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-DiaryApp-dummy.m"; sourceTree = ""; }; - D9D1F9ED142F768BE9209BE2650C151C /* RequestTaskMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTaskMap.swift; path = Source/RequestTaskMap.swift; sourceTree = ""; }; - DBF6EFE675654E66327281E6A7801356 /* Result+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Result+Alamofire.swift"; path = "Source/Result+Alamofire.swift"; sourceTree = ""; }; - DE519701FB770D29ACC8A8D8231EDE60 /* RetryPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryPolicy.swift; path = Source/RetryPolicy.swift; sourceTree = ""; }; - E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SwiftyJSON; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - E3BE26BD10803C330C2253D9B9BB3998 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Source/RedirectHandler.swift; sourceTree = ""; }; - ED527FF867A54B900D1EA2E8F4AD4E2D /* Alamofire.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.debug.xcconfig; sourceTree = ""; }; - ED8C6118D389689E913B1D9A16AE20E4 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; - F1121250A1C77343D21882F241A51679 /* Session.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Session.swift; path = Source/Session.swift; sourceTree = ""; }; - F6B65762324B6D2294DFE96F6546298A /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSessionConfiguration+Alamofire.swift"; path = "Source/URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; - FAF0D15D79312C1EC4B0AF3B4C81C1A3 /* Pods-DiaryApp-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-DiaryApp-Info.plist"; sourceTree = ""; }; - FC6755DCDD561DDF29441E07C4A243D9 /* SwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-umbrella.h"; sourceTree = ""; }; - FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; - FD82A81AA05DD999D73E18F84E60D42E /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 3977393A21672F0FBC6F1193739E0D15 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 325CCDB295FFA016638075B5D2CEDD5C /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 5BF6E64D3157435E5797A5278584A4DC /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - D7BCBE1EB4A638403C265CE2199EFF1B /* CFNetwork.framework in Frameworks */, - 8E85763AE29BEF0A46EE875B8F069E8E /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - FBF275D03B0C8D171A97F34D1C197333 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 5E363952D297EEBFDC960AF93D5C1090 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 61C8CC330A5CA84DA2F5F1D32AB07069 /* iOS */, - ); - name = Frameworks; - sourceTree = ""; - }; - 343C4D5B9441A9C8A9F89904AABAABC2 /* Support Files */ = { - isa = PBXGroup; - children = ( - CD79008838AE61E32FFD1716929AC2F1 /* Alamofire.modulemap */, - A99447FC5354951E2B4EE89B31510C70 /* Alamofire-dummy.m */, - 14AAF947BF52795074BC4C048D87CBF2 /* Alamofire-Info.plist */, - B4E635F2092C404FC9100DA1B41920FA /* Alamofire-prefix.pch */, - 0A08F78C71A4CC559CCAC71F103EB26F /* Alamofire-umbrella.h */, - ED527FF867A54B900D1EA2E8F4AD4E2D /* Alamofire.debug.xcconfig */, - 40A2EBF5257D2162748FB0D6BAAC62BE /* Alamofire.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; - sourceTree = ""; - }; - 3B5B2CDDC9ACCECC65D4DE3D945692E1 /* SwiftyJSON */ = { - isa = PBXGroup; - children = ( - A7B2B42AD4CEF88F4CCC378D6688B7CC /* SwiftyJSON.swift */, - CAEE96DC76CF535AA181B64994201BD7 /* Support Files */, - ); - name = SwiftyJSON; - path = SwiftyJSON; - sourceTree = ""; - }; - 4AFF7588B551EF7D5C39DD2A317F5DD2 /* Targets Support Files */ = { - isa = PBXGroup; - children = ( - 6F944C129BBA621F70B917C4A53D1419 /* Pods-DiaryApp */, - ); - name = "Targets Support Files"; - sourceTree = ""; - }; - 61C8CC330A5CA84DA2F5F1D32AB07069 /* iOS */ = { - isa = PBXGroup; - children = ( - 8D3D57353834825F7B52B816066B7789 /* CFNetwork.framework */, - FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */, - ); - name = iOS; - sourceTree = ""; - }; - 6F944C129BBA621F70B917C4A53D1419 /* Pods-DiaryApp */ = { - isa = PBXGroup; - children = ( - C77EAAD4714B2D83B1C0661732B06E6A /* Pods-DiaryApp.modulemap */, - CB489F9A2BACE59A9F683A85F52505C3 /* Pods-DiaryApp-acknowledgements.markdown */, - 571EB0F4A1903700A7631F3C8D497307 /* Pods-DiaryApp-acknowledgements.plist */, - D73D7B0EEC2266B6A2CB0C66355A76FA /* Pods-DiaryApp-dummy.m */, - A15528F1A1F70BECF6479F15B930BB57 /* Pods-DiaryApp-frameworks.sh */, - FAF0D15D79312C1EC4B0AF3B4C81C1A3 /* Pods-DiaryApp-Info.plist */, - 45EC6EEE1BE9C1F9BCA56EDF3650F910 /* Pods-DiaryApp-umbrella.h */, - A249A2B83CC3ECEF2DA592160DFE283D /* Pods-DiaryApp.debug.xcconfig */, - 1BF9CC04B4FD0CD457FA84A78FF7568A /* Pods-DiaryApp.release.xcconfig */, - ); - name = "Pods-DiaryApp"; - path = "Target Support Files/Pods-DiaryApp"; - sourceTree = ""; - }; - 8F75D8B612FBB879D9C90143AFCEFF25 /* Products */ = { - isa = PBXGroup; - children = ( - 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */, - 5F9C2818D0015901A6056D4A5F086DD3 /* Pods-DiaryApp */, - E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON */, - ); - name = Products; - sourceTree = ""; - }; - A432C0D0F76CDD71F8C45F1970C7EA89 /* Pods */ = { - isa = PBXGroup; - children = ( - E866D9E518011326A7ABF952D1B92E1A /* Alamofire */, - 3B5B2CDDC9ACCECC65D4DE3D945692E1 /* SwiftyJSON */, - ); - name = Pods; - sourceTree = ""; - }; - CAEE96DC76CF535AA181B64994201BD7 /* Support Files */ = { - isa = PBXGroup; - children = ( - 528324114E67C28E10AD71BF531E9A0E /* SwiftyJSON.modulemap */, - B5D675CC25C04904109F8207299DFED0 /* SwiftyJSON-dummy.m */, - 75F5B7EF640D4B1A9C333EADBD359F47 /* SwiftyJSON-Info.plist */, - 9DEFECFEAF0C978DF44C124E0BD594E7 /* SwiftyJSON-prefix.pch */, - FC6755DCDD561DDF29441E07C4A243D9 /* SwiftyJSON-umbrella.h */, - 08D72F04F55B8DAC1106A210D8946EC8 /* SwiftyJSON.debug.xcconfig */, - 2E0ECA398B6DC3827602F405677B2C28 /* SwiftyJSON.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/SwiftyJSON"; - sourceTree = ""; - }; - CF1408CF629C7361332E53B88F7BD30C = { - isa = PBXGroup; - children = ( - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, - 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */, - A432C0D0F76CDD71F8C45F1970C7EA89 /* Pods */, - 8F75D8B612FBB879D9C90143AFCEFF25 /* Products */, - 4AFF7588B551EF7D5C39DD2A317F5DD2 /* Targets Support Files */, - ); - sourceTree = ""; - }; - E866D9E518011326A7ABF952D1B92E1A /* Alamofire */ = { - isa = PBXGroup; - children = ( - A11577B72AA4553089ABB084F728B215 /* AFError.swift */, - 30C7AB0C34B2F81D314EF29DB2479728 /* Alamofire.swift */, - 91302FA166B81FAAA21B862AE8C809AE /* AlamofireExtended.swift */, - C0DFBA534907823891A87B63D3CF1314 /* AuthenticationInterceptor.swift */, - 80E500F0F145B765C8790D12014D5762 /* CachedResponseHandler.swift */, - 3078E923BB50C0CBFFAFCBF33A1D5A7B /* Combine.swift */, - 30A33AEB1ECAC7269C4B74174CF55AEC /* Concurrency.swift */, - BA9F3FE74C26CA6150E487EC73B4C6CF /* DispatchQueue+Alamofire.swift */, - CC533D2C2706EF4D05C39CB8608073C0 /* EventMonitor.swift */, - BBCEFF14802034F762E9D9AEBCE2911E /* HTTPHeaders.swift */, - 6122F7837BC3657FB979A4B70F075644 /* HTTPMethod.swift */, - 2A6AB9F7BED5CEAD6061F8E84B98A9AA /* MultipartFormData.swift */, - 5190045555EB63C0CE433336B62F1EFE /* MultipartUpload.swift */, - CC95874ACDA952F59C68A1E198C45E6D /* NetworkReachabilityManager.swift */, - FD82A81AA05DD999D73E18F84E60D42E /* Notifications.swift */, - D51D195FCE9098E02B61633008659F56 /* OperationQueue+Alamofire.swift */, - 75F57608866ED7F1B0AECAAD3E8D1480 /* ParameterEncoder.swift */, - 2CE95150D59D402944D22D64270CC596 /* ParameterEncoding.swift */, - 136D69898625D4CE7169E6FC93CC5B3B /* Protected.swift */, - E3BE26BD10803C330C2253D9B9BB3998 /* RedirectHandler.swift */, - 3B697EA074391CA1E5281F6C42FEC222 /* Request.swift */, - 4B55A86AD74401D249D77D562AB87E21 /* RequestCompression.swift */, - 7A1895CFA307AEA25985B669A053E29D /* RequestInterceptor.swift */, - D9D1F9ED142F768BE9209BE2650C151C /* RequestTaskMap.swift */, - ED8C6118D389689E913B1D9A16AE20E4 /* Response.swift */, - 1C199D0E86CE0A8AAD5CF013719B559E /* ResponseSerialization.swift */, - DBF6EFE675654E66327281E6A7801356 /* Result+Alamofire.swift */, - DE519701FB770D29ACC8A8D8231EDE60 /* RetryPolicy.swift */, - 55AC0B3E5EFE171CF2531104772E1A19 /* ServerTrustEvaluation.swift */, - F1121250A1C77343D21882F241A51679 /* Session.swift */, - 18D1E41CFC45E859349C7E0368EE9DF1 /* SessionDelegate.swift */, - 501AA2DD4A61A385DAAA2B5D51AFFAA4 /* StringEncoding+Alamofire.swift */, - 8AD70DF61CE4EBB95681B2CB1D677753 /* URLConvertible+URLRequestConvertible.swift */, - 7A08D0CF6B90AA621D958AD039F7F545 /* URLEncodedFormEncoder.swift */, - 9D31DB1760C5695EE9B439DD62108846 /* URLRequest+Alamofire.swift */, - F6B65762324B6D2294DFE96F6546298A /* URLSessionConfiguration+Alamofire.swift */, - 74391BDD82CE581AF8EEB0CA18A048B1 /* Validation.swift */, - 343C4D5B9441A9C8A9F89904AABAABC2 /* Support Files */, - ); - name = Alamofire; - path = Alamofire; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 37AF420EAACFD30FC53913AC89710C00 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 2F89511EA6BE9B4E192272E9060674A7 /* Pods-DiaryApp-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 41145698F7DF35B05606D01197454CFC /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - A115142039C23F91827E6961CC479F05 /* SwiftyJSON-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - ED12AA7015568FEE3FAA009FC97DAAD5 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - F038D81F7ABAA15CF03246AD4BF334F7 /* Alamofire-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - CC9775904631956189536A37F63CE37E /* Pods-DiaryApp */ = { - isa = PBXNativeTarget; - buildConfigurationList = 7B5018230A2DA353B0B36C08868324D1 /* Build configuration list for PBXNativeTarget "Pods-DiaryApp" */; - buildPhases = ( - 37AF420EAACFD30FC53913AC89710C00 /* Headers */, - 6681F71DB2F5634633FADB4DEB4719E7 /* Sources */, - FBF275D03B0C8D171A97F34D1C197333 /* Frameworks */, - D4122CB0EB090487D805F048E3000178 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 8F3650EC1DC9D8FAC97DBF6DAFF86B24 /* PBXTargetDependency */, - 8551393011A629CD25638D28ED437E0D /* PBXTargetDependency */, - ); - name = "Pods-DiaryApp"; - productName = Pods_DiaryApp; - productReference = 5F9C2818D0015901A6056D4A5F086DD3 /* Pods-DiaryApp */; - productType = "com.apple.product-type.framework"; - }; - D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */ = { - isa = PBXNativeTarget; - buildConfigurationList = 2490E828D479276A7E0AFBA515DD77FA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */; - buildPhases = ( - 41145698F7DF35B05606D01197454CFC /* Headers */, - 7B5BEB32F210EFE38F7D58FF8A1CC2DE /* Sources */, - 3977393A21672F0FBC6F1193739E0D15 /* Frameworks */, - B05597C458D738E12F170EAC515F8483 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = SwiftyJSON; - productName = SwiftyJSON; - productReference = E23C076BA70925415F490FEDB215DA92 /* SwiftyJSON */; - productType = "com.apple.product-type.framework"; - }; - EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { - isa = PBXNativeTarget; - buildConfigurationList = D7761A54AFA2998F27E0BC2FACC2EB53 /* Build configuration list for PBXNativeTarget "Alamofire" */; - buildPhases = ( - ED12AA7015568FEE3FAA009FC97DAAD5 /* Headers */, - 277C3B3F937C6D40D2B777A164FAB89D /* Sources */, - 5BF6E64D3157435E5797A5278584A4DC /* Frameworks */, - 565FD2058706F22D2347B30C65280F30 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Alamofire; - productName = Alamofire; - productReference = 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */; - productType = "com.apple.product-type.framework"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - BFDFE7DC352907FC980B868725387E98 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1300; - LastUpgradeCheck = 1300; - }; - buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; - compatibilityVersion = "Xcode 13.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - Base, - en, - ); - mainGroup = CF1408CF629C7361332E53B88F7BD30C; - productRefGroup = 8F75D8B612FBB879D9C90143AFCEFF25 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */, - CC9775904631956189536A37F63CE37E /* Pods-DiaryApp */, - D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 565FD2058706F22D2347B30C65280F30 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - B05597C458D738E12F170EAC515F8483 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - D4122CB0EB090487D805F048E3000178 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 277C3B3F937C6D40D2B777A164FAB89D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 320C0D7A88AA812EFB20016BA1F5D7AE /* AFError.swift in Sources */, - 81E6A0FF7F286008345ECFA3A2103FA8 /* Alamofire.swift in Sources */, - D09FBBADAF7C5C757AA5AB5DFE54BD25 /* Alamofire-dummy.m in Sources */, - F2415AE8678DE2698B7AD7D88B1A5C0F /* AlamofireExtended.swift in Sources */, - 197457852FC83E905248660B0F930452 /* AuthenticationInterceptor.swift in Sources */, - 04A8430BFC619C34E5F4D3878D094380 /* CachedResponseHandler.swift in Sources */, - 385BC4B250B6A6DB8AAAEA77D5B7A46F /* Combine.swift in Sources */, - 78B1DD1219182494A6AFAD26AAB20AA6 /* Concurrency.swift in Sources */, - 8E698F134A953250D5834C8B83CDAD34 /* DispatchQueue+Alamofire.swift in Sources */, - 82FD97FBBEFE51E2D3B434AF4954FC93 /* EventMonitor.swift in Sources */, - 529173B31EFCD3D199E79866AFBEC86C /* HTTPHeaders.swift in Sources */, - F66CC47AD425C8D57BD149AFD09C2AFE /* HTTPMethod.swift in Sources */, - 737747B9A98257DB58112C3A23686669 /* MultipartFormData.swift in Sources */, - 732C29255F73EF3D83D49BD4F8FEAA8F /* MultipartUpload.swift in Sources */, - BAB17A1C6CAD14B3788973EAF8466C93 /* NetworkReachabilityManager.swift in Sources */, - 3A59D8FBAF9A54906E3644AC80465AFB /* Notifications.swift in Sources */, - 7D64BC3E6CAA4AB54EAC0AAADE93F578 /* OperationQueue+Alamofire.swift in Sources */, - B17D933C8F8BC6A4F91AA620D7D7A870 /* ParameterEncoder.swift in Sources */, - 482B74C0548970BB9C095E2D8530E421 /* ParameterEncoding.swift in Sources */, - 079F0820555C5B86C9FBD5EC6344137F /* Protected.swift in Sources */, - ECE6F23823454A8FDB3F97CE1A7CD182 /* RedirectHandler.swift in Sources */, - 5B92A66A66BD639411C3D839A0F87B0C /* Request.swift in Sources */, - A523488C60BF961290D0B1ABB9ADACEC /* RequestCompression.swift in Sources */, - 1AFD57838680DF58184FF94D14C7F3FF /* RequestInterceptor.swift in Sources */, - ECF2F956B37A4C28B228BC291A57AD6E /* RequestTaskMap.swift in Sources */, - AA721ECC2B36AFB7D9FE70C83E6D63F9 /* Response.swift in Sources */, - 3FA127A261BB563409868A0DC21807B2 /* ResponseSerialization.swift in Sources */, - F6E94E8EE1CE35F49B9091BE8748587B /* Result+Alamofire.swift in Sources */, - 643A7AFFB7AEB70B2B9B7E0926055023 /* RetryPolicy.swift in Sources */, - 77AB6AF4BFC6DE016DA7C057B5799C84 /* ServerTrustEvaluation.swift in Sources */, - 282FCD4EA8B05830E9108690B8CD336B /* Session.swift in Sources */, - E6251F02EE12804D1B66AE32E716E664 /* SessionDelegate.swift in Sources */, - C04739CBCEE445B66192BFA708655EDF /* StringEncoding+Alamofire.swift in Sources */, - D0560E8E2E5EB407B5D8E0381BF453FA /* URLConvertible+URLRequestConvertible.swift in Sources */, - C8269B42DED12AB1F275648D0BD32E45 /* URLEncodedFormEncoder.swift in Sources */, - 11CCD832BD537718892C6A216A38490A /* URLRequest+Alamofire.swift in Sources */, - 67B10FEAA3B7E5387D20E76B1085E94D /* URLSessionConfiguration+Alamofire.swift in Sources */, - D368E6F70C5E6998548A72E65F92432D /* Validation.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 6681F71DB2F5634633FADB4DEB4719E7 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 6CB17C9753A4EAD270D129B366F9FEC5 /* Pods-DiaryApp-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 7B5BEB32F210EFE38F7D58FF8A1CC2DE /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - A3CEE8324948497036C4E123B21CBC59 /* SwiftyJSON.swift in Sources */, - 5FA526557719FDBE81B1974B113CF600 /* SwiftyJSON-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 8551393011A629CD25638D28ED437E0D /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = SwiftyJSON; - target = D118A6A04828FD3CDA8640CD2B6796D2 /* SwiftyJSON */; - targetProxy = 9A946D9941B776AE87D1C60FE7A1CA37 /* PBXContainerItemProxy */; - }; - 8F3650EC1DC9D8FAC97DBF6DAFF86B24 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Alamofire; - target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; - targetProxy = 25EE24530F5DE77C2138C3C848364587 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 61C156878AA0F739377C03E2D20A62BF /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = A249A2B83CC3ECEF2DA592160DFE283D /* Pods-DiaryApp.debug.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 8DE5143C03248BB6CD542DE3963D6F3A /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_DEBUG=1", - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Debug; - }; - 9E406C6AAF85E580207CD97B0044DEAB /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_RELEASE=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Release; - }; - A9EEBF12B0E3733A640B1F7870912751 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 2E0ECA398B6DC3827602F405677B2C28 /* SwiftyJSON.release.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; - PRODUCT_MODULE_NAME = SwiftyJSON; - PRODUCT_NAME = SwiftyJSON; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - B7D9E7CD650F798EC835C67DACFEBC4F /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = ED527FF867A54B900D1EA2E8F4AD4E2D /* Alamofire.debug.xcconfig */; - buildSettings = { - CLANG_ENABLE_OBJC_WEAK = NO; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - PRODUCT_MODULE_NAME = Alamofire; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - BD0E5E3EFB0F4CCE246B60BB04FAB85B /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 08D72F04F55B8DAC1106A210D8946EC8 /* SwiftyJSON.debug.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; - PRODUCT_MODULE_NAME = SwiftyJSON; - PRODUCT_NAME = SwiftyJSON; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - ED4DC8D666B2B63C25FA4E972D98AD8B /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 1BF9CC04B4FD0CD457FA84A78FF7568A /* Pods-DiaryApp.release.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - F5F3306F2C09AB4B623C805497E28D51 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 40A2EBF5257D2162748FB0D6BAAC62BE /* Alamofire.release.xcconfig */; - buildSettings = { - CLANG_ENABLE_OBJC_WEAK = NO; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - PRODUCT_MODULE_NAME = Alamofire; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 2490E828D479276A7E0AFBA515DD77FA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - BD0E5E3EFB0F4CCE246B60BB04FAB85B /* Debug */, - A9EEBF12B0E3733A640B1F7870912751 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 8DE5143C03248BB6CD542DE3963D6F3A /* Debug */, - 9E406C6AAF85E580207CD97B0044DEAB /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 7B5018230A2DA353B0B36C08868324D1 /* Build configuration list for PBXNativeTarget "Pods-DiaryApp" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 61C156878AA0F739377C03E2D20A62BF /* Debug */, - ED4DC8D666B2B63C25FA4E972D98AD8B /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - D7761A54AFA2998F27E0BC2FACC2EB53 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - B7D9E7CD650F798EC835C67DACFEBC4F /* Debug */, - F5F3306F2C09AB4B623C805497E28D51 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; -} diff --git a/Pods/SwiftyJSON/LICENSE b/Pods/SwiftyJSON/LICENSE deleted file mode 100644 index 68e3fd7..0000000 --- a/Pods/SwiftyJSON/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Ruoyu Fu - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Pods/SwiftyJSON/README.md b/Pods/SwiftyJSON/README.md deleted file mode 100644 index 2465415..0000000 --- a/Pods/SwiftyJSON/README.md +++ /dev/null @@ -1,560 +0,0 @@ -# SwiftyJSON - -[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0%20%7C%20macOS%2010.10%20%7C%20tvOS%209.0%20%7C%20watchOS%203.0-F28D00.svg) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com) - -SwiftyJSON makes it easy to deal with JSON data in Swift. - -Platform | Build Status ----------| --------------| -*OS | [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) | -[Linux](https://github.com/IBM-Swift/SwiftyJSON) | [![Build Status](https://travis-ci.org/IBM-Swift/SwiftyJSON.svg?branch=master)](https://travis-ci.org/IBM-Swift/SwiftyJSON) | - - -1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) -2. [Requirements](#requirements) -3. [Integration](#integration) -4. [Usage](#usage) - - [Initialization](#initialization) - - [Subscript](#subscript) - - [Loop](#loop) - - [Error](#error) - - [Optional getter](#optional-getter) - - [Non-optional getter](#non-optional-getter) - - [Setter](#setter) - - [Raw object](#raw-object) - - [Literal convertibles](#literal-convertibles) - - [Merging](#merging) -5. [Work with Alamofire](#work-with-alamofire) -6. [Work with Moya](#work-with-moya) -7. [SwiftyJSON Model Generator](#swiftyjson-model-generator) - - -## Why is the typical JSON handling in Swift NOT good? - -Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. - -Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to [Twitter's API](https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline)). - -The code would look like this: - -```swift -if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], - let user = statusesArray[0]["user"] as? [String: Any], - let username = user["name"] as? String { - // Finally we got the username -} -``` - -It's not good. - -Even if we use optional chaining, it would be messy: - -```swift -if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], - let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String { - // There's our username -} -``` - -An unreadable mess--for something that should really be simple! - -With SwiftyJSON all you have to do is: - -```swift -let json = JSON(data: dataFromNetworking) -if let userName = json[0]["user"]["name"].string { - //Now you got your value -} -``` - -And don't worry about the Optional Wrapping thing. It's done for you automatically. - -```swift -let json = JSON(data: dataFromNetworking) -let result = json[999999]["wrong_key"]["wrong_name"] -if let userName = result.string { - //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety -} else { - //Print the error - print(result.error) -} -``` - -## Requirements - -- iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+ -- Xcode 8 - -## Integration - -#### CocoaPods (iOS 8+, OS X 10.9+) - -You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON` by adding it to your `Podfile`: - -```ruby -platform :ios, '8.0' -use_frameworks! - -target 'MyApp' do - pod 'SwiftyJSON', '~> 4.0' -end -``` - -#### Carthage (iOS 8+, OS X 10.9+) - -You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: - -``` -github "SwiftyJSON/SwiftyJSON" ~> 4.0 -``` - -If you use Carthage to build your dependencies, make sure you have added `SwiftyJSON.framework` to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase. - -#### Swift Package Manager - -You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: - -```swift -// swift-tools-version:4.0 -import PackageDescription - -let package = Package( - name: "YOUR_PROJECT_NAME", - dependencies: [ - .package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", from: "4.0.0"), - ] -) -``` -Then run `swift build` whenever you get prepared. - -#### Manually (iOS 7+, OS X 10.9+) - -To use this library in your project manually you may: - -1. for Projects, just drag SwiftyJSON.swift to the project tree -2. for Workspaces, include the whole SwiftyJSON.xcodeproj - -## Usage - -#### Initialization - -```swift -import SwiftyJSON -``` - -```swift -let json = JSON(data: dataFromNetworking) -``` -Or - -```swift -let json = JSON(jsonObject) -``` -Or - -```swift -if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) { - let json = JSON(data: dataFromString) -} -``` - -#### Subscript - -```swift -// Getting a double from a JSON Array -let name = json[0].double -``` - -```swift -// Getting an array of string from a JSON Array -let arrayNames = json["users"].arrayValue.map {$0["name"].stringValue} -``` - -```swift -// Getting a string from a JSON Dictionary -let name = json["name"].stringValue -``` - -```swift -// Getting a string using a path to the element -let path: [JSONSubscriptType] = [1,"list",2,"name"] -let name = json[path].string -// Just the same -let name = json[1]["list"][2]["name"].string -// Alternatively -let name = json[1,"list",2,"name"].string -``` - -```swift -// With a hard way -let name = json[].string -``` - -```swift -// With a custom way -let keys:[JSONSubscriptType] = [1,"list",2,"name"] -let name = json[keys].string -``` - -#### Loop - -```swift -// If json is .Dictionary -for (key,subJson):(String, JSON) in json { - // Do something you want -} -``` - -*The first element is always a String, even if the JSON is an Array* - -```swift -// If json is .Array -// The `index` is 0.. = json["list"].arrayValue -``` - -```swift -// If not a Dictionary or nil, return [:] -let user: Dictionary = json["user"].dictionaryValue -``` - -#### Setter - -```swift -json["name"] = JSON("new-name") -json[0] = JSON(1) -``` - -```swift -json["id"].int = 1234567890 -json["coordinate"].double = 8766.766 -json["name"].string = "Jack" -json.arrayObject = [1,2,3,4] -json.dictionaryObject = ["name":"Jack", "age":25] -``` - -#### Raw object - -```swift -let rawObject: Any = json.object -``` - -```swift -let rawValue: Any = json.rawValue -``` - -```swift -//convert the JSON to raw NSData -do { - let rawData = try json.rawData() - //Do something you want -} catch { - print("Error \(error)") -} -``` - -```swift -//convert the JSON to a raw String -if let rawString = json.rawString() { - //Do something you want -} else { - print("json.rawString is nil") -} -``` - -#### Existence - -```swift -// shows you whether value specified in JSON or not -if json["name"].exists() -``` - -#### Literal convertibles - -For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) - -```swift -// StringLiteralConvertible -let json: JSON = "I'm a json" -``` - -```swift -/ /IntegerLiteralConvertible -let json: JSON = 12345 -``` - -```swift -// BooleanLiteralConvertible -let json: JSON = true -``` - -```swift -// FloatLiteralConvertible -let json: JSON = 2.8765 -``` - -```swift -// DictionaryLiteralConvertible -let json: JSON = ["I":"am", "a":"json"] -``` - -```swift -// ArrayLiteralConvertible -let json: JSON = ["I", "am", "a", "json"] -``` - -```swift -// With subscript in array -var json: JSON = [1,2,3] -json[0] = 100 -json[1] = 200 -json[2] = 300 -json[999] = 300 // Don't worry, nothing will happen -``` - -```swift -// With subscript in dictionary -var json: JSON = ["name": "Jack", "age": 25] -json["name"] = "Mike" -json["age"] = "25" // It's OK to set String -json["address"] = "L.A." // Add the "address": "L.A." in json -``` - -```swift -// Array & Dictionary -var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] -json["list"][3]["what"] = "that" -json["list",3,"what"] = "that" -let path: [JSONSubscriptType] = ["list",3,"what"] -json[path] = "that" -``` - -```swift -// With other JSON objects -let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] -let auth: JSON = [ - "user": user.object, // use user.object instead of just user - "apikey": "supersecretapitoken" -] -``` - -#### Merging - -It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the `other` JSON. - -If both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment: - -- In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. -- In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. - -In a case where two fields in a JSON have different types, the value will get always overwritten. - -There are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy. - -```swift -let original: JSON = [ - "first_name": "John", - "age": 20, - "skills": ["Coding", "Reading"], - "address": [ - "street": "Front St", - "zip": "12345", - ] -] - -let update: JSON = [ - "last_name": "Doe", - "age": 21, - "skills": ["Writing"], - "address": [ - "zip": "12342", - "city": "New York City" - ] -] - -let updated = original.merge(with: update) -// [ -// "first_name": "John", -// "last_name": "Doe", -// "age": 21, -// "skills": ["Coding", "Reading", "Writing"], -// "address": [ -// "street": "Front St", -// "zip": "12342", -// "city": "New York City" -// ] -// ] -``` - -## String representation -There are two options available: -- use the default Swift one -- use a custom one that will handle optionals well and represent `nil` as `"null"`: -```swift -let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] -let json = JSON(dict) -let representation = json.rawString(options: [.castNilToNSNull: true]) -// representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} -``` - -## Work with [Alamofire](https://github.com/Alamofire/Alamofire) - -SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: - -```swift -Alamofire.request(url, method: .get).validate().responseJSON { response in - switch response.result { - case .success(let value): - let json = JSON(value) - print("JSON: \(json)") - case .failure(let error): - print(error) - } -} -``` - -We also provide an extension of Alamofire for serializing NSData to SwiftyJSON's JSON. - -See: [Alamofire-SwiftyJSON](https://github.com/SwiftyJSON/Alamofire-SwiftyJSON) - - -## Work with [Moya](https://github.com/Moya/Moya) - -SwiftyJSON parse data to JSON: - -```swift -let provider = MoyaProvider() -provider.request(.showProducts) { result in - switch result { - case let .success(moyaResponse): - let data = moyaResponse.data - let json = JSON(data: data) // convert network data to json - print(json) - case let .failure(error): - print("error: \(error)") - } -} - -``` - -## SwiftyJSON Model Generator -Tools to generate SwiftyJSON Models -* [JSON Cafe](http://www.jsoncafe.com/) -* [JSON Export](https://github.com/Ahmed-Ali/JSONExport) diff --git a/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift b/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift deleted file mode 100644 index f7a3f08..0000000 --- a/Pods/SwiftyJSON/Source/SwiftyJSON/SwiftyJSON.swift +++ /dev/null @@ -1,1401 +0,0 @@ -// SwiftyJSON.swift -// -// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import Foundation - -// MARK: - Error -// swiftlint:disable line_length -public enum SwiftyJSONError: Int, Swift.Error { - case unsupportedType = 999 - case indexOutOfBounds = 900 - case elementTooDeep = 902 - case wrongType = 901 - case notExist = 500 - case invalidJSON = 490 -} - -extension SwiftyJSONError: CustomNSError { - - /// return the error domain of SwiftyJSONError - public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" } - - /// return the error code of SwiftyJSONError - public var errorCode: Int { return self.rawValue } - - /// return the userInfo of SwiftyJSONError - public var errorUserInfo: [String: Any] { - switch self { - case .unsupportedType: - return [NSLocalizedDescriptionKey: "It is an unsupported type."] - case .indexOutOfBounds: - return [NSLocalizedDescriptionKey: "Array Index is out of bounds."] - case .wrongType: - return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."] - case .notExist: - return [NSLocalizedDescriptionKey: "Dictionary key does not exist."] - case .invalidJSON: - return [NSLocalizedDescriptionKey: "JSON is invalid."] - case .elementTooDeep: - return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."] - } - } -} - -// MARK: - JSON Type - -/** -JSON's type definitions. - -See http://www.json.org -*/ -public enum Type: Int { - case number - case string - case bool - case array - case dictionary - case null - case unknown -} - -// MARK: - JSON Base - -public struct JSON { - - /** - Creates a JSON using the data. - - - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - - parameter opt: The JSON serialization reading options. `[]` by default. - - - returns: The created JSON - */ - public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { - let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) - self.init(jsonObject: object) - } - - /** - Creates a JSON object - - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - - - parameter object: the object - - - returns: the created JSON object - */ - public init(_ object: Any) { - switch object { - case let object as Data: - do { - try self.init(data: object) - } catch { - self.init(jsonObject: NSNull()) - } - default: - self.init(jsonObject: object) - } - } - - /** - Parses the JSON string into a JSON object - - - parameter json: the JSON string - - - returns: the created JSON object - */ - public init(parseJSON jsonString: String) { - if let data = jsonString.data(using: .utf8) { - self.init(data) - } else { - self.init(NSNull()) - } - } - - /** - Creates a JSON using the object. - - - parameter jsonObject: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - - - returns: The created JSON - */ - fileprivate init(jsonObject: Any) { - object = jsonObject - } - - /** - Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, - present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - - - parameter other: The JSON which gets merged into this JSON - - - throws `ErrorWrongType` if the other JSONs differs in type on the top level. - */ - public mutating func merge(with other: JSON) throws { - try self.merge(with: other, typecheck: true) - } - - /** - Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, - present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - - - parameter other: The JSON which gets merged into this JSON - - - throws `ErrorWrongType` if the other JSONs differs in type on the top level. - - - returns: New merged JSON - */ - public func merged(with other: JSON) throws -> JSON { - var merged = self - try merged.merge(with: other, typecheck: true) - return merged - } - - /** - Private woker function which does the actual merging - Typecheck is set to true for the first recursion level to prevent total override of the source JSON - */ - fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { - if type == other.type { - switch type { - case .dictionary: - for (key, _) in other { - try self[key].merge(with: other[key], typecheck: false) - } - case .array: - self = JSON(arrayValue + other.arrayValue) - default: - self = other - } - } else { - if typecheck { - throw SwiftyJSONError.wrongType - } else { - self = other - } - } - } - - /// Private object - fileprivate var rawArray: [Any] = [] - fileprivate var rawDictionary: [String: Any] = [:] - fileprivate var rawString: String = "" - fileprivate var rawNumber: NSNumber = 0 - fileprivate var rawNull: NSNull = NSNull() - fileprivate var rawBool: Bool = false - - /// JSON type, fileprivate setter - public fileprivate(set) var type: Type = .null - - /// Error in JSON, fileprivate setter - public fileprivate(set) var error: SwiftyJSONError? - - /// Object in JSON - public var object: Any { - get { - switch type { - case .array: return rawArray - case .dictionary: return rawDictionary - case .string: return rawString - case .number: return rawNumber - case .bool: return rawBool - default: return rawNull - } - } - set { - error = nil - switch unwrap(newValue) { - case let number as NSNumber: - if number.isBool { - type = .bool - rawBool = number.boolValue - } else { - type = .number - rawNumber = number - } - case let string as String: - type = .string - rawString = string - case _ as NSNull: - type = .null - case nil: - type = .null - case let array as [Any]: - type = .array - rawArray = array - case let dictionary as [String: Any]: - type = .dictionary - rawDictionary = dictionary - default: - type = .unknown - error = SwiftyJSONError.unsupportedType - } - } - } - - /// The static null JSON - @available(*, unavailable, renamed:"null") - public static var nullJSON: JSON { return null } - public static var null: JSON { return JSON(NSNull()) } -} - -/// Private method to unwarp an object recursively -private func unwrap(_ object: Any) -> Any { - switch object { - case let json as JSON: - return unwrap(json.object) - case let array as [Any]: - return array.map(unwrap) - case let dictionary as [String: Any]: - var d = dictionary - dictionary.forEach { pair in - d[pair.key] = unwrap(pair.value) - } - return d - default: - return object - } -} - -public enum Index: Comparable { - case array(Int) - case dictionary(DictionaryIndex) - case null - - static public func == (lhs: Index, rhs: Index) -> Bool { - switch (lhs, rhs) { - case (.array(let left), .array(let right)): return left == right - case (.dictionary(let left), .dictionary(let right)): return left == right - case (.null, .null): return true - default: return false - } - } - - static public func < (lhs: Index, rhs: Index) -> Bool { - switch (lhs, rhs) { - case (.array(let left), .array(let right)): return left < right - case (.dictionary(let left), .dictionary(let right)): return left < right - default: return false - } - } -} - -public typealias JSONIndex = Index -public typealias JSONRawIndex = Index - -extension JSON: Swift.Collection { - - public typealias Index = JSONRawIndex - - public var startIndex: Index { - switch type { - case .array: return .array(rawArray.startIndex) - case .dictionary: return .dictionary(rawDictionary.startIndex) - default: return .null - } - } - - public var endIndex: Index { - switch type { - case .array: return .array(rawArray.endIndex) - case .dictionary: return .dictionary(rawDictionary.endIndex) - default: return .null - } - } - - public func index(after i: Index) -> Index { - switch i { - case .array(let idx): return .array(rawArray.index(after: idx)) - case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) - default: return .null - } - } - - public subscript (position: Index) -> (String, JSON) { - switch position { - case .array(let idx): return (String(idx), JSON(rawArray[idx])) - case .dictionary(let idx): return (rawDictionary[idx].key, JSON(rawDictionary[idx].value)) - default: return ("", JSON.null) - } - } -} - -// MARK: - Subscript - -/** - * To mark both String and Int can be used in subscript. - */ -public enum JSONKey { - case index(Int) - case key(String) -} - -public protocol JSONSubscriptType { - var jsonKey: JSONKey { get } -} - -extension Int: JSONSubscriptType { - public var jsonKey: JSONKey { - return JSONKey.index(self) - } -} - -extension String: JSONSubscriptType { - public var jsonKey: JSONKey { - return JSONKey.key(self) - } -} - -extension JSON { - - /// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error. - fileprivate subscript(index index: Int) -> JSON { - get { - if type != .array { - var r = JSON.null - r.error = self.error ?? SwiftyJSONError.wrongType - return r - } else if rawArray.indices.contains(index) { - return JSON(rawArray[index]) - } else { - var r = JSON.null - r.error = SwiftyJSONError.indexOutOfBounds - return r - } - } - set { - if type == .array && - rawArray.indices.contains(index) && - newValue.error == nil { - rawArray[index] = newValue.object - } - } - } - - /// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. - fileprivate subscript(key key: String) -> JSON { - get { - var r = JSON.null - if type == .dictionary { - if let o = rawDictionary[key] { - r = JSON(o) - } else { - r.error = SwiftyJSONError.notExist - } - } else { - r.error = self.error ?? SwiftyJSONError.wrongType - } - return r - } - set { - if type == .dictionary && newValue.error == nil { - rawDictionary[key] = newValue.object - } - } - } - - /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. - fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { - get { - switch sub.jsonKey { - case .index(let index): return self[index: index] - case .key(let key): return self[key: key] - } - } - set { - switch sub.jsonKey { - case .index(let index): self[index: index] = newValue - case .key(let key): self[key: key] = newValue - } - } - } - - /** - Find a json in the complex data structures by using array of Int and/or String as path. - - Example: - - ``` - let json = JSON[data] - let path = [9,"list","person","name"] - let name = json[path] - ``` - - The same as: let name = json[9]["list"]["person"]["name"] - - - parameter path: The target json's path. - - - returns: Return a json found by the path or a null json with error - */ - public subscript(path: [JSONSubscriptType]) -> JSON { - get { - return path.reduce(self) { $0[sub: $1] } - } - set { - switch path.count { - case 0: return - case 1: self[sub:path[0]].object = newValue.object - default: - var aPath = path - aPath.remove(at: 0) - var nextJSON = self[sub: path[0]] - nextJSON[aPath] = newValue - self[sub: path[0]] = nextJSON - } - } - } - - /** - Find a json in the complex data structures by using array of Int and/or String as path. - - - parameter path: The target json's path. Example: - - let name = json[9,"list","person","name"] - - The same as: let name = json[9]["list"]["person"]["name"] - - - returns: Return a json found by the path or a null json with error - */ - public subscript(path: JSONSubscriptType...) -> JSON { - get { - return self[path] - } - set { - self[path] = newValue - } - } -} - -// MARK: - LiteralConvertible - -extension JSON: Swift.ExpressibleByStringLiteral { - - public init(stringLiteral value: StringLiteralType) { - self.init(value) - } - - public init(extendedGraphemeClusterLiteral value: StringLiteralType) { - self.init(value) - } - - public init(unicodeScalarLiteral value: StringLiteralType) { - self.init(value) - } -} - -extension JSON: Swift.ExpressibleByIntegerLiteral { - - public init(integerLiteral value: IntegerLiteralType) { - self.init(value) - } -} - -extension JSON: Swift.ExpressibleByBooleanLiteral { - - public init(booleanLiteral value: BooleanLiteralType) { - self.init(value) - } -} - -extension JSON: Swift.ExpressibleByFloatLiteral { - - public init(floatLiteral value: FloatLiteralType) { - self.init(value) - } -} - -extension JSON: Swift.ExpressibleByDictionaryLiteral { - public init(dictionaryLiteral elements: (String, Any)...) { - let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1}) - self.init(dictionary) - } -} - -extension JSON: Swift.ExpressibleByArrayLiteral { - - public init(arrayLiteral elements: Any...) { - self.init(elements) - } -} - -// MARK: - Raw - -extension JSON: Swift.RawRepresentable { - - public init?(rawValue: Any) { - if JSON(rawValue).type == .unknown { - return nil - } else { - self.init(rawValue) - } - } - - public var rawValue: Any { - return object - } - - public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { - guard JSONSerialization.isValidJSONObject(object) else { - throw SwiftyJSONError.invalidJSON - } - - return try JSONSerialization.data(withJSONObject: object, options: opt) - } - - public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { - do { - return try _rawString(encoding, options: [.jsonSerialization: opt]) - } catch { - print("Could not serialize object to JSON because:", error.localizedDescription) - return nil - } - } - - public func rawString(_ options: [writingOptionsKeys: Any]) -> String? { - let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 - let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 - do { - return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) - } catch { - print("Could not serialize object to JSON because:", error.localizedDescription) - return nil - } - } - - fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { - guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON } - switch type { - case .dictionary: - do { - if !(options[.castNilToNSNull] as? Bool ?? false) { - let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted - let data = try rawData(options: jsonOption) - return String(data: data, encoding: encoding) - } - - guard let dict = object as? [String: Any?] else { - return nil - } - let body = try dict.keys.map { key throws -> String in - guard let value = dict[key] else { - return "\"\(key)\": null" - } - guard let unwrappedValue = value else { - return "\"\(key)\": null" - } - - let nestedValue = JSON(unwrappedValue) - guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { - throw SwiftyJSONError.elementTooDeep - } - if nestedValue.type == .string { - return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" - } else { - return "\"\(key)\": \(nestedString)" - } - } - - return "{\(body.joined(separator: ","))}" - } catch _ { - return nil - } - case .array: - do { - if !(options[.castNilToNSNull] as? Bool ?? false) { - let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted - let data = try rawData(options: jsonOption) - return String(data: data, encoding: encoding) - } - - guard let array = object as? [Any?] else { - return nil - } - let body = try array.map { value throws -> String in - guard let unwrappedValue = value else { - return "null" - } - - let nestedValue = JSON(unwrappedValue) - guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { - throw SwiftyJSONError.invalidJSON - } - if nestedValue.type == .string { - return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" - } else { - return nestedString - } - } - - return "[\(body.joined(separator: ","))]" - } catch _ { - return nil - } - case .string: return rawString - case .number: return rawNumber.stringValue - case .bool: return rawBool.description - case .null: return "null" - default: return nil - } - } -} - -// MARK: - Printable, DebugPrintable - -extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { - - public var description: String { - return rawString(options: .prettyPrinted) ?? "unknown" - } - - public var debugDescription: String { - return description - } -} - -// MARK: - Array - -extension JSON { - - //Optional [JSON] - public var array: [JSON]? { - return type == .array ? rawArray.map { JSON($0) } : nil - } - - //Non-optional [JSON] - public var arrayValue: [JSON] { - return self.array ?? [] - } - - //Optional [Any] - public var arrayObject: [Any]? { - get { - switch type { - case .array: return rawArray - default: return nil - } - } - set { - self.object = newValue ?? NSNull() - } - } -} - -// MARK: - Dictionary - -extension JSON { - - //Optional [String : JSON] - public var dictionary: [String: JSON]? { - if type == .dictionary { - var d = [String: JSON](minimumCapacity: rawDictionary.count) - rawDictionary.forEach { pair in - d[pair.key] = JSON(pair.value) - } - return d - } else { - return nil - } - } - - //Non-optional [String : JSON] - public var dictionaryValue: [String: JSON] { - return dictionary ?? [:] - } - - //Optional [String : Any] - - public var dictionaryObject: [String: Any]? { - get { - switch type { - case .dictionary: return rawDictionary - default: return nil - } - } - set { - object = newValue ?? NSNull() - } - } -} - -// MARK: - Bool - -extension JSON { // : Swift.Bool - - //Optional bool - public var bool: Bool? { - get { - switch type { - case .bool: return rawBool - default: return nil - } - } - set { - object = newValue ?? NSNull() - } - } - - //Non-optional bool - public var boolValue: Bool { - get { - switch type { - case .bool: return rawBool - case .number: return rawNumber.boolValue - case .string: return ["true", "y", "t", "yes", "1"].contains { rawString.caseInsensitiveCompare($0) == .orderedSame } - default: return false - } - } - set { - object = newValue - } - } -} - -// MARK: - String - -extension JSON { - - //Optional string - public var string: String? { - get { - switch type { - case .string: return object as? String - default: return nil - } - } - set { - object = newValue ?? NSNull() - } - } - - //Non-optional string - public var stringValue: String { - get { - switch type { - case .string: return object as? String ?? "" - case .number: return rawNumber.stringValue - case .bool: return (object as? Bool).map { String($0) } ?? "" - default: return "" - } - } - set { - object = newValue - } - } -} - -// MARK: - Number - -extension JSON { - - //Optional number - public var number: NSNumber? { - get { - switch type { - case .number: return rawNumber - case .bool: return NSNumber(value: rawBool ? 1 : 0) - default: return nil - } - } - set { - object = newValue ?? NSNull() - } - } - - //Non-optional number - public var numberValue: NSNumber { - get { - switch type { - case .string: - let decimal = NSDecimalNumber(string: object as? String) - return decimal == .notANumber ? .zero : decimal - case .number: return object as? NSNumber ?? NSNumber(value: 0) - case .bool: return NSNumber(value: rawBool ? 1 : 0) - default: return NSNumber(value: 0.0) - } - } - set { - object = newValue - } - } -} - -// MARK: - Null - -extension JSON { - - public var null: NSNull? { - set { - object = NSNull() - } - get { - switch type { - case .null: return rawNull - default: return nil - } - } - } - public func exists() -> Bool { - if let errorValue = error, (400...1000).contains(errorValue.errorCode) { - return false - } - return true - } -} - -// MARK: - URL - -extension JSON { - - //Optional URL - public var url: URL? { - get { - switch type { - case .string: - // Check for existing percent escapes first to prevent double-escaping of % character - if rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { - return Foundation.URL(string: rawString) - } else if let encodedString_ = rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { - // We have to use `Foundation.URL` otherwise it conflicts with the variable name. - return Foundation.URL(string: encodedString_) - } else { - return nil - } - default: - return nil - } - } - set { - object = newValue?.absoluteString ?? NSNull() - } - } -} - -// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 - -extension JSON { - - public var double: Double? { - get { - return number?.doubleValue - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var doubleValue: Double { - get { - return numberValue.doubleValue - } - set { - object = NSNumber(value: newValue) - } - } - - public var float: Float? { - get { - return number?.floatValue - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var floatValue: Float { - get { - return numberValue.floatValue - } - set { - object = NSNumber(value: newValue) - } - } - - public var int: Int? { - get { - return number?.intValue - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var intValue: Int { - get { - return numberValue.intValue - } - set { - object = NSNumber(value: newValue) - } - } - - public var uInt: UInt? { - get { - return number?.uintValue - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var uIntValue: UInt { - get { - return numberValue.uintValue - } - set { - object = NSNumber(value: newValue) - } - } - - public var int8: Int8? { - get { - return number?.int8Value - } - set { - if let newValue = newValue { - object = NSNumber(value: Int(newValue)) - } else { - object = NSNull() - } - } - } - - public var int8Value: Int8 { - get { - return numberValue.int8Value - } - set { - object = NSNumber(value: Int(newValue)) - } - } - - public var uInt8: UInt8? { - get { - return number?.uint8Value - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var uInt8Value: UInt8 { - get { - return numberValue.uint8Value - } - set { - object = NSNumber(value: newValue) - } - } - - public var int16: Int16? { - get { - return number?.int16Value - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var int16Value: Int16 { - get { - return numberValue.int16Value - } - set { - object = NSNumber(value: newValue) - } - } - - public var uInt16: UInt16? { - get { - return number?.uint16Value - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var uInt16Value: UInt16 { - get { - return numberValue.uint16Value - } - set { - object = NSNumber(value: newValue) - } - } - - public var int32: Int32? { - get { - return number?.int32Value - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var int32Value: Int32 { - get { - return numberValue.int32Value - } - set { - object = NSNumber(value: newValue) - } - } - - public var uInt32: UInt32? { - get { - return number?.uint32Value - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var uInt32Value: UInt32 { - get { - return numberValue.uint32Value - } - set { - object = NSNumber(value: newValue) - } - } - - public var int64: Int64? { - get { - return number?.int64Value - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var int64Value: Int64 { - get { - return numberValue.int64Value - } - set { - object = NSNumber(value: newValue) - } - } - - public var uInt64: UInt64? { - get { - return number?.uint64Value - } - set { - if let newValue = newValue { - object = NSNumber(value: newValue) - } else { - object = NSNull() - } - } - } - - public var uInt64Value: UInt64 { - get { - return numberValue.uint64Value - } - set { - object = NSNumber(value: newValue) - } - } -} - -// MARK: - Comparable - -extension JSON: Swift.Comparable {} - -public func == (lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): return lhs.rawNumber == rhs.rawNumber - case (.string, .string): return lhs.rawString == rhs.rawString - case (.bool, .bool): return lhs.rawBool == rhs.rawBool - case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.null, .null): return true - default: return false - } -} - -public func <= (lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): return lhs.rawNumber <= rhs.rawNumber - case (.string, .string): return lhs.rawString <= rhs.rawString - case (.bool, .bool): return lhs.rawBool == rhs.rawBool - case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.null, .null): return true - default: return false - } -} - -public func >= (lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): return lhs.rawNumber >= rhs.rawNumber - case (.string, .string): return lhs.rawString >= rhs.rawString - case (.bool, .bool): return lhs.rawBool == rhs.rawBool - case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray - case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary - case (.null, .null): return true - default: return false - } -} - -public func > (lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): return lhs.rawNumber > rhs.rawNumber - case (.string, .string): return lhs.rawString > rhs.rawString - default: return false - } -} - -public func < (lhs: JSON, rhs: JSON) -> Bool { - - switch (lhs.type, rhs.type) { - case (.number, .number): return lhs.rawNumber < rhs.rawNumber - case (.string, .string): return lhs.rawString < rhs.rawString - default: return false - } -} - -private let trueNumber = NSNumber(value: true) -private let falseNumber = NSNumber(value: false) -private let trueObjCType = String(cString: trueNumber.objCType) -private let falseObjCType = String(cString: falseNumber.objCType) - -// MARK: - NSNumber: Comparable - -extension NSNumber { - fileprivate var isBool: Bool { - let objCType = String(cString: self.objCType) - if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { - return true - } else { - return false - } - } -} - -func == (lhs: NSNumber, rhs: NSNumber) -> Bool { - switch (lhs.isBool, rhs.isBool) { - case (false, true): return false - case (true, false): return false - default: return lhs.compare(rhs) == .orderedSame - } -} - -func != (lhs: NSNumber, rhs: NSNumber) -> Bool { - return !(lhs == rhs) -} - -func < (lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): return false - case (true, false): return false - default: return lhs.compare(rhs) == .orderedAscending - } -} - -func > (lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): return false - case (true, false): return false - default: return lhs.compare(rhs) == ComparisonResult.orderedDescending - } -} - -func <= (lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): return false - case (true, false): return false - default: return lhs.compare(rhs) != .orderedDescending - } -} - -func >= (lhs: NSNumber, rhs: NSNumber) -> Bool { - - switch (lhs.isBool, rhs.isBool) { - case (false, true): return false - case (true, false): return false - default: return lhs.compare(rhs) != .orderedAscending - } -} - -public enum writingOptionsKeys { - case jsonSerialization - case castNilToNSNull - case maxObjextDepth - case encoding -} - -// MARK: - JSON: Codable -extension JSON: Codable { - private static var codableTypes: [Codable.Type] { - return [ - Bool.self, - Int.self, - Int8.self, - Int16.self, - Int32.self, - Int64.self, - UInt.self, - UInt8.self, - UInt16.self, - UInt32.self, - UInt64.self, - Double.self, - String.self, - [JSON].self, - [String: JSON].self - ] - } - public init(from decoder: Decoder) throws { - var object: Any? - - if let container = try? decoder.singleValueContainer(), !container.decodeNil() { - for type in JSON.codableTypes { - if object != nil { - break - } - // try to decode value - switch type { - case let boolType as Bool.Type: - object = try? container.decode(boolType) - case let intType as Int.Type: - object = try? container.decode(intType) - case let int8Type as Int8.Type: - object = try? container.decode(int8Type) - case let int32Type as Int32.Type: - object = try? container.decode(int32Type) - case let int64Type as Int64.Type: - object = try? container.decode(int64Type) - case let uintType as UInt.Type: - object = try? container.decode(uintType) - case let uint8Type as UInt8.Type: - object = try? container.decode(uint8Type) - case let uint16Type as UInt16.Type: - object = try? container.decode(uint16Type) - case let uint32Type as UInt32.Type: - object = try? container.decode(uint32Type) - case let uint64Type as UInt64.Type: - object = try? container.decode(uint64Type) - case let doubleType as Double.Type: - object = try? container.decode(doubleType) - case let stringType as String.Type: - object = try? container.decode(stringType) - case let jsonValueArrayType as [JSON].Type: - object = try? container.decode(jsonValueArrayType) - case let jsonValueDictType as [String: JSON].Type: - object = try? container.decode(jsonValueDictType) - default: - break - } - } - } - self.init(object ?? NSNull()) - } - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - if object is NSNull { - try container.encodeNil() - return - } - switch object { - case let intValue as Int: - try container.encode(intValue) - case let int8Value as Int8: - try container.encode(int8Value) - case let int32Value as Int32: - try container.encode(int32Value) - case let int64Value as Int64: - try container.encode(int64Value) - case let uintValue as UInt: - try container.encode(uintValue) - case let uint8Value as UInt8: - try container.encode(uint8Value) - case let uint16Value as UInt16: - try container.encode(uint16Value) - case let uint32Value as UInt32: - try container.encode(uint32Value) - case let uint64Value as UInt64: - try container.encode(uint64Value) - case let doubleValue as Double: - try container.encode(doubleValue) - case let boolValue as Bool: - try container.encode(boolValue) - case let stringValue as String: - try container.encode(stringValue) - case is [Any]: - let jsonValueArray = array ?? [] - try container.encode(jsonValueArray) - case is [String: Any]: - let jsonValueDictValue = dictionary ?? [:] - try container.encode(jsonValueDictValue) - default: - break - } - } -} diff --git a/Pods/Target Support Files/Alamofire/Alamofire-Info.plist b/Pods/Target Support Files/Alamofire/Alamofire-Info.plist deleted file mode 100644 index b22a6a3..0000000 --- a/Pods/Target Support Files/Alamofire/Alamofire-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - ${PODS_DEVELOPMENT_LANGUAGE} - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 5.8.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m deleted file mode 100644 index a6c4594..0000000 --- a/Pods/Target Support Files/Alamofire/Alamofire-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Alamofire : NSObject -@end -@implementation PodsDummy_Alamofire -@end diff --git a/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch deleted file mode 100644 index beb2a24..0000000 --- a/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - diff --git a/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h deleted file mode 100644 index 00014e3..0000000 --- a/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double AlamofireVersionNumber; -FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; - diff --git a/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig b/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig deleted file mode 100644 index dbfd4d1..0000000 --- a/Pods/Target Support Files/Alamofire/Alamofire.debug.xcconfig +++ /dev/null @@ -1,15 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift -OTHER_LDFLAGS = $(inherited) -framework "CFNetwork" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire -PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/Pods/Target Support Files/Alamofire/Alamofire.modulemap deleted file mode 100644 index d1f125f..0000000 --- a/Pods/Target Support Files/Alamofire/Alamofire.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Alamofire { - umbrella header "Alamofire-umbrella.h" - - export * - module * { export * } -} diff --git a/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig b/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig deleted file mode 100644 index dbfd4d1..0000000 --- a/Pods/Target Support Files/Alamofire/Alamofire.release.xcconfig +++ /dev/null @@ -1,15 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift -OTHER_LDFLAGS = $(inherited) -framework "CFNetwork" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire -PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist deleted file mode 100644 index 19cf209..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - ${PODS_DEVELOPMENT_LANGUAGE} - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.markdown b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.markdown deleted file mode 100644 index 6c1dc97..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.markdown +++ /dev/null @@ -1,51 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: - -## Alamofire - -Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - -## SwiftyJSON - -The MIT License (MIT) - -Copyright (c) 2017 Ruoyu Fu - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.plist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.plist deleted file mode 100644 index ab49857..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-acknowledgements.plist +++ /dev/null @@ -1,89 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - License - MIT - Title - Alamofire - Type - PSGroupSpecifier - - - FooterText - The MIT License (MIT) - -Copyright (c) 2017 Ruoyu Fu - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - License - MIT - Title - SwiftyJSON - Type - PSGroupSpecifier - - - FooterText - Generated by CocoaPods - https://cocoapods.org - Title - - Type - PSGroupSpecifier - - - StringsTable - Acknowledgements - Title - Acknowledgements - - diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-dummy.m b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-dummy.m deleted file mode 100644 index dc0a239..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_DiaryApp : NSObject -@end -@implementation PodsDummy_Pods_DiaryApp -@end diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-input-files.xcfilelist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-input-files.xcfilelist deleted file mode 100644 index 0b63d92..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-input-files.xcfilelist +++ /dev/null @@ -1,3 +0,0 @@ -${PODS_ROOT}/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh -${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework -${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-output-files.xcfilelist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-output-files.xcfilelist deleted file mode 100644 index 65d4b8b..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Debug-output-files.xcfilelist +++ /dev/null @@ -1,2 +0,0 @@ -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftyJSON.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-input-files.xcfilelist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-input-files.xcfilelist deleted file mode 100644 index 0b63d92..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-input-files.xcfilelist +++ /dev/null @@ -1,3 +0,0 @@ -${PODS_ROOT}/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh -${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework -${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-output-files.xcfilelist b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-output-files.xcfilelist deleted file mode 100644 index 65d4b8b..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks-Release-output-files.xcfilelist +++ /dev/null @@ -1,2 +0,0 @@ -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftyJSON.framework \ No newline at end of file diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh deleted file mode 100755 index cf2dcd9..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-frameworks.sh +++ /dev/null @@ -1,188 +0,0 @@ -#!/bin/sh -set -e -set -u -set -o pipefail - -function on_error { - echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" -} -trap 'on_error $LINENO' ERR - -if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then - # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy - # frameworks to, so exit 0 (signalling the script phase was successful). - exit 0 -fi - -echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" -mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - -COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" -SWIFT_STDLIB_PATH="${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" -BCSYMBOLMAP_DIR="BCSymbolMaps" - - -# This protects against multiple targets copying the same framework dependency at the same time. The solution -# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html -RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") - -# Copies and strips a vendored framework -install_framework() -{ - if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then - local source="${BUILT_PRODUCTS_DIR}/$1" - elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then - local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" - elif [ -r "$1" ]; then - local source="$1" - fi - - local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - - if [ -L "${source}" ]; then - echo "Symlinked..." - source="$(readlink -f "${source}")" - fi - - if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then - # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied - find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do - echo "Installing $f" - install_bcsymbolmap "$f" "$destination" - rm "$f" - done - rmdir "${source}/${BCSYMBOLMAP_DIR}" - fi - - # Use filter instead of exclude so missing patterns don't throw errors. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" - - local basename - basename="$(basename -s .framework "$1")" - binary="${destination}/${basename}.framework/${basename}" - - if ! [ -r "$binary" ]; then - binary="${destination}/${basename}" - elif [ -L "${binary}" ]; then - echo "Destination binary is symlinked..." - dirname="$(dirname "${binary}")" - binary="${dirname}/$(readlink "${binary}")" - fi - - # Strip invalid architectures so "fat" simulator / device frameworks work on device - if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then - strip_invalid_archs "$binary" - fi - - # Resign the code if required by the build settings to avoid unstable apps - code_sign_if_enabled "${destination}/$(basename "$1")" - - # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. - if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then - local swift_runtime_libs - swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) - for lib in $swift_runtime_libs; do - echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" - rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" - code_sign_if_enabled "${destination}/${lib}" - done - fi -} -# Copies and strips a vendored dSYM -install_dsym() { - local source="$1" - warn_missing_arch=${2:-true} - if [ -r "$source" ]; then - # Copy the dSYM into the targets temp dir. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" - - local basename - basename="$(basename -s .dSYM "$source")" - binary_name="$(ls "$source/Contents/Resources/DWARF")" - binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" - - # Strip invalid architectures from the dSYM. - if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then - strip_invalid_archs "$binary" "$warn_missing_arch" - fi - if [[ $STRIP_BINARY_RETVAL == 0 ]]; then - # Move the stripped file into its final destination. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" - else - # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. - mkdir -p "${DWARF_DSYM_FOLDER_PATH}" - touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" - fi - fi -} - -# Used as a return value for each invocation of `strip_invalid_archs` function. -STRIP_BINARY_RETVAL=0 - -# Strip invalid architectures -strip_invalid_archs() { - binary="$1" - warn_missing_arch=${2:-true} - # Get architectures for current target binary - binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" - # Intersect them with the architectures we are building for - intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" - # If there are no archs supported by this binary then warn the user - if [[ -z "$intersected_archs" ]]; then - if [[ "$warn_missing_arch" == "true" ]]; then - echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." - fi - STRIP_BINARY_RETVAL=1 - return - fi - stripped="" - for arch in $binary_archs; do - if ! [[ "${ARCHS}" == *"$arch"* ]]; then - # Strip non-valid architectures in-place - lipo -remove "$arch" -output "$binary" "$binary" - stripped="$stripped $arch" - fi - done - if [[ "$stripped" ]]; then - echo "Stripped $binary of architectures:$stripped" - fi - STRIP_BINARY_RETVAL=0 -} - -# Copies the bcsymbolmap files of a vendored framework -install_bcsymbolmap() { - local bcsymbolmap_path="$1" - local destination="${BUILT_PRODUCTS_DIR}" - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" -} - -# Signs a framework with the provided identity -code_sign_if_enabled() { - if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then - # Use the current code_sign_identity - echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" - local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" - - if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - code_sign_cmd="$code_sign_cmd &" - fi - echo "$code_sign_cmd" - eval "$code_sign_cmd" - fi -} - -if [[ "$CONFIGURATION" == "Debug" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" - install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" -fi -if [[ "$CONFIGURATION" == "Release" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" - install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" -fi -if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - wait -fi diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-umbrella.h b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-umbrella.h deleted file mode 100644 index 873fb43..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double Pods_DiaryAppVersionNumber; -FOUNDATION_EXPORT const unsigned char Pods_DiaryAppVersionString[]; - diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.debug.xcconfig b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.debug.xcconfig deleted file mode 100644 index 83a54bd..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.debug.xcconfig +++ /dev/null @@ -1,15 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON/SwiftyJSON.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' -LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "SwiftyJSON" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap deleted file mode 100644 index 0aeff01..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods_DiaryApp { - umbrella header "Pods-DiaryApp-umbrella.h" - - export * - module * { export * } -} diff --git a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.release.xcconfig b/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.release.xcconfig deleted file mode 100644 index 83a54bd..0000000 --- a/Pods/Target Support Files/Pods-DiaryApp/Pods-DiaryApp.release.xcconfig +++ /dev/null @@ -1,15 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON/SwiftyJSON.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' -LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "SwiftyJSON" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist deleted file mode 100644 index 8136e62..0000000 --- a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - ${PODS_DEVELOPMENT_LANGUAGE} - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 5.0.1 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m deleted file mode 100644 index 3159bec..0000000 --- a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_SwiftyJSON : NSObject -@end -@implementation PodsDummy_SwiftyJSON -@end diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch deleted file mode 100644 index beb2a24..0000000 --- a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h deleted file mode 100644 index b627dec..0000000 --- a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double SwiftyJSONVersionNumber; -FOUNDATION_EXPORT const unsigned char SwiftyJSONVersionString[]; - diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig deleted file mode 100644 index 2ac300f..0000000 --- a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.debug.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftyJSON -PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap deleted file mode 100644 index 6f41751..0000000 --- a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module SwiftyJSON { - umbrella header "SwiftyJSON-umbrella.h" - - export * - module * { export * } -} diff --git a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig b/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig deleted file mode 100644 index 2ac300f..0000000 --- a/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.release.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftyJSON -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -LIBRARY_SEARCH_PATHS = $(inherited) "${TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_DEVELOPMENT_LANGUAGE = ${DEVELOPMENT_LANGUAGE} -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftyJSON -PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES