Initial commit; substitutions can be reviewed, no further functionality implemented yet

This commit is contained in:
Deniz Duezgoeren
2019-07-09 19:39:06 +02:00
commit 860d87f446
169 changed files with 30855 additions and 0 deletions
+742
View File
@@ -0,0 +1,742 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objects = {
/* Begin PBXBuildFile section */
1BF3A6CA97BA41C38482C1A6 /* Pods_AvH_PlanTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D9D6269E96544A9242A29611 /* Pods_AvH_PlanTests.framework */; };
2E65263AFD35D6B542E89AE4 /* Pods_AvH_Plan.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7605BB0678C9E27A1D3E9DAA /* Pods_AvH_Plan.framework */; };
A96133802299867400B541D4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A961337F2299867400B541D4 /* AppDelegate.swift */; };
A96133822299867400B541D4 /* FirstViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133812299867400B541D4 /* FirstViewController.swift */; };
A96133842299867400B541D4 /* SecondViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133832299867400B541D4 /* SecondViewController.swift */; };
A96133872299867400B541D4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A96133852299867400B541D4 /* Main.storyboard */; };
A96133892299867A00B541D4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A96133882299867A00B541D4 /* Assets.xcassets */; };
A961338C2299867A00B541D4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A961338A2299867A00B541D4 /* LaunchScreen.storyboard */; };
A96133972299867A00B541D4 /* AvH_PlanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133962299867A00B541D4 /* AvH_PlanTests.swift */; };
A96133A22299867A00B541D4 /* AvH_PlanUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133A12299867A00B541D4 /* AvH_PlanUITests.swift */; };
A96133B0229986DF00B541D4 /* CollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133AF229986DF00B541D4 /* CollectionViewCell.swift */; };
A9A3496C22D4859200F35AE0 /* SubstModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9A3496B22D4859200F35AE0 /* SubstModel.swift */; };
C736A19A44C64423F3A695B7 /* Pods_AvH_PlanUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 74EDE3D8134812AB76BEB988 /* Pods_AvH_PlanUITests.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
A96133932299867A00B541D4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = A96133742299867300B541D4 /* Project object */;
proxyType = 1;
remoteGlobalIDString = A961337B2299867300B541D4;
remoteInfo = "AvH Plan";
};
A961339E2299867A00B541D4 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = A96133742299867300B541D4 /* Project object */;
proxyType = 1;
remoteGlobalIDString = A961337B2299867300B541D4;
remoteInfo = "AvH Plan";
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
589FBD2CE6A9C73CD9B81441 /* Pods-AvH PlanUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH PlanUITests.release.xcconfig"; path = "Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.release.xcconfig"; sourceTree = "<group>"; };
74EDE3D8134812AB76BEB988 /* Pods_AvH_PlanUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AvH_PlanUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
7605BB0678C9E27A1D3E9DAA /* Pods_AvH_Plan.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AvH_Plan.framework; sourceTree = BUILT_PRODUCTS_DIR; };
A961337C2299867400B541D4 /* AvH Plan.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "AvH Plan.app"; sourceTree = BUILT_PRODUCTS_DIR; };
A961337F2299867400B541D4 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
A96133812299867400B541D4 /* FirstViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirstViewController.swift; sourceTree = "<group>"; };
A96133832299867400B541D4 /* SecondViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecondViewController.swift; sourceTree = "<group>"; };
A96133862299867400B541D4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
A96133882299867A00B541D4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
A961338B2299867A00B541D4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
A961338D2299867A00B541D4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
A96133922299867A00B541D4 /* AvH PlanTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AvH PlanTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
A96133962299867A00B541D4 /* AvH_PlanTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvH_PlanTests.swift; sourceTree = "<group>"; };
A96133982299867A00B541D4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
A961339D2299867A00B541D4 /* AvH PlanUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AvH PlanUITests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
A96133A12299867A00B541D4 /* AvH_PlanUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvH_PlanUITests.swift; sourceTree = "<group>"; };
A96133A32299867A00B541D4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
A96133AF229986DF00B541D4 /* CollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CollectionViewCell.swift; sourceTree = "<group>"; };
A9A3496B22D4859200F35AE0 /* SubstModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubstModel.swift; sourceTree = "<group>"; };
C6EC6ACE7893F2BB0A157817 /* Pods-AvH Plan.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH Plan.release.xcconfig"; path = "Target Support Files/Pods-AvH Plan/Pods-AvH Plan.release.xcconfig"; sourceTree = "<group>"; };
D9D6269E96544A9242A29611 /* Pods_AvH_PlanTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AvH_PlanTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
E596AED9E99670CBF1B6F49E /* Pods-AvH Plan.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH Plan.debug.xcconfig"; path = "Target Support Files/Pods-AvH Plan/Pods-AvH Plan.debug.xcconfig"; sourceTree = "<group>"; };
F0769608C3BBAAEBCCA008F6 /* Pods-AvH PlanTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH PlanTests.debug.xcconfig"; path = "Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.debug.xcconfig"; sourceTree = "<group>"; };
F0FCFF5036EBDC7E5902C52D /* Pods-AvH PlanTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH PlanTests.release.xcconfig"; path = "Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.release.xcconfig"; sourceTree = "<group>"; };
F8A7FDE248283EAE3C45555A /* Pods-AvH PlanUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH PlanUITests.debug.xcconfig"; path = "Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.debug.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
A96133792299867300B541D4 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
2E65263AFD35D6B542E89AE4 /* Pods_AvH_Plan.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A961338F2299867A00B541D4 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
1BF3A6CA97BA41C38482C1A6 /* Pods_AvH_PlanTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A961339A2299867A00B541D4 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C736A19A44C64423F3A695B7 /* Pods_AvH_PlanUITests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
0FCE2FEB0B034FB375960A54 /* Pods */ = {
isa = PBXGroup;
children = (
E596AED9E99670CBF1B6F49E /* Pods-AvH Plan.debug.xcconfig */,
C6EC6ACE7893F2BB0A157817 /* Pods-AvH Plan.release.xcconfig */,
F0769608C3BBAAEBCCA008F6 /* Pods-AvH PlanTests.debug.xcconfig */,
F0FCFF5036EBDC7E5902C52D /* Pods-AvH PlanTests.release.xcconfig */,
F8A7FDE248283EAE3C45555A /* Pods-AvH PlanUITests.debug.xcconfig */,
589FBD2CE6A9C73CD9B81441 /* Pods-AvH PlanUITests.release.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
A7F8C8C9CE4E171D98EE659D /* Frameworks */ = {
isa = PBXGroup;
children = (
7605BB0678C9E27A1D3E9DAA /* Pods_AvH_Plan.framework */,
D9D6269E96544A9242A29611 /* Pods_AvH_PlanTests.framework */,
74EDE3D8134812AB76BEB988 /* Pods_AvH_PlanUITests.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
A96133732299867300B541D4 = {
isa = PBXGroup;
children = (
A961337E2299867400B541D4 /* AvH Plan */,
A96133952299867A00B541D4 /* AvH PlanTests */,
A96133A02299867A00B541D4 /* AvH PlanUITests */,
A961337D2299867400B541D4 /* Products */,
0FCE2FEB0B034FB375960A54 /* Pods */,
A7F8C8C9CE4E171D98EE659D /* Frameworks */,
);
sourceTree = "<group>";
};
A961337D2299867400B541D4 /* Products */ = {
isa = PBXGroup;
children = (
A961337C2299867400B541D4 /* AvH Plan.app */,
A96133922299867A00B541D4 /* AvH PlanTests.xctest */,
A961339D2299867A00B541D4 /* AvH PlanUITests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
A961337E2299867400B541D4 /* AvH Plan */ = {
isa = PBXGroup;
children = (
A961337F2299867400B541D4 /* AppDelegate.swift */,
A96133812299867400B541D4 /* FirstViewController.swift */,
A9A3496B22D4859200F35AE0 /* SubstModel.swift */,
A96133832299867400B541D4 /* SecondViewController.swift */,
A96133852299867400B541D4 /* Main.storyboard */,
A96133882299867A00B541D4 /* Assets.xcassets */,
A961338A2299867A00B541D4 /* LaunchScreen.storyboard */,
A961338D2299867A00B541D4 /* Info.plist */,
A96133AF229986DF00B541D4 /* CollectionViewCell.swift */,
);
path = "AvH Plan";
sourceTree = "<group>";
};
A96133952299867A00B541D4 /* AvH PlanTests */ = {
isa = PBXGroup;
children = (
A96133962299867A00B541D4 /* AvH_PlanTests.swift */,
A96133982299867A00B541D4 /* Info.plist */,
);
path = "AvH PlanTests";
sourceTree = "<group>";
};
A96133A02299867A00B541D4 /* AvH PlanUITests */ = {
isa = PBXGroup;
children = (
A96133A12299867A00B541D4 /* AvH_PlanUITests.swift */,
A96133A32299867A00B541D4 /* Info.plist */,
);
path = "AvH PlanUITests";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
A961337B2299867300B541D4 /* AvH Plan */ = {
isa = PBXNativeTarget;
buildConfigurationList = A96133A62299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH Plan" */;
buildPhases = (
BD3857CC61F238E4A90FF1BA /* [CP] Check Pods Manifest.lock */,
A96133782299867300B541D4 /* Sources */,
A96133792299867300B541D4 /* Frameworks */,
A961337A2299867300B541D4 /* Resources */,
D4638A8231BADABB6CD590D7 /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = "AvH Plan";
productName = "AvH Plan";
productReference = A961337C2299867400B541D4 /* AvH Plan.app */;
productType = "com.apple.product-type.application";
};
A96133912299867A00B541D4 /* AvH PlanTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = A96133A92299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH PlanTests" */;
buildPhases = (
65F085C1A4E8355ADC705123 /* [CP] Check Pods Manifest.lock */,
A961338E2299867A00B541D4 /* Sources */,
A961338F2299867A00B541D4 /* Frameworks */,
A96133902299867A00B541D4 /* Resources */,
);
buildRules = (
);
dependencies = (
A96133942299867A00B541D4 /* PBXTargetDependency */,
);
name = "AvH PlanTests";
productName = "AvH PlanTests";
productReference = A96133922299867A00B541D4 /* AvH PlanTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
A961339C2299867A00B541D4 /* AvH PlanUITests */ = {
isa = PBXNativeTarget;
buildConfigurationList = A96133AC2299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH PlanUITests" */;
buildPhases = (
68D555593A47B6FCAD9D4C33 /* [CP] Check Pods Manifest.lock */,
A96133992299867A00B541D4 /* Sources */,
A961339A2299867A00B541D4 /* Frameworks */,
A961339B2299867A00B541D4 /* Resources */,
);
buildRules = (
);
dependencies = (
A961339F2299867A00B541D4 /* PBXTargetDependency */,
);
name = "AvH PlanUITests";
productName = "AvH PlanUITests";
productReference = A961339D2299867A00B541D4 /* AvH PlanUITests.xctest */;
productType = "com.apple.product-type.bundle.ui-testing";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
A96133742299867300B541D4 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1020;
LastUpgradeCheck = 1020;
ORGANIZATIONNAME = "Deniz Duezgoeren";
TargetAttributes = {
A961337B2299867300B541D4 = {
CreatedOnToolsVersion = 10.2;
};
A96133912299867A00B541D4 = {
CreatedOnToolsVersion = 10.2;
TestTargetID = A961337B2299867300B541D4;
};
A961339C2299867A00B541D4 = {
CreatedOnToolsVersion = 10.2;
TestTargetID = A961337B2299867300B541D4;
};
};
};
buildConfigurationList = A96133772299867300B541D4 /* Build configuration list for PBXProject "AvH Plan" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = A96133732299867300B541D4;
productRefGroup = A961337D2299867400B541D4 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
A961337B2299867300B541D4 /* AvH Plan */,
A96133912299867A00B541D4 /* AvH PlanTests */,
A961339C2299867A00B541D4 /* AvH PlanUITests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
A961337A2299867300B541D4 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A961338C2299867A00B541D4 /* LaunchScreen.storyboard in Resources */,
A96133892299867A00B541D4 /* Assets.xcassets in Resources */,
A96133872299867400B541D4 /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A96133902299867A00B541D4 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
A961339B2299867A00B541D4 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
65F085C1A4E8355ADC705123 /* [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-AvH PlanTests-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;
};
68D555593A47B6FCAD9D4C33 /* [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-AvH PlanUITests-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;
};
BD3857CC61F238E4A90FF1BA /* [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-AvH Plan-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;
};
D4638A8231BADABB6CD590D7 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_ROOT}/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-frameworks.sh",
"${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework",
"${BUILT_PRODUCTS_DIR}/Kanna/Kanna.framework",
"${BUILT_PRODUCTS_DIR}/SwiftSoup/SwiftSoup.framework",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
);
outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Kanna.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftSoup.framework",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
A96133782299867300B541D4 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A96133842299867400B541D4 /* SecondViewController.swift in Sources */,
A96133802299867400B541D4 /* AppDelegate.swift in Sources */,
A9A3496C22D4859200F35AE0 /* SubstModel.swift in Sources */,
A96133B0229986DF00B541D4 /* CollectionViewCell.swift in Sources */,
A96133822299867400B541D4 /* FirstViewController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A961338E2299867A00B541D4 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A96133972299867A00B541D4 /* AvH_PlanTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
A96133992299867A00B541D4 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A96133A22299867A00B541D4 /* AvH_PlanUITests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
A96133942299867A00B541D4 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = A961337B2299867300B541D4 /* AvH Plan */;
targetProxy = A96133932299867A00B541D4 /* PBXContainerItemProxy */;
};
A961339F2299867A00B541D4 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = A961337B2299867300B541D4 /* AvH Plan */;
targetProxy = A961339E2299867A00B541D4 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
A96133852299867400B541D4 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
A96133862299867400B541D4 /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
A961338A2299867A00B541D4 /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
A961338B2299867A00B541D4 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
A96133A42299867A00B541D4 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
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_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;
CODE_SIGN_IDENTITY = "iPhone Developer";
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 = (
"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 = 12.2;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
A96133A52299867A00B541D4 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
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_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;
CODE_SIGN_IDENTITY = "iPhone Developer";
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_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 = 12.2;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
A96133A72299867A00B541D4 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = E596AED9E99670CBF1B6F49E /* Pods-AvH Plan.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = "AvH Plan/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-Plan";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
A96133A82299867A00B541D4 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = C6EC6ACE7893F2BB0A157817 /* Pods-AvH Plan.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = "AvH Plan/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-Plan";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
A96133AA2299867A00B541D4 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = F0769608C3BBAAEBCCA008F6 /* Pods-AvH PlanTests.debug.xcconfig */;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = "AvH PlanTests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-PlanTests";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/AvH Plan.app/AvH Plan";
};
name = Debug;
};
A96133AB2299867A00B541D4 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = F0FCFF5036EBDC7E5902C52D /* Pods-AvH PlanTests.release.xcconfig */;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = "AvH PlanTests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-PlanTests";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/AvH Plan.app/AvH Plan";
};
name = Release;
};
A96133AD2299867A00B541D4 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = F8A7FDE248283EAE3C45555A /* Pods-AvH PlanUITests.debug.xcconfig */;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = "AvH PlanUITests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-PlanUITests";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = "AvH Plan";
};
name = Debug;
};
A96133AE2299867A00B541D4 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 589FBD2CE6A9C73CD9B81441 /* Pods-AvH PlanUITests.release.xcconfig */;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = "AvH PlanUITests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-PlanUITests";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = "AvH Plan";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
A96133772299867300B541D4 /* Build configuration list for PBXProject "AvH Plan" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A96133A42299867A00B541D4 /* Debug */,
A96133A52299867A00B541D4 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A96133A62299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH Plan" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A96133A72299867A00B541D4 /* Debug */,
A96133A82299867A00B541D4 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A96133A92299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH PlanTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A96133AA2299867A00B541D4 /* Debug */,
A96133AB2299867A00B541D4 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A96133AC2299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH PlanUITests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A96133AD2299867A00B541D4 /* Debug */,
A96133AE2299867A00B541D4 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = A96133742299867300B541D4 /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:AvH Plan.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>AvH Plan.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>6</integer>
</dict>
</dict>
</dict>
</plist>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:AvH Plan.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict/>
</plist>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildLocationStyle</key>
<string>UseAppPreferences</string>
<key>CustomBuildLocationType</key>
<string>RelativeToDerivedData</string>
<key>DerivedDataLocationStyle</key>
<string>Default</string>
<key>EnabledFullIndexStoreVisibility</key>
<false/>
<key>IssueFilterStyle</key>
<string>ShowActiveSchemeOnly</string>
<key>LiveSourceIssuesEnabled</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
type = "0"
version = "2.0">
</Bucket>
+46
View File
@@ -0,0 +1,46 @@
//
// AppDelegate.swift
// AvH Plan
//
// Created by Deniz Duezgoeren on 25.05.19.
// Copyright © 2019 Deniz Duezgoeren. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
@@ -0,0 +1,98 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "first.pdf"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.
+12
View File
@@ -0,0 +1,12 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "second.pdf"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
+211
View File
@@ -0,0 +1,211 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="49e-Tb-3d3">
<device id="retina6_1" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14490.49"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="Stack View standard spacing" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--AvH Plan-->
<scene sceneID="hNz-n2-bh7">
<objects>
<viewController title="AvH Plan" id="9pv-A4-QxB" customClass="FirstViewController" customModule="AvH_Plan" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="tsR-hK-woN">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="MUg-vU-nTS">
<rect key="frame" x="0.0" y="44" width="414" height="769"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="1" minimumInteritemSpacing="1" id="E2H-8A-xtb">
<size key="itemSize" width="380" height="140"/>
<size key="headerReferenceSize" width="0.0" height="0.0"/>
<size key="footerReferenceSize" width="0.0" height="0.0"/>
<inset key="sectionInset" minX="0.0" minY="0.0" maxX="0.0" maxY="0.0"/>
</collectionViewFlowLayout>
<cells>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" layoutMarginsFollowReadableWidth="YES" reuseIdentifier="cell" id="xB6-Yw-wrb" customClass="CollectionViewCell" customModule="AvH_Plan" customModuleProvider="target">
<rect key="frame" x="17" y="0.0" width="380" height="100"/>
<autoresizingMask key="autoresizingMask"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO">
<rect key="frame" x="0.0" y="0.0" width="380" height="100"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="VTw-6O-uFV">
<rect key="frame" x="12" y="4" width="356" height="92"/>
<subviews>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacingType="standard" translatesAutoresizingMaskIntoConstraints="NO" id="Szc-6F-3eJ">
<rect key="frame" x="12" y="12" width="332" height="68"/>
<subviews>
<stackView opaque="NO" contentMode="scaleToFill" ambiguous="YES" spacingType="standard" translatesAutoresizingMaskIntoConstraints="NO" id="9OH-kZ-TWT">
<rect key="frame" x="0.0" y="0.0" width="332" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" ambiguous="YES" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="s5x-MZ-cys">
<rect key="frame" x="0.0" y="0.0" width="282" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" ambiguous="YES" text="Label" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="vmZ-so-40w">
<rect key="frame" x="290" y="0.0" width="42" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</stackView>
<stackView opaque="NO" contentMode="scaleToFill" ambiguous="YES" spacingType="standard" translatesAutoresizingMaskIntoConstraints="NO" id="mB7-DS-Ukk">
<rect key="frame" x="0.0" y="28.5" width="332" height="20.5"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" ambiguous="YES" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="LtQ-go-Loc">
<rect key="frame" x="0.0" y="0.0" width="42" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" ambiguous="YES" text="Label" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="8wi-UM-ePc">
<rect key="frame" x="50" y="0.0" width="282" height="20.5"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</stackView>
<stackView opaque="NO" contentMode="scaleToFill" ambiguous="YES" spacingType="standard" translatesAutoresizingMaskIntoConstraints="NO" id="Vr3-yI-gCi">
<rect key="frame" x="0.0" y="57" width="332" height="11"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" ambiguous="YES" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Lsb-TY-Oms">
<rect key="frame" x="0.0" y="0.0" width="42" height="11"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" ambiguous="YES" text="Label" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="f4b-16-4Nr">
<rect key="frame" x="50" y="0.0" width="282" height="11"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</stackView>
</subviews>
</stackView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="Szc-6F-3eJ" firstAttribute="top" secondItem="VTw-6O-uFV" secondAttribute="top" constant="12" id="NjZ-jw-oU8"/>
<constraint firstItem="Szc-6F-3eJ" firstAttribute="leading" secondItem="VTw-6O-uFV" secondAttribute="leading" constant="12" id="Vfp-6p-RI9"/>
<constraint firstAttribute="trailing" secondItem="Szc-6F-3eJ" secondAttribute="trailing" constant="12" id="lSf-Mf-Y0B"/>
<constraint firstAttribute="bottom" secondItem="Szc-6F-3eJ" secondAttribute="bottom" constant="12" id="wph-6i-6au"/>
</constraints>
</view>
</subviews>
</view>
<constraints>
<constraint firstAttribute="bottom" secondItem="VTw-6O-uFV" secondAttribute="bottom" constant="4" id="BsD-qD-oo7"/>
<constraint firstAttribute="trailing" secondItem="VTw-6O-uFV" secondAttribute="trailing" constant="12" id="Z4z-B5-ywW"/>
<constraint firstItem="VTw-6O-uFV" firstAttribute="leading" secondItem="xB6-Yw-wrb" secondAttribute="leading" constant="12" id="t7f-vA-jxE"/>
<constraint firstItem="VTw-6O-uFV" firstAttribute="top" secondItem="xB6-Yw-wrb" secondAttribute="top" constant="4" id="xoF-QP-gym"/>
</constraints>
<size key="customSize" width="380" height="100"/>
<connections>
<outlet property="additional" destination="Lsb-TY-Oms" id="UP3-K8-qjX"/>
<outlet property="course" destination="LtQ-go-Loc" id="m9l-aX-vsb"/>
<outlet property="date" destination="vmZ-so-40w" id="mag-zc-3bq"/>
<outlet property="group" destination="s5x-MZ-cys" id="4Gb-HC-UWT"/>
<outlet property="room" destination="f4b-16-4Nr" id="rGV-eH-YXp"/>
<outlet property="time" destination="8wi-UM-ePc" id="Cb9-9i-I74"/>
<outlet property="tintView" destination="VTw-6O-uFV" id="NCG-3N-nMs"/>
</connections>
</collectionViewCell>
</cells>
<connections>
<outlet property="dataSource" destination="9pv-A4-QxB" id="b8Y-vN-lRv"/>
<outlet property="delegate" destination="9pv-A4-QxB" id="USs-0B-kr6"/>
</connections>
</collectionView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="MUg-vU-nTS" firstAttribute="bottom" secondItem="PQr-Ze-W5v" secondAttribute="bottom" id="KRr-Ea-pgg"/>
<constraint firstItem="MUg-vU-nTS" firstAttribute="top" secondItem="PQr-Ze-W5v" secondAttribute="top" id="Nlm-uh-3FO"/>
<constraint firstItem="MUg-vU-nTS" firstAttribute="trailing" secondItem="PQr-Ze-W5v" secondAttribute="trailing" id="WLI-wf-EQD"/>
<constraint firstItem="MUg-vU-nTS" firstAttribute="leading" secondItem="PQr-Ze-W5v" secondAttribute="leading" id="XVI-cC-b2v"/>
</constraints>
<viewLayoutGuide key="safeArea" id="PQr-Ze-W5v"/>
</view>
<tabBarItem key="tabBarItem" title="First" image="first" id="acW-dT-cKf"/>
<connections>
<outlet property="collectionView" destination="MUg-vU-nTS" id="MW6-qD-6nu"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="W5J-7L-Pyd" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="749.27536231884062" y="-320.75892857142856"/>
</scene>
<!--Second-->
<scene sceneID="wg7-f3-ORb">
<objects>
<viewController id="8rJ-Kc-sve" customClass="SecondViewController" customModule="AvH_Plan" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="QS5-Rx-YEW">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Loaded by SecondViewController" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="NDk-cv-Gan">
<rect key="frame" x="99.5" y="477.5" width="215" height="17"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleToFill" misplaced="YES" text="Second View" textAlignment="center" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="zEq-FU-wV5">
<rect key="frame" x="-33" y="417" width="201.5" height="43"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<fontDescription key="fontDescription" type="system" pointSize="36"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="NDk-cv-Gan" firstAttribute="top" secondItem="zEq-FU-wV5" secondAttribute="bottom" constant="8" symbolic="YES" id="Day-4N-Vmt"/>
<constraint firstItem="NDk-cv-Gan" firstAttribute="centerX" secondItem="zEq-FU-wV5" secondAttribute="centerX" id="JgO-Fn-dHn"/>
<constraint firstAttribute="centerX" secondItem="zEq-FU-wV5" secondAttribute="centerX" id="qqM-NS-xev"/>
<constraint firstAttribute="centerY" secondItem="zEq-FU-wV5" secondAttribute="centerY" id="qzY-Ky-pLD"/>
</constraints>
<viewLayoutGuide key="safeArea" id="O1u-W8-tvY"/>
</view>
<tabBarItem key="tabBarItem" title="Second" image="second" id="cPa-gy-q4n"/>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="4Nw-L8-lE0" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="750" y="360"/>
</scene>
<!--AvH Plan-->
<scene sceneID="yl2-sM-qoP">
<objects>
<tabBarController title="AvH Plan" id="49e-Tb-3d3" sceneMemberID="viewController">
<tabBar key="tabBar" contentMode="scaleToFill" id="W28-zg-YXA">
<rect key="frame" x="0.0" y="975" width="768" height="49"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMinY="YES"/>
<color key="backgroundColor" red="0.0" green="0.0" blue="0.0" alpha="0.0" colorSpace="custom" customColorSpace="sRGB"/>
</tabBar>
<connections>
<segue destination="9pv-A4-QxB" kind="relationship" relationship="viewControllers" id="u7Y-xg-7CH"/>
<segue destination="8rJ-Kc-sve" kind="relationship" relationship="viewControllers" id="lzU-1b-eKA"/>
</connections>
</tabBarController>
<placeholder placeholderIdentifier="IBFirstResponder" id="HuB-VB-40B" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="0.0" y="0.0"/>
</scene>
</scenes>
<resources>
<image name="first" width="30" height="30"/>
<image name="second" width="30" height="30"/>
</resources>
</document>
+19
View File
@@ -0,0 +1,19 @@
//
// CollectionViewCell.swift
// AvH Plan
//
// Created by Deniz Duezgoeren on 25.05.19.
// Copyright © 2019 Deniz Duezgoeren. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var group: UILabel!
@IBOutlet weak var course: UILabel!
@IBOutlet weak var additional: UILabel!
@IBOutlet weak var date: UILabel!
@IBOutlet weak var time: UILabel!
@IBOutlet weak var room: UILabel!
@IBOutlet weak var tintView: UIView!
}
+168
View File
@@ -0,0 +1,168 @@
//
// FirstViewController.swift
// AvH Plan
//
// Created by Deniz Duezgoeren on 25.05.19.
// Copyright © 2019 Deniz Duezgoeren. All rights reserved.
//
import UIKit
import SwiftSoup
import Alamofire
import SQLite3
class FirstViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let reuseIdentifier = "cell"
@IBOutlet weak var collectionView: UICollectionView!
let queue = DispatchQueue(label: "work-queue")
var group: Array<String> = Array()
var course: Array<String> = Array()
var additional: Array<String> = Array()
var date: Array<String> = Array()
var time: Array<String> = Array()
var room: Array<String> = Array()
private let refreshControl = UIRefreshControl()
var db: OpaquePointer?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 10.0, *) {
collectionView.refreshControl = refreshControl
} else {
collectionView.addSubview(refreshControl)
}
refreshControl.addTarget(self, action: #selector(objDoAsync(_:)), for: .valueChanged)
refreshControl.tintColor = UIColor(red: 0.39, green: 0.71, blue: 0.96, alpha: 1.0)
refreshControl.attributedTitle = NSAttributedString(string: "Fetching the plan...")
self.refreshControl.beginRefreshing()
self.doAsync()
}
@objc private func objDoAsync(_ sender: Any) {
self.doAsync()
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0)
// let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
// layout.itemSize = CGSize(width: view.frame.size.width, height: 129)
// let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
// .appendingPathComponent("SubstDB.sqlite")
//
// if (sqlite3_open(fileURL.path, &db) != SQLITE_OK) {
// print("Error opening database connection")
// }
// sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS subst_table (id INTEGER PRIMARY KEY AUTOINCREMENT, group TEXT, course TEXT, add TEXT, date TEXT, time TEXT, room TEXT)", nil, nil, nil)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.group.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CollectionViewCell
if self.group.count != 0 {
cell.group.text = self.group[indexPath.item]
cell.course.text = self.course[indexPath.item]
cell.additional.text = self.additional[indexPath.item]
cell.date.text = self.date[indexPath.item]
cell.time.text = self.time[indexPath.item]
cell.room.text = self.room[indexPath.item]
}
// cell.backgroundColor = UIColor(red: 0.39, green: 0.71, blue: 0.96, alpha: 1.0)
cell.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
cell.tintView.backgroundColor = cell.backgroundColor
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("You selected cell#\(indexPath.item)!")
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.size.width, height: 108)
}
func doAsync() {
queue.async {
let url = "https://djd4rkn355.github.io/subst_test.html"
Alamofire.request(url).responseString { response in
if let html = response.result.value {
self.parseHTML(html: html)
}
}
}
}
func insertInDb() {
// let insertString = "INSERT INTO subst_table VALUES (?, ?, ?, ?, ?, ?)"
//
// if (sqlite3_prepare_v2(db, insertString, nil, nil, nil) != SQLITE_OK) {
// print("error db")
// }
// if (
}
func parseHTML(html: String) {
do {
let doc: Document = try SwiftSoup.parse(html)
let rows: Elements = try doc.select("tr")
self.group.removeAll()
self.date.removeAll()
self.time.removeAll()
self.course.removeAll()
self.room.removeAll()
self.additional.removeAll()
var group: String
var date: String
var time: String
var course: String
var room: String
var add: String
// sqlite3_exec(db, "DELETE FROM subst_table", nil, nil, nil)
for i in (0..<rows.size()) {
let row = rows.get(i)
let cols = try row.select("th")
group = try cols.get(0).text()
date = try cols.get(1).text()
time = try cols.get(2).text()
course = try cols.get(3).text()
room = try cols.get(4).text()
add = try cols.get(5).text()
self.group.append(group)
self.date.append(date)
self.time.append(time)
self.course.append(course)
self.room.append(room)
self.additional.append(add)
// insert()
}
self.collectionView.reloadData() // reloadData() only produces 13 cells, no more, no less
// nevermind, but it depends on the "items" array, for some reason??
// self.updateView()
self.refreshControl.endRefreshing()
// self.activityIndicatorView.stopAnimating()
} catch Exception.Error(let type, let message) {
print(type)
print(message)
} catch {
print("error")
}
}
}
+55
View File
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UIStatusBarTintParameters</key>
<dict>
<key>UINavigationBar</key>
<dict>
<key>Style</key>
<string>UIBarStyleDefault</string>
<key>Translucent</key>
<false/>
</dict>
</dict>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
+20
View File
@@ -0,0 +1,20 @@
//
// SecondViewController.swift
// AvH Plan
//
// Created by Deniz Duezgoeren on 25.05.19.
// Copyright © 2019 Deniz Duezgoeren. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
+13
View File
@@ -0,0 +1,13 @@
//
// SubstModel.swift
// AvH Plan
//
// Created by Deniz Duezgoeren on 09.07.19.
// Copyright © 2019 Deniz Duezgoeren. All rights reserved.
//
import Foundation
class SubstModel {
}
+34
View File
@@ -0,0 +1,34 @@
//
// AvH_PlanTests.swift
// AvH PlanTests
//
// Created by Deniz Duezgoeren on 25.05.19.
// Copyright © 2019 Deniz Duezgoeren. All rights reserved.
//
import XCTest
@testable import AvH_Plan
class AvH_PlanTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
+34
View File
@@ -0,0 +1,34 @@
//
// AvH_PlanUITests.swift
// AvH PlanUITests
//
// Created by Deniz Duezgoeren on 25.05.19.
// Copyright © 2019 Deniz Duezgoeren. All rights reserved.
//
import XCTest
class AvH_PlanUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests its important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
+23
View File
@@ -0,0 +1,23 @@
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'AvH Plan' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for AvH Plan
pod 'SwiftSoup'
pod 'Kanna'
pod 'Alamofire'
target 'AvH PlanTests' do
inherit! :search_paths
# Pods for testing
end
target 'AvH PlanUITests' do
inherit! :search_paths
# Pods for testing
end
end
+24
View File
@@ -0,0 +1,24 @@
PODS:
- Alamofire (4.8.2)
- Kanna (5.0.0)
- SwiftSoup (1.7.4)
DEPENDENCIES:
- Alamofire
- Kanna
- SwiftSoup
SPEC REPOS:
https://github.com/cocoapods/specs.git:
- Alamofire
- Kanna
- SwiftSoup
SPEC CHECKSUMS:
Alamofire: ae5c501addb7afdbb13687d7f2f722c78734c2d3
Kanna: a32875df62975f8f4b871e933b4ea1a5c3b8be0f
SwiftSoup: 92f5b348c131aed8af04f4326db1579ab19fa08c
PODFILE CHECKSUM: 30581c398549a5f1d7f1c358553c9bcad81e21a6
COCOAPODS: 1.6.1
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2014 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.
+243
View File
@@ -0,0 +1,243 @@
![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/alamofire.png)
[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire)
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](https://alamofire.github.io/Alamofire)
[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](https://twitter.com/AlamofireSF)
[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
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)
- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md)
- **Intro -** [Making a Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-a-request), [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), [Parameter Encoding](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#parameter-encoding), [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-manager), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-delegate), [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)
- **Model Objects -** [Custom Response Serialization](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#custom-response-serialization)
- **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] URL / JSON / plist 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
- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 8.3+
- Swift 3.1+
## Migration Guides
- [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**, 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 and follow the guide. The more detail the better!
- If you **want to contribute**, submit a pull request.
## Installation
### CocoaPods
[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:
```bash
$ gem install cocoapods
```
> CocoaPods 1.1+ is required to build Alamofire 4.0+.
To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`:
```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target '<Your Target Name>' do
pod 'Alamofire', '~> 4.7'
end
```
Then, run the following command:
```bash
$ pod install
```
### Carthage
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
You can install Carthage with [Homebrew](https://brew.sh/) using the following command:
```bash
$ brew update
$ brew install carthage
```
To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl
github "Alamofire/Alamofire" ~> 4.7
```
Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project.
### 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. It is in early development, but Alamofire does support its use on supported platforms.
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 3
```swift
dependencies: [
.Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4)
]
```
#### Swift 4
```swift
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.0.0")
]
```
### 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 OS X.
> You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `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.
## 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 test case
- `rdar://26870455` - Background URL Session Configurations do not work in the simulator
- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest`
- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+
## 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 on 9/1/17 in Xcode 9 beta 6).
## 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.
### What logic belongs in a Router vs. a Request Adapter?
Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`.
The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`.
## 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.
## Donations
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 us members to gain some legal protections and also allow us to put donations to use, tax free.
Donating to 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 today to help us reach our goal would be greatly appreciated.
[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ)
## License
Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details.
+460
View File
@@ -0,0 +1,460 @@
//
// AFError.swift
//
// Copyright (c) 2014 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
/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
/// their own associated reasons.
///
/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`.
/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process.
/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails.
/// - responseValidationFailed: Returned when a `validate()` call fails.
/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process.
public enum AFError: Error {
/// The underlying reason the parameter encoding error occurred.
///
/// - missingURL: The URL request did not have a URL to encode.
/// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the
/// encoding process.
/// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during
/// encoding process.
public enum ParameterEncodingFailureReason {
case missingURL
case jsonEncodingFailed(error: Error)
case propertyListEncodingFailed(error: Error)
}
/// The underlying reason the multipart encoding error occurred.
///
/// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a
/// file URL.
/// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty
/// `lastPathComponent` or `pathExtension.
/// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable.
/// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw
/// an error.
/// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory.
/// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by
/// the system.
/// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided
/// threw an error.
/// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`.
/// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the
/// encoded data to disk.
/// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file
/// already exists at the provided `fileURL`.
/// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is
/// not a file URL.
/// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an
/// underlying error.
/// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with
/// underlying system error.
public enum MultipartEncodingFailureReason {
case bodyPartURLInvalid(url: URL)
case bodyPartFilenameInvalid(in: URL)
case bodyPartFileNotReachable(at: URL)
case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
case bodyPartFileIsDirectory(at: URL)
case bodyPartFileSizeNotAvailable(at: URL)
case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
case bodyPartInputStreamCreationFailed(for: URL)
case outputStreamCreationFailed(for: URL)
case outputStreamFileAlreadyExists(at: URL)
case outputStreamURLInvalid(url: URL)
case outputStreamWriteFailed(error: Error)
case inputStreamReadFailed(error: Error)
}
/// The underlying reason the response validation error occurred.
///
/// - dataFileNil: The data file containing the server response did not exist.
/// - dataFileReadFailed: The data file containing the server response could not be read.
/// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes`
/// provided did not contain wildcard type.
/// - unacceptableContentType: The response `Content-Type` did not match any type in the provided
/// `acceptableContentTypes`.
/// - unacceptableStatusCode: The response status code was not acceptable.
public enum ResponseValidationFailureReason {
case dataFileNil
case dataFileReadFailed(at: URL)
case missingContentType(acceptableContentTypes: [String])
case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
case unacceptableStatusCode(code: Int)
}
/// The underlying reason the response serialization error occurred.
///
/// - inputDataNil: The server response contained no data.
/// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length.
/// - inputFileNil: The file containing the server response did not exist.
/// - inputFileReadFailed: The file containing the server response could not be read.
/// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`.
/// - jsonSerializationFailed: JSON serialization failed with an underlying system error.
/// - propertyListSerializationFailed: Property list serialization failed with an underlying system error.
public enum ResponseSerializationFailureReason {
case inputDataNil
case inputDataNilOrZeroLength
case inputFileNil
case inputFileReadFailed(at: URL)
case stringSerializationFailed(encoding: String.Encoding)
case jsonSerializationFailed(error: Error)
case propertyListSerializationFailed(error: Error)
}
case invalidURL(url: URLConvertible)
case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
case responseValidationFailed(reason: ResponseValidationFailureReason)
case responseSerializationFailed(reason: ResponseSerializationFailureReason)
}
// MARK: - Adapt Error
struct AdaptError: Error {
let error: Error
}
extension Error {
var underlyingAdaptError: Error? { return (self as? AdaptError)?.error }
}
// MARK: - Error Booleans
extension AFError {
/// Returns whether the AFError is an invalid URL error.
public var isInvalidURLError: Bool {
if case .invalidURL = self { return true }
return false
}
/// Returns whether the AFError is a parameter encoding error. 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 AFError is a multipart encoding error. 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 `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, and `responseCode` properties will contain the associated values.
public var isResponseValidationError: Bool {
if case .responseValidationFailed = self { return true }
return false
}
/// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and
/// `underlyingError` properties will contain the associated values.
public var isResponseSerializationError: Bool {
if case .responseSerializationFailed = self { return true }
return false
}
}
// MARK: - Convenience Properties
extension AFError {
/// The `URLConvertible` associated with the error.
public var urlConvertible: URLConvertible? {
switch self {
case .invalidURL(let url):
return url
default:
return nil
}
}
/// The `URL` associated with the error.
public var url: URL? {
switch self {
case .multipartEncodingFailed(let reason):
return reason.url
default:
return nil
}
}
/// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`,
/// `.multipartEncodingFailed` or `.responseSerializationFailed` error.
public var underlyingError: Error? {
switch self {
case .parameterEncodingFailed(let reason):
return reason.underlyingError
case .multipartEncodingFailed(let reason):
return reason.underlyingError
case .responseSerializationFailed(let reason):
return reason.underlyingError
default:
return nil
}
}
/// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
public var acceptableContentTypes: [String]? {
switch self {
case .responseValidationFailed(let reason):
return reason.acceptableContentTypes
default:
return nil
}
}
/// The response `Content-Type` of a `.responseValidationFailed` error.
public var responseContentType: String? {
switch self {
case .responseValidationFailed(let reason):
return reason.responseContentType
default:
return nil
}
}
/// The response code of a `.responseValidationFailed` error.
public var responseCode: Int? {
switch self {
case .responseValidationFailed(let reason):
return reason.responseCode
default:
return nil
}
}
/// The `String.Encoding` associated with a failed `.stringResponse()` call.
public var failedStringEncoding: String.Encoding? {
switch self {
case .responseSerializationFailed(let reason):
return reason.failedStringEncoding
default:
return nil
}
}
}
extension AFError.ParameterEncodingFailureReason {
var underlyingError: Error? {
switch self {
case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error):
return error
default:
return nil
}
}
}
extension AFError.MultipartEncodingFailureReason {
var url: URL? {
switch self {
case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url),
.bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url),
.bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url),
.outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url),
.bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _):
return url
default:
return nil
}
}
var underlyingError: Error? {
switch self {
case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error),
.outputStreamWriteFailed(let error), .inputStreamReadFailed(let error):
return error
default:
return nil
}
}
}
extension AFError.ResponseValidationFailureReason {
var acceptableContentTypes: [String]? {
switch self {
case .missingContentType(let types), .unacceptableContentType(let types, _):
return types
default:
return nil
}
}
var responseContentType: String? {
switch self {
case .unacceptableContentType(_, let responseType):
return responseType
default:
return nil
}
}
var responseCode: Int? {
switch self {
case .unacceptableStatusCode(let code):
return code
default:
return nil
}
}
}
extension AFError.ResponseSerializationFailureReason {
var failedStringEncoding: String.Encoding? {
switch self {
case .stringSerializationFailed(let encoding):
return encoding
default:
return nil
}
}
var underlyingError: Error? {
switch self {
case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error):
return error
default:
return nil
}
}
}
// MARK: - Error Descriptions
extension AFError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidURL(let url):
return "URL is not valid: \(url)"
case .parameterEncodingFailed(let reason):
return reason.localizedDescription
case .multipartEncodingFailed(let reason):
return reason.localizedDescription
case .responseValidationFailed(let reason):
return reason.localizedDescription
case .responseSerializationFailed(let reason):
return reason.localizedDescription
}
}
}
extension AFError.ParameterEncodingFailureReason {
var localizedDescription: String {
switch self {
case .missingURL:
return "URL request to encode was missing a URL"
case .jsonEncodingFailed(let error):
return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
case .propertyListEncodingFailed(let error):
return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)"
}
}
}
extension AFError.MultipartEncodingFailureReason {
var localizedDescription: String {
switch self {
case .bodyPartURLInvalid(let url):
return "The URL provided is not a file URL: \(url)"
case .bodyPartFilenameInvalid(let url):
return "The URL provided does not have a valid filename: \(url)"
case .bodyPartFileNotReachable(let url):
return "The URL provided is not reachable: \(url)"
case .bodyPartFileNotReachableWithError(let url, let error):
return (
"The system returned an error while checking the provided URL for " +
"reachability.\nURL: \(url)\nError: \(error)"
)
case .bodyPartFileIsDirectory(let url):
return "The URL provided is a directory: \(url)"
case .bodyPartFileSizeNotAvailable(let url):
return "Could not fetch the file size from the provided URL: \(url)"
case .bodyPartFileSizeQueryFailedWithError(let url, let error):
return (
"The system returned an error while attempting to fetch the file size from the " +
"provided URL.\nURL: \(url)\nError: \(error)"
)
case .bodyPartInputStreamCreationFailed(let url):
return "Failed to create an InputStream for the provided URL: \(url)"
case .outputStreamCreationFailed(let url):
return "Failed to create an OutputStream for URL: \(url)"
case .outputStreamFileAlreadyExists(let url):
return "A file already exists at the provided URL: \(url)"
case .outputStreamURLInvalid(let url):
return "The provided OutputStream URL is invalid: \(url)"
case .outputStreamWriteFailed(let error):
return "OutputStream write failed with error: \(error)"
case .inputStreamReadFailed(let error):
return "InputStream read failed with error: \(error)"
}
}
}
extension AFError.ResponseSerializationFailureReason {
var localizedDescription: String {
switch self {
case .inputDataNil:
return "Response could not be serialized, input data was nil."
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 .inputFileReadFailed(let url):
return "Response could not be serialized, input file could not be read: \(url)."
case .stringSerializationFailed(let encoding):
return "String could not be serialized with encoding: \(encoding)."
case .jsonSerializationFailed(let error):
return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
case .propertyListSerializationFailed(let error):
return "PropertyList could not be serialized because of 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 .dataFileReadFailed(let url):
return "Response could not be validated, data file could not be read: \(url)."
case .missingContentType(let types):
return (
"Response Content-Type was missing and acceptable content types " +
"(\(types.joined(separator: ","))) do not match \"*/*\"."
)
case .unacceptableContentType(let acceptableTypes, let responseType):
return (
"Response Content-Type \"\(responseType)\" does not match any acceptable types: " +
"\(acceptableTypes.joined(separator: ","))."
)
case .unacceptableStatusCode(let code):
return "Response status code was unacceptable: \(code)."
}
}
}
+465
View File
@@ -0,0 +1,465 @@
//
// Alamofire.swift
//
// Copyright (c) 2014 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 URLs, which are then used to construct
/// URL requests.
public protocol URLConvertible {
/// Returns a URL that conforms to RFC 2396 or throws an `Error`.
///
/// - throws: An `Error` if the type cannot be converted to a `URL`.
///
/// - returns: A URL or throws an `Error`.
func asURL() throws -> URL
}
extension String: URLConvertible {
/// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`.
///
/// - throws: An `AFError.invalidURL` if `self` is not a valid URL string.
///
/// - returns: A URL or throws an `AFError`.
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 { return self }
}
extension URLComponents: URLConvertible {
/// Returns a URL if `url` is not nil, otherwise throws an `Error`.
///
/// - throws: An `AFError.invalidURL` if `url` is `nil`.
///
/// - returns: A URL or throws an `AFError`.
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 construct URL requests.
public protocol URLRequestConvertible {
/// Returns a URL request or throws if an `Error` was encountered.
///
/// - throws: An `Error` if the underlying `URLRequest` is `nil`.
///
/// - returns: A URL request.
func asURLRequest() throws -> URLRequest
}
extension URLRequestConvertible {
/// The URL request.
public var urlRequest: URLRequest? { return try? asURLRequest() }
}
extension URLRequest: URLRequestConvertible {
/// Returns a URL request or throws if an `Error` was encountered.
public func asURLRequest() throws -> URLRequest { return self }
}
// MARK: -
extension URLRequest {
/// Creates an instance with the specified `method`, `urlString` and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The new `URLRequest` instance.
public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws {
let url = try url.asURL()
self.init(url: url)
httpMethod = method.rawValue
if let headers = headers {
for (headerField, headerValue) in headers {
setValue(headerValue, forHTTPHeaderField: headerField)
}
}
}
func adapt(using adapter: RequestAdapter?) throws -> URLRequest {
guard let adapter = adapter else { return self }
return try adapter.adapt(self)
}
}
// MARK: - Data Request
/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
/// `method`, `parameters`, `encoding` and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `DataRequest`.
@discardableResult
public func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
return SessionManager.default.request(
url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
/// specified `urlRequest`.
///
/// - parameter urlRequest: The URL request
///
/// - returns: The created `DataRequest`.
@discardableResult
public func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
return SessionManager.default.request(urlRequest)
}
// MARK: - Download Request
// MARK: URL Request
/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
public func download(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return SessionManager.default.download(
url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers,
to: destination
)
}
/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
/// specified `urlRequest` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// - parameter urlRequest: The URL request.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
public func download(
_ urlRequest: URLRequestConvertible,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return SessionManager.default.download(urlRequest, to: destination)
}
// MARK: Resume Data
/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a
/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `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 following Stack Overflow post:
///
/// - http://stackoverflow.com/a/39347461/1342462
///
/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional
/// information.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
public func download(
resumingWith resumeData: Data,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return SessionManager.default.download(resumingWith: resumeData, to: destination)
}
// MARK: - Upload Request
// MARK: File
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
/// for uploading the `file`.
///
/// - parameter file: The file to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
public func upload(
_ fileURL: URL,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers)
}
/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
/// uploading the `file`.
///
/// - parameter file: The file to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
return SessionManager.default.upload(fileURL, with: urlRequest)
}
// MARK: Data
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
/// for uploading the `data`.
///
/// - parameter data: The data to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
public func upload(
_ data: Data,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
return SessionManager.default.upload(data, to: url, method: method, headers: headers)
}
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
/// uploading the `data`.
///
/// - parameter data: The data to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
return SessionManager.default.upload(data, with: urlRequest)
}
// MARK: InputStream
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
/// for uploading the `stream`.
///
/// - parameter stream: The stream to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
public func upload(
_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
return SessionManager.default.upload(stream, to: url, method: method, headers: headers)
}
/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
/// uploading the `stream`.
///
/// - parameter urlRequest: The URL request.
/// - parameter stream: The stream to upload.
///
/// - returns: The created `UploadRequest`.
@discardableResult
public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
return SessionManager.default.upload(stream, with: urlRequest)
}
// MARK: MultipartFormData
/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls
/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// 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.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
public func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
{
return SessionManager.default.upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
to: url,
method: method,
headers: headers,
encodingCompletion: encodingCompletion
)
}
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and
/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// 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.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter urlRequest: The URL request.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
public func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
with urlRequest: URLRequestConvertible,
encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
{
return SessionManager.default.upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
with: urlRequest,
encodingCompletion: encodingCompletion
)
}
#if !os(watchOS)
// MARK: - Stream Request
// MARK: Hostname and Port
/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname`
/// and `port`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter hostName: The hostname of the server to connect to.
/// - parameter port: The port of the server to connect to.
///
/// - returns: The created `StreamRequest`.
@discardableResult
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
public func stream(withHostName hostName: String, port: Int) -> StreamRequest {
return SessionManager.default.stream(withHostName: hostName, port: port)
}
// MARK: NetService
/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter netService: The net service used to identify the endpoint.
///
/// - returns: The created `StreamRequest`.
@discardableResult
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
public func stream(with netService: NetService) -> StreamRequest {
return SessionManager.default.stream(with: netService)
}
#endif
+37
View File
@@ -0,0 +1,37 @@
//
// DispatchQueue+Alamofire.swift
//
// Copyright (c) 2014 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 {
static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) }
static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) }
static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) }
static var background: DispatchQueue { return DispatchQueue.global(qos: .background) }
func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) {
asyncAfter(deadline: .now() + delay, execute: closure)
}
}
+580
View File
@@ -0,0 +1,580 @@
//
// MultipartFormData.swift
//
// Copyright (c) 2014 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 os(iOS) || os(watchOS) || os(tvOS)
import MobileCoreServices
#elseif os(macOS)
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
struct EncodingCharacters {
static let crlf = "\r\n"
}
struct BoundaryGenerator {
enum BoundaryType {
case initial, encapsulated, final
}
static func randomBoundary() -> String {
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
}
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 boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)!
}
}
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
/// 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 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
/// The boundary used to separate the body parts in the encoded form data.
public var boundary: String
private var bodyParts: [BodyPart]
private var bodyPartError: AFError?
private let streamBufferSize: Int
// MARK: - Lifecycle
/// Creates a multipart form data object.
///
/// - returns: The multipart form data object.
public init() {
self.boundary = BoundaryGenerator.randomBoundary()
self.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
///
self.streamBufferSize = 1024
}
// MARK: - Body Parts
/// Creates a body part from the data and appends it to the multipart form data object.
///
/// The body part data will be encoded using the following format:
///
/// - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
/// - Encoded data
/// - Multipart form boundary
///
/// - parameter data: The data to encode into the multipart form data.
/// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
public func append(_ data: Data, withName name: String) {
let headers = contentHeaders(withName: name)
let stream = InputStream(data: data)
let length = UInt64(data.count)
append(stream, withLength: length, headers: headers)
}
/// Creates a body part from the data and appends it to the multipart form data object.
///
/// The body part data will be encoded using the following format:
///
/// - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
/// - `Content-Type: #{generated mimeType}` (HTTP Header)
/// - Encoded data
/// - Multipart form boundary
///
/// - parameter data: The data to encode into the multipart form data.
/// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
/// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
public func append(_ data: Data, withName name: String, mimeType: String) {
let headers = contentHeaders(withName: name, mimeType: mimeType)
let stream = InputStream(data: data)
let length = UInt64(data.count)
append(stream, withLength: length, headers: headers)
}
/// Creates a body part from the data and appends it to the multipart form data object.
///
/// 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
///
/// - parameter data: The data to encode into the multipart form data.
/// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
/// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
/// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) {
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 multipart form data object.
///
/// 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.
///
/// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
/// - parameter name: The 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 multipart form data object.
///
/// 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
///
/// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
/// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
/// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
/// - parameter mimeType: The 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?
//============================================================
do {
let isReachable = try fileURL.checkPromisedItemIsReachable()
guard isReachable else {
setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL))
return
}
} catch {
setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error))
return
}
//============================================================
// Check 3 - is file URL a directory?
//============================================================
var isDirectory: ObjCBool = false
let path = fileURL.path
guard FileManager.default.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.default.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 multipart form data object.
///
/// 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
///
/// - parameter stream: The input stream to encode in the multipart form data.
/// - parameter length: The content length of the stream.
/// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
/// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
/// - parameter mimeType: The 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 headers, stream and length and appends it to the multipart form data object.
///
/// The body part data will be encoded using the following format:
///
/// - HTTP headers
/// - Encoded stream data
/// - Multipart form boundary
///
/// - parameter stream: The input stream to encode in the multipart form data.
/// - parameter length: The content length of the stream.
/// - parameter headers: The HTTP headers 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 the appended body parts into a single `Data` value.
///
/// It is important to note that 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 `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
///
/// - throws: An `AFError` if encoding encounters an error.
///
/// - returns: The encoded `Data` if encoding is successful.
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 the appended body parts into 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: The file URL to write the multipart form data into.
///
/// - throws: An `AFError` if encoding encounters an error.
public func writeEncodedData(to fileURL: URL) throws {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
if FileManager.default.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() }
self.bodyParts.first?.hasInitialBoundary = true
self.bodyParts.last?.hasFinalBoundary = true
for bodyPart in self.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 {
var headerText = ""
for (key, value) in bodyPart.headers {
headerText += "\(key): \(value)\(EncodingCharacters.crlf)"
}
headerText += EncodingCharacters.crlf
return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)!
}
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
}
}
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() }
while inputStream.hasBytesAvailable {
var buffer = [UInt8](repeating: 0, count: streamBufferSize)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let streamError = inputStream.streamError {
throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError))
}
if bytesRead > 0 {
if buffer.count != bytesRead {
buffer = Array(buffer[0..<bytesRead])
}
try write(&buffer, to: outputStream)
} else {
break
}
}
}
private func writeFinalBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
if bodyPart.hasFinalBoundary {
return try write(finalBoundaryData(), to: outputStream)
}
}
// MARK: - Private - Writing Buffered Data to Output Stream
private func write(_ data: Data, to outputStream: OutputStream) throws {
var buffer = [UInt8](repeating: 0, count: data.count)
data.copyBytes(to: &buffer, count: data.count)
return try write(&buffer, to: outputStream)
}
private func write(_ buffer: inout [UInt8], to outputStream: OutputStream) throws {
var bytesToWrite = buffer.count
while bytesToWrite > 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..<buffer.count])
}
}
}
// MARK: - Private - Mime Type
private func mimeType(forPathExtension pathExtension: String) -> String {
if
let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
{
return contentType as String
}
return "application/octet-stream"
}
// MARK: - Private - Content Headers
private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] {
var disposition = "form-data; name=\"\(name)\""
if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" }
var headers = ["Content-Disposition": disposition]
if let mimeType = mimeType { headers["Content-Type"] = mimeType }
return headers
}
// MARK: - Private - Boundary Encoding
private func initialBoundaryData() -> Data {
return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary)
}
private func encapsulatedBoundaryData() -> Data {
return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary)
}
private func finalBoundaryData() -> Data {
return 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)
}
}
+235
View File
@@ -0,0 +1,235 @@
//
// NetworkReachabilityManager.swift
//
// Copyright (c) 2014 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(watchOS)
import Foundation
import SystemConfiguration
/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN 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.
///
/// - unknown: It is unknown whether the network is reachable.
/// - notReachable: The network is not reachable.
/// - reachable: The network is reachable.
public enum NetworkReachabilityStatus {
case unknown
case notReachable
case reachable(ConnectionType)
}
/// Defines the various connection types detected by reachability flags.
///
/// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi.
/// - wwan: The connection type is a WWAN connection.
public enum ConnectionType {
case ethernetOrWiFi
case wwan
}
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// network reachability status.
public typealias Listener = (NetworkReachabilityStatus) -> Void
// MARK: - Properties
/// Whether the network is currently reachable.
open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
/// Whether the network is currently reachable over the WWAN interface.
open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
/// Whether the network is currently reachable over Ethernet or WiFi interface.
open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
/// The current network reachability status.
open var networkReachabilityStatus: NetworkReachabilityStatus {
guard let flags = self.flags else { return .unknown }
return networkReachabilityStatusForFlags(flags)
}
/// The dispatch queue to execute the `listener` closure on.
open var listenerQueue: DispatchQueue = DispatchQueue.main
/// A closure executed when the network reachability status changes.
open var listener: Listener?
open var flags: SCNetworkReachabilityFlags? {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachability, &flags) {
return flags
}
return nil
}
private let reachability: SCNetworkReachability
open var previousFlags: SCNetworkReachabilityFlags
// MARK: - Initialization
/// Creates a `NetworkReachabilityManager` instance with the specified host.
///
/// - parameter host: The host used to evaluate network reachability.
///
/// - returns: The new `NetworkReachabilityManager` instance.
public convenience init?(host: String) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
self.init(reachability: reachability)
}
/// Creates a `NetworkReachabilityManager` 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.
///
/// - returns: The new `NetworkReachabilityManager` instance.
public convenience init?() {
var address = sockaddr_in()
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &address, { pointer in
return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) {
return SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else { return nil }
self.init(reachability: reachability)
}
private init(reachability: SCNetworkReachability) {
self.reachability = reachability
// Set the previous flags to an unreserved value to represent unknown status
self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30)
}
deinit {
stopListening()
}
// MARK: - Listening
/// Starts listening for changes in network reachability status.
///
/// - returns: `true` if listening was started successfully, `false` otherwise.
@discardableResult
open func startListening() -> Bool {
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = Unmanaged.passUnretained(self).toOpaque()
let callbackEnabled = SCNetworkReachabilitySetCallback(
reachability,
{ (_, flags, info) in
let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue()
reachability.notifyListener(flags)
},
&context
)
let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
listenerQueue.async {
guard let flags = self.flags else { return }
self.notifyListener(flags)
}
return callbackEnabled && queueEnabled
}
/// Stops listening for changes in network reachability status.
open func stopListening() {
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
}
// MARK: - Internal - Listener Notification
func notifyListener(_ flags: SCNetworkReachabilityFlags) {
guard previousFlags != flags else { return }
previousFlags = flags
listener?(networkReachabilityStatusForFlags(flags))
}
// MARK: - Internal - Network Reachability Status
func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
guard isNetworkReachable(with: flags) else { return .notReachable }
var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
#if os(iOS)
if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
#endif
return networkStatus
}
func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)
let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)
return isReachable && (!needsConnection || canConnectWithoutUserInteraction)
}
}
// MARK: -
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
/// Returns whether the two network reachability status values are equal.
///
/// - parameter lhs: The left-hand side value to compare.
/// - parameter rhs: The right-hand side value to compare.
///
/// - returns: `true` if the two values are equal, `false` otherwise.
public func ==(
lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
-> Bool
{
switch (lhs, rhs) {
case (.unknown, .unknown):
return true
case (.notReachable, .notReachable):
return true
case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
return lhsConnectionType == rhsConnectionType
default:
return false
}
}
#endif
+55
View File
@@ -0,0 +1,55 @@
//
// Notifications.swift
//
// Copyright (c) 2014 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 Notification.Name {
/// Used as a namespace for all `URLSessionTask` related notifications.
public struct Task {
/// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`.
public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume")
/// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`.
public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend")
/// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`.
public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel")
/// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`.
public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete")
}
}
// MARK: -
extension Notification {
/// Used as a namespace for all `Notification` user info dictionary keys.
public struct Key {
/// User info dictionary key representing the `URLSessionTask` associated with the notification.
public static let Task = "org.alamofire.notification.key.task"
/// User info dictionary key representing the responseData associated with the notification.
public static let ResponseData = "org.alamofire.notification.key.responseData"
}
}
+483
View File
@@ -0,0 +1,483 @@
//
// ParameterEncoding.swift
//
// Copyright (c) 2014 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
/// HTTP method definitions.
///
/// See https://tools.ietf.org/html/rfc7231#section-4.3
public enum HTTPMethod: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
// MARK: -
/// 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 URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
///
/// - returns: The encoded request.
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.
///
/// - methodDependent: 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.
/// - queryString: Sets or appends encoded query string result to existing query string.
/// - httpBody: Sets encoded query string result as the HTTP body of the URL request.
public enum Destination {
case methodDependent, queryString, httpBody
}
/// Configures how `Array` parameters are encoded.
///
/// - brackets: An empty set of square brackets is appended to the key for every value.
/// This is the default behavior.
/// - noBrackets: No brackets are appended. The key is encoded as is.
public enum ArrayEncoding {
case brackets, noBrackets
func encode(key: String) -> String {
switch self {
case .brackets:
return "\(key)[]"
case .noBrackets:
return key
}
}
}
/// Configures how `Bool` parameters are encoded.
///
/// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior.
/// - literal: Encode `true` and `false` as string literals.
public enum BoolEncoding {
case numeric, 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.
public static var `default`: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.methodDependent` destination.
public static var methodDependent: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.queryString` destination.
public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) }
/// Returns a `URLEncoding` instance with an `.httpBody` destination.
public static var httpBody: URLEncoding { return 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 a `URLEncoding` instance using the specified destination.
///
/// - parameter destination: The destination defining where the encoded query string is to be applied.
/// - parameter arrayEncoding: The encoding to use for `Array` parameters.
/// - parameter boolEncoding: The encoding to use for `Bool` parameters.
///
/// - returns: The new `URLEncoding` instance.
public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) {
self.destination = destination
self.arrayEncoding = arrayEncoding
self.boolEncoding = boolEncoding
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
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 = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: 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.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
}
return urlRequest
}
/// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
///
/// - parameter key: The key of the query component.
/// - parameter value: The 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)] = []
if let dictionary = value as? [String: Any] {
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
} else if let array = value as? [Any] {
for value in array {
components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value)
}
} else if let value = value as? NSNumber {
if value.isBool {
components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue))))
} else {
components.append((escape(key), escape("\(value)")))
}
} else if let bool = value as? Bool {
components.append((escape(key), escape(boolEncoding.encode(value: bool))))
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// 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.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
public func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
let range = startIndex..<endIndex
let substring = string[range]
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? String(substring)
index = endIndex
}
}
return escaped
}
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: "&")
}
private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
switch destination {
case .queryString:
return true
case .httpBody:
return false
default:
break
}
switch method {
case .get, .head, .delete:
return true
default:
return false
}
}
}
// 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 {
// MARK: Properties
/// Returns a `JSONEncoding` instance with default writing options.
public static var `default`: JSONEncoding { return JSONEncoding() }
/// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
/// The options for writing the parameters as JSON data.
public let options: JSONSerialization.WritingOptions
// MARK: Initialization
/// Creates a `JSONEncoding` instance using the specified options.
///
/// - parameter options: The options for writing the parameters as JSON data.
///
/// - returns: The new `JSONEncoding` instance.
public init(options: JSONSerialization.WritingOptions = []) {
self.options = options
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
/// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
///
/// - parameter urlRequest: The request to apply the JSON object to.
/// - parameter jsonObject: The JSON object to apply to the request.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let jsonObject = jsonObject else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
/// field of an encoded request is set to `application/x-plist`.
public struct PropertyListEncoding: ParameterEncoding {
// MARK: Properties
/// Returns a default `PropertyListEncoding` instance.
public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
/// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
/// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
/// The property list serialization format.
public let format: PropertyListSerialization.PropertyListFormat
/// The options for writing the parameters as plist data.
public let options: PropertyListSerialization.WriteOptions
// MARK: Initialization
/// Creates a `PropertyListEncoding` instance using the specified format and options.
///
/// - parameter format: The property list serialization format.
/// - parameter options: The options for writing the parameters as plist data.
///
/// - returns: The new `PropertyListEncoding` instance.
public init(
format: PropertyListSerialization.PropertyListFormat = .xml,
options: PropertyListSerialization.WriteOptions = 0)
{
self.format = format
self.options = options
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try PropertyListSerialization.data(
fromPropertyList: parameters,
format: format,
options: options
)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
extension NSNumber {
fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
}
+649
View File
@@ -0,0 +1,649 @@
//
// Request.swift
//
// Copyright (c) 2014 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 inspect and optionally adapt a `URLRequest` in some manner if necessary.
public protocol RequestAdapter {
/// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result.
///
/// - parameter urlRequest: The URL request to adapt.
///
/// - throws: An `Error` if the adaptation encounters an error.
///
/// - returns: The adapted `URLRequest`.
func adapt(_ urlRequest: URLRequest) throws -> URLRequest
}
// MARK: -
/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
/// 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.
///
/// - parameter manager: The session manager the request was executed on.
/// - parameter request: The request that failed due to the encountered error.
/// - parameter error: The error encountered when executing the request.
/// - parameter completion: The completion closure to be executed when retry decision has been determined.
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
}
// MARK: -
protocol TaskConvertible {
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
}
/// A dictionary of headers to apply to a `URLRequest`.
public typealias HTTPHeaders = [String: String]
// MARK: -
/// Responsible for sending a request and receiving the response and associated data from the server, as well as
/// managing its underlying `URLSessionTask`.
open class Request {
// MARK: Helper Types
/// A closure executed when monitoring upload or download progress of a request.
public typealias ProgressHandler = (Progress) -> Void
enum RequestTask {
case data(TaskConvertible?, URLSessionTask?)
case download(TaskConvertible?, URLSessionTask?)
case upload(TaskConvertible?, URLSessionTask?)
case stream(TaskConvertible?, URLSessionTask?)
}
// MARK: Properties
/// The delegate for the underlying task.
open internal(set) var delegate: TaskDelegate {
get {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
return taskDelegate
}
set {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
taskDelegate = newValue
}
}
/// The underlying task.
open var task: URLSessionTask? { return delegate.task }
/// The session belonging to the underlying task.
public let session: URLSession
/// The request sent or to be sent to the server.
open var request: URLRequest? { return task?.originalRequest }
/// The response received from the server, if any.
open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
/// The number of times the request has been retried.
open internal(set) var retryCount: UInt = 0
let originalTask: TaskConvertible?
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
var validations: [() -> Void] = []
private var taskDelegate: TaskDelegate
private var taskDelegateLock = NSLock()
// MARK: Lifecycle
init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
self.session = session
switch requestTask {
case .data(let originalTask, let task):
taskDelegate = DataTaskDelegate(task: task)
self.originalTask = originalTask
case .download(let originalTask, let task):
taskDelegate = DownloadTaskDelegate(task: task)
self.originalTask = originalTask
case .upload(let originalTask, let task):
taskDelegate = UploadTaskDelegate(task: task)
self.originalTask = originalTask
case .stream(let originalTask, let task):
taskDelegate = TaskDelegate(task: task)
self.originalTask = originalTask
}
delegate.error = error
delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
}
// MARK: Authentication
/// Associates an HTTP Basic credential with the request.
///
/// - parameter user: The user.
/// - parameter password: The password.
/// - parameter persistence: The URL credential persistence. `.ForSession` by default.
///
/// - returns: The request.
@discardableResult
open func authenticate(
user: String,
password: String,
persistence: URLCredential.Persistence = .forSession)
-> Self
{
let credential = URLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/// Associates a specified credential with the request.
///
/// - parameter credential: The credential.
///
/// - returns: The request.
@discardableResult
open func authenticate(usingCredential credential: URLCredential) -> Self {
delegate.credential = credential
return self
}
/// Returns a base64 encoded basic authentication credential as an authorization header tuple.
///
/// - parameter user: The user.
/// - parameter password: The password.
///
/// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
open class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
let credential = data.base64EncodedString(options: [])
return (key: "Authorization", value: "Basic \(credential)")
}
// MARK: State
/// Resumes the request.
open func resume() {
guard let task = task else { delegate.queue.isSuspended = false ; return }
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NotificationCenter.default.post(
name: Notification.Name.Task.DidResume,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Suspends the request.
open func suspend() {
guard let task = task else { return }
task.suspend()
NotificationCenter.default.post(
name: Notification.Name.Task.DidSuspend,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Cancels the request.
open func cancel() {
guard let task = task else { return }
task.cancel()
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
}
// MARK: - CustomStringConvertible
extension Request: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
/// well as the response status code if a response has been received.
open var description: String {
var components: [String] = []
if let HTTPMethod = request?.httpMethod {
components.append(HTTPMethod)
}
if let urlString = request?.url?.absoluteString {
components.append(urlString)
}
if let response = response {
components.append("(\(response.statusCode))")
}
return components.joined(separator: " ")
}
}
// MARK: - CustomDebugStringConvertible
extension Request: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, in the form of a cURL command.
open var debugDescription: String {
return cURLRepresentation()
}
func cURLRepresentation() -> String {
var components = ["$ curl -v"]
guard let request = self.request,
let url = request.url,
let host = url.host
else {
return "$ curl command could not be created"
}
if let httpMethod = request.httpMethod, httpMethod != "GET" {
components.append("-X \(httpMethod)")
}
if let credentialStorage = self.session.configuration.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 = delegate.credential, let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
}
if session.configuration.httpShouldSetCookies {
if
let cookieStorage = session.configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
#if swift(>=3.2)
components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"")
#else
components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
#endif
}
}
var headers: [AnyHashable: Any] = [:]
session.configuration.httpAdditionalHeaders?.filter { $0.0 != AnyHashable("Cookie") }
.forEach { headers[$0.0] = $0.1 }
request.allHTTPHeaderFields?.filter { $0.0 != "Cookie" }
.forEach { headers[$0.0] = $0.1 }
components += headers.map {
let escapedValue = String(describing: $0.value).replacingOccurrences(of: "\"", with: "\\\"")
return "-H \"\($0.key): \(escapedValue)\""
}
if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
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")
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
open class DataRequest: Request {
// MARK: Helper Types
struct Requestable: TaskConvertible {
let urlRequest: URLRequest
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let urlRequest = try self.urlRequest.adapt(using: adapter)
return queue.sync { session.dataTask(with: urlRequest) }
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let requestable = originalTask as? Requestable { return requestable.urlRequest }
return nil
}
/// The progress of fetching the response data from the server for the request.
open var progress: Progress { return dataDelegate.progress }
var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
// MARK: Stream
/// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
///
/// This closure returns the bytes most recently received from the server, not including data from previous calls.
/// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
/// also important to note that the server data in any `Response` object will be `nil`.
///
/// - parameter closure: The code to be executed periodically during the lifecycle of the request.
///
/// - returns: The request.
@discardableResult
open func stream(closure: ((Data) -> Void)? = nil) -> Self {
dataDelegate.dataStream = closure
return self
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
dataDelegate.progressHandler = (closure, queue)
return self
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
open class DownloadRequest: Request {
// MARK: Helper Types
/// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
/// destination URL.
public struct DownloadOptions: OptionSet {
/// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
public let rawValue: UInt
/// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
/// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
/// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
///
/// - parameter rawValue: The raw bitmask value for the option.
///
/// - returns: A new log level instance.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
/// A closure executed once a download request 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 URL response, and returns a two arguments: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
public typealias DownloadFileDestination = (
_ temporaryURL: URL,
_ response: HTTPURLResponse)
-> (destinationURL: URL, options: DownloadOptions)
enum Downloadable: TaskConvertible {
case request(URLRequest)
case resumeData(Data)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .request(urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.downloadTask(with: urlRequest) }
case let .resumeData(resumeData):
task = queue.sync { session.downloadTask(withResumeData: resumeData) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
return urlRequest
}
return nil
}
/// The resume data of the underlying download task if available after a failure.
open var resumeData: Data? { return downloadDelegate.resumeData }
/// The progress of downloading the response data from the server for the request.
open var progress: Progress { return downloadDelegate.progress }
var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
// MARK: State
/// Cancels the request.
open override func cancel() {
downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task as Any]
)
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
downloadDelegate.progressHandler = (closure, queue)
return self
}
// MARK: Destination
/// 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.
///
/// - parameter directory: The search path directory. `.DocumentDirectory` by default.
/// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
///
/// - returns: A download file destination closure.
open class func suggestedDownloadDestination(
for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask)
-> DownloadFileDestination
{
return { temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
if !directoryURLs.isEmpty {
return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
}
return (temporaryURL, [])
}
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
open class UploadRequest: DataRequest {
// MARK: Helper Types
enum Uploadable: TaskConvertible {
case data(Data, URLRequest)
case file(URL, URLRequest)
case stream(InputStream, URLRequest)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .data(data, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
case let .file(url, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
case let .stream(_, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
guard let uploadable = originalTask as? Uploadable else { return nil }
switch uploadable {
case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
return urlRequest
}
}
/// The progress of uploading the payload to the server for the upload request.
open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
// MARK: Upload Progress
/// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
/// the server.
///
/// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
/// of data being read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is sent to the server.
///
/// - returns: The request.
@discardableResult
open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
uploadDelegate.uploadProgressHandler = (closure, queue)
return self
}
}
// MARK: -
#if !os(watchOS)
/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open class StreamRequest: Request {
enum Streamable: TaskConvertible {
case stream(hostName: String, port: Int)
case netService(NetService)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
let task: URLSessionTask
switch self {
case let .stream(hostName, port):
task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
case let .netService(netService):
task = queue.sync { session.streamTask(with: netService) }
}
return task
}
}
}
#endif
+567
View File
@@ -0,0 +1,567 @@
//
// Response.swift
//
// Copyright (c) 2014 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
/// Used to store all data associated with an non-serialized response of a data or upload request.
public struct DefaultDataResponse {
/// 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 error encountered while executing or validating the request.
public let error: Error?
/// The timeline of the complete lifecycle of the request.
public let timeline: Timeline
var _metrics: AnyObject?
/// Creates a `DefaultDataResponse` instance from the specified parameters.
///
/// - Parameters:
/// - request: The URL request sent to the server.
/// - response: The server's response to the URL request.
/// - data: The data returned by the server.
/// - error: The error encountered while executing or validating the request.
/// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default.
/// - metrics: The task metrics containing the request / response statistics. `nil` by default.
public init(
request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
error: Error?,
timeline: Timeline = Timeline(),
metrics: AnyObject? = nil)
{
self.request = request
self.response = response
self.data = data
self.error = error
self.timeline = timeline
}
}
// MARK: -
/// Used to store all data associated with a serialized response of a data or upload request.
public struct DataResponse<Value> {
/// 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 result of response serialization.
public let result: Result<Value>
/// The timeline of the complete lifecycle of the request.
public let timeline: Timeline
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Value? { return result.value }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Error? { return result.error }
var _metrics: AnyObject?
/// Creates a `DataResponse` instance with the specified parameters derived from response serialization.
///
/// - parameter request: The URL request sent to the server.
/// - parameter response: The server's response to the URL request.
/// - parameter data: The data returned by the server.
/// - parameter result: The result of response serialization.
/// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
///
/// - returns: The new `DataResponse` instance.
public init(
request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
result: Result<Value>,
timeline: Timeline = Timeline())
{
self.request = request
self.response = response
self.data = data
self.result = result
self.timeline = timeline
}
}
// 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 {
return result.debugDescription
}
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
/// response, the server data, the response serialization result and the timeline.
public var debugDescription: String {
var output: [String] = []
output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil")
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[Data]: \(data?.count ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)")
output.append("[Timeline]: \(timeline.debugDescription)")
return output.joined(separator: "\n")
}
}
// 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<Data> = ...
/// 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<T>(_ transform: (Value) -> T) -> DataResponse<T> {
var response = DataResponse<T>(
request: request,
response: self.response,
data: data,
result: result.map(transform),
timeline: timeline
)
response._metrics = _metrics
return response
}
/// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result
/// value as a parameter.
///
/// Use the `flatMap` method with a closure that may throw an error. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let possibleObject = possibleData.flatMap {
/// 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 flatMap<T>(_ transform: (Value) throws -> T) -> DataResponse<T> {
var response = DataResponse<T>(
request: request,
response: self.response,
data: data,
result: result.flatMap(transform),
timeline: timeline
)
response._metrics = _metrics
return response
}
/// 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<Data> = ...
/// 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<E: Error>(_ transform: (Error) -> E) -> DataResponse {
var response = DataResponse(
request: request,
response: self.response,
data: data,
result: result.mapError(transform),
timeline: timeline
)
response._metrics = _metrics
return response
}
/// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `flatMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let possibleObject = possibleData.flatMapError {
/// 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 flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DataResponse {
var response = DataResponse(
request: request,
response: self.response,
data: data,
result: result.flatMapError(transform),
timeline: timeline
)
response._metrics = _metrics
return response
}
}
// MARK: -
/// Used to store all data associated with an non-serialized response of a download request.
public struct DefaultDownloadResponse {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The temporary destination URL of the data returned from the server.
public let temporaryURL: URL?
/// The final destination URL of the data returned from the server if it was moved.
public let destinationURL: URL?
/// The resume data generated if the request was cancelled.
public let resumeData: Data?
/// The error encountered while executing or validating the request.
public let error: Error?
/// The timeline of the complete lifecycle of the request.
public let timeline: Timeline
var _metrics: AnyObject?
/// Creates a `DefaultDownloadResponse` instance from the specified parameters.
///
/// - Parameters:
/// - request: The URL request sent to the server.
/// - response: The server's response to the URL request.
/// - temporaryURL: The temporary destination URL of the data returned from the server.
/// - destinationURL: The final destination URL of the data returned from the server if it was moved.
/// - resumeData: The resume data generated if the request was cancelled.
/// - error: The error encountered while executing or validating the request.
/// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default.
/// - metrics: The task metrics containing the request / response statistics. `nil` by default.
public init(
request: URLRequest?,
response: HTTPURLResponse?,
temporaryURL: URL?,
destinationURL: URL?,
resumeData: Data?,
error: Error?,
timeline: Timeline = Timeline(),
metrics: AnyObject? = nil)
{
self.request = request
self.response = response
self.temporaryURL = temporaryURL
self.destinationURL = destinationURL
self.resumeData = resumeData
self.error = error
self.timeline = timeline
}
}
// MARK: -
/// Used to store all data associated with a serialized response of a download request.
public struct DownloadResponse<Value> {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The temporary destination URL of the data returned from the server.
public let temporaryURL: URL?
/// The final destination URL of the data returned from the server if it was moved.
public let destinationURL: URL?
/// The resume data generated if the request was cancelled.
public let resumeData: Data?
/// The result of response serialization.
public let result: Result<Value>
/// The timeline of the complete lifecycle of the request.
public let timeline: Timeline
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Value? { return result.value }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Error? { return result.error }
var _metrics: AnyObject?
/// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
///
/// - parameter request: The URL request sent to the server.
/// - parameter response: The server's response to the URL request.
/// - parameter temporaryURL: The temporary destination URL of the data returned from the server.
/// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved.
/// - parameter resumeData: The resume data generated if the request was cancelled.
/// - parameter result: The result of response serialization.
/// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`.
///
/// - returns: The new `DownloadResponse` instance.
public init(
request: URLRequest?,
response: HTTPURLResponse?,
temporaryURL: URL?,
destinationURL: URL?,
resumeData: Data?,
result: Result<Value>,
timeline: Timeline = Timeline())
{
self.request = request
self.response = response
self.temporaryURL = temporaryURL
self.destinationURL = destinationURL
self.resumeData = resumeData
self.result = result
self.timeline = timeline
}
}
// 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 {
return result.debugDescription
}
/// 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 response serialization result and the
/// timeline.
public var debugDescription: String {
var output: [String] = []
output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil")
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")")
output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")")
output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)")
output.append("[Timeline]: \(timeline.debugDescription)")
return output.joined(separator: "\n")
}
}
// 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<Data> = ...
/// 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<T>(_ transform: (Value) -> T) -> DownloadResponse<T> {
var response = DownloadResponse<T>(
request: request,
response: self.response,
temporaryURL: temporaryURL,
destinationURL: destinationURL,
resumeData: resumeData,
result: result.map(transform),
timeline: timeline
)
response._metrics = _metrics
return response
}
/// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `flatMap` method with a closure that may throw an error. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let possibleObject = possibleData.flatMap {
/// 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 flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> {
var response = DownloadResponse<T>(
request: request,
response: self.response,
temporaryURL: temporaryURL,
destinationURL: destinationURL,
resumeData: resumeData,
result: result.flatMap(transform),
timeline: timeline
)
response._metrics = _metrics
return response
}
/// 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<Data> = ...
/// 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<E: Error>(_ transform: (Error) -> E) -> DownloadResponse {
var response = DownloadResponse(
request: request,
response: self.response,
temporaryURL: temporaryURL,
destinationURL: destinationURL,
resumeData: resumeData,
result: result.mapError(transform),
timeline: timeline
)
response._metrics = _metrics
return response
}
/// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `flatMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let possibleObject = possibleData.flatMapError {
/// 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 flatMapError<E: Error>(_ transform: (Error) throws -> E) -> DownloadResponse {
var response = DownloadResponse(
request: request,
response: self.response,
temporaryURL: temporaryURL,
destinationURL: destinationURL,
resumeData: resumeData,
result: result.flatMapError(transform),
timeline: timeline
)
response._metrics = _metrics
return response
}
}
// MARK: -
protocol Response {
/// The task metrics containing the request / response statistics.
var _metrics: AnyObject? { get set }
mutating func add(_ metrics: AnyObject?)
}
extension Response {
mutating func add(_ metrics: AnyObject?) {
#if !os(watchOS)
guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return }
guard let metrics = metrics as? URLSessionTaskMetrics else { return }
_metrics = metrics
#endif
}
}
// MARK: -
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
extension DefaultDataResponse: Response {
#if !os(watchOS)
/// The task metrics containing the request / response statistics.
public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics }
#endif
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
extension DataResponse: Response {
#if !os(watchOS)
/// The task metrics containing the request / response statistics.
public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics }
#endif
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
extension DefaultDownloadResponse: Response {
#if !os(watchOS)
/// The task metrics containing the request / response statistics.
public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics }
#endif
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
extension DownloadResponse: Response {
#if !os(watchOS)
/// The task metrics containing the request / response statistics.
public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics }
#endif
}
+715
View File
@@ -0,0 +1,715 @@
//
// ResponseSerialization.swift
//
// Copyright (c) 2014 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
/// The type in which all data response serializers must conform to in order to serialize a response.
public protocol DataResponseSerializerProtocol {
/// The type of serialized object to be created by this `DataResponseSerializerType`.
associatedtype SerializedObject
/// A closure used by response handlers that takes a request, response, data and error and returns a result.
var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<SerializedObject> { get }
}
// MARK: -
/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object.
public struct DataResponseSerializer<Value>: DataResponseSerializerProtocol {
/// The type of serialized object to be created by this `DataResponseSerializer`.
public typealias SerializedObject = Value
/// A closure used by response handlers that takes a request, response, data and error and returns a result.
public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>
/// Initializes the `ResponseSerializer` instance with the given serialize response closure.
///
/// - parameter serializeResponse: The closure used to serialize the response.
///
/// - returns: The new generic response serializer instance.
public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>) {
self.serializeResponse = serializeResponse
}
}
// MARK: -
/// The type in which all download response serializers must conform to in order to serialize a response.
public protocol DownloadResponseSerializerProtocol {
/// The type of serialized object to be created by this `DownloadResponseSerializerType`.
associatedtype SerializedObject
/// A closure used by response handlers that takes a request, response, url and error and returns a result.
var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<SerializedObject> { get }
}
// MARK: -
/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object.
public struct DownloadResponseSerializer<Value>: DownloadResponseSerializerProtocol {
/// The type of serialized object to be created by this `DownloadResponseSerializer`.
public typealias SerializedObject = Value
/// A closure used by response handlers that takes a request, response, url and error and returns a result.
public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>
/// Initializes the `ResponseSerializer` instance with the given serialize response closure.
///
/// - parameter serializeResponse: The closure used to serialize the response.
///
/// - returns: The new generic response serializer instance.
public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Timeline
extension Request {
var timeline: Timeline {
let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent()
let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
return Timeline(
requestStartTime: requestStartTime,
initialResponseTime: initialResponseTime,
requestCompletedTime: requestCompletedTime,
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
)
}
}
// MARK: - Default
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self {
delegate.queue.addOperation {
(queue ?? DispatchQueue.main).async {
var dataResponse = DefaultDataResponse(
request: self.request,
response: self.response,
data: self.delegate.data,
error: self.delegate.error,
timeline: self.timeline
)
dataResponse.add(self.delegate.metrics)
completionHandler(dataResponse)
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
/// and data.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response<T: DataResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void)
-> Self
{
delegate.queue.addOperation {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
var dataResponse = DataResponse<T.SerializedObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result,
timeline: self.timeline
)
dataResponse.add(self.delegate.metrics)
(queue ?? DispatchQueue.main).async { completionHandler(dataResponse) }
}
return self
}
}
extension DownloadRequest {
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DefaultDownloadResponse) -> Void)
-> Self
{
delegate.queue.addOperation {
(queue ?? DispatchQueue.main).async {
var downloadResponse = DefaultDownloadResponse(
request: self.request,
response: self.response,
temporaryURL: self.downloadDelegate.temporaryURL,
destinationURL: self.downloadDelegate.destinationURL,
resumeData: self.downloadDelegate.resumeData,
error: self.downloadDelegate.error,
timeline: self.timeline
)
downloadResponse.add(self.delegate.metrics)
completionHandler(downloadResponse)
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
/// and data contained in the destination url.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response<T: DownloadResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
-> Self
{
delegate.queue.addOperation {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.downloadDelegate.fileURL,
self.downloadDelegate.error
)
var downloadResponse = DownloadResponse<T.SerializedObject>(
request: self.request,
response: self.response,
temporaryURL: self.downloadDelegate.temporaryURL,
destinationURL: self.downloadDelegate.destinationURL,
resumeData: self.downloadDelegate.resumeData,
result: result,
timeline: self.timeline
)
downloadResponse.add(self.delegate.metrics)
(queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) }
}
return self
}
}
// MARK: - Data
extension Request {
/// Returns a result data type that contains the response data as-is.
///
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Data> {
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) }
guard let validData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
return .success(validData)
}
}
extension DataRequest {
/// Creates a response serializer that returns the associated data as-is.
///
/// - returns: A data response serializer.
public static func dataResponseSerializer() -> DataResponseSerializer<Data> {
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseData(response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseData(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<Data>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.dataResponseSerializer(),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns the associated data as-is.
///
/// - returns: A data response serializer.
public static func dataResponseSerializer() -> DownloadResponseSerializer<Data> {
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponseData(response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseData(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DownloadResponse<Data>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.dataResponseSerializer(),
completionHandler: completionHandler
)
}
}
// MARK: - String
extension Request {
/// Returns a result string type initialized from the response data with the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponseString(
encoding: String.Encoding?,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<String>
{
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") }
guard let validData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
var convertedEncoding = encoding
if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil {
convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName))
)
}
let actualEncoding = convertedEncoding ?? .isoLatin1
if let string = String(data: validData, encoding: actualEncoding) {
return .success(string)
} else {
return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)))
}
}
}
extension DataRequest {
/// Creates a response serializer that returns a result string type initialized from the response data with
/// the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
///
/// - returns: A string response serializer.
public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> {
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
/// server response, falling back to the default HTTP default character set,
/// ISO-8859-1.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseString(
queue: DispatchQueue? = nil,
encoding: String.Encoding? = nil,
completionHandler: @escaping (DataResponse<String>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns a result string type initialized from the response data with
/// the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
///
/// - returns: A string response serializer.
public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer<String> {
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
/// server response, falling back to the default HTTP default character set,
/// ISO-8859-1.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseString(
queue: DispatchQueue? = nil,
encoding: String.Encoding? = nil,
completionHandler: @escaping (DownloadResponse<String>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization`
/// with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponseJSON(
options: JSONSerialization.ReadingOptions,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<Any>
{
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
guard let validData = data, validData.count > 0 else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
do {
let json = try JSONSerialization.jsonObject(with: validData, options: options)
return .success(json)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
}
}
}
extension DataRequest {
/// Creates a response serializer that returns a JSON object result type constructed from the response data using
/// `JSONSerialization` with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
///
/// - returns: A JSON object response serializer.
public static func jsonResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> DataResponseSerializer<Any>
{
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.jsonResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns a JSON object result type constructed from the response data using
/// `JSONSerialization` with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
///
/// - returns: A JSON object response serializer.
public static func jsonResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> DownloadResponseSerializer<Any>
{
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DownloadResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.jsonResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/// Returns a plist object contained in a result type constructed from the response data using
/// `PropertyListSerialization` with the specified reading options.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponsePropertyList(
options: PropertyListSerialization.ReadOptions,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<Any>
{
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
guard let validData = data, validData.count > 0 else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
do {
let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil)
return .success(plist)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error)))
}
}
}
extension DataRequest {
/// Creates a response serializer that returns an object constructed from the response data using
/// `PropertyListSerialization` with the specified reading options.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
///
/// - returns: A property list object response serializer.
public static func propertyListResponseSerializer(
options: PropertyListSerialization.ReadOptions = [])
-> DataResponseSerializer<Any>
{
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responsePropertyList(
queue: DispatchQueue? = nil,
options: PropertyListSerialization.ReadOptions = [],
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns an object constructed from the response data using
/// `PropertyListSerialization` with the specified reading options.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
///
/// - returns: A property list object response serializer.
public static func propertyListResponseSerializer(
options: PropertyListSerialization.ReadOptions = [])
-> DownloadResponseSerializer<Any>
{
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responsePropertyList(
queue: DispatchQueue? = nil,
options: PropertyListSerialization.ReadOptions = [],
completionHandler: @escaping (DownloadResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
/// A set of HTTP response status code that do not contain response data.
private let emptyDataStatusCodes: Set<Int> = [204, 205]
+300
View File
@@ -0,0 +1,300 @@
//
// Result.swift
//
// Copyright (c) 2014 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
/// Used to represent whether a request was successful or encountered an error.
///
/// - success: The request and all post processing operations were successful resulting in the serialization of the
/// provided associated value.
///
/// - failure: The request encountered an error resulting in a failure. The associated values are the original data
/// provided by the server as well as the error that caused the failure.
public enum Result<Value> {
case success(Value)
case failure(Error)
/// Returns `true` if the result is a success, `false` otherwise.
public var isSuccess: Bool {
switch self {
case .success:
return true
case .failure:
return false
}
}
/// Returns `true` if the result is a failure, `false` otherwise.
public var isFailure: Bool {
return !isSuccess
}
/// Returns the associated value if the result is a success, `nil` otherwise.
public var value: Value? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
/// Returns the associated error value if the result is a failure, `nil` otherwise.
public var error: Error? {
switch self {
case .success:
return nil
case .failure(let error):
return error
}
}
}
// MARK: - CustomStringConvertible
extension Result: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
switch self {
case .success:
return "SUCCESS"
case .failure:
return "FAILURE"
}
}
}
// MARK: - CustomDebugStringConvertible
extension Result: CustomDebugStringConvertible {
/// The debug textual representation used when written to an output stream, which includes whether the result was a
/// success or failure in addition to the value or error.
public var debugDescription: String {
switch self {
case .success(let value):
return "SUCCESS: \(value)"
case .failure(let error):
return "FAILURE: \(error)"
}
}
}
// MARK: - Functional APIs
extension Result {
/// Creates a `Result` instance from the result of a closure.
///
/// A failure result is created when the closure throws, and a success result is created when the closure
/// succeeds without throwing an error.
///
/// func someString() throws -> String { ... }
///
/// let result = Result(value: {
/// return try someString()
/// })
///
/// // The type of result is Result<String>
///
/// The trailing closure syntax is also supported:
///
/// let result = Result { try someString() }
///
/// - parameter value: The closure to execute and create the result for.
public init(value: () throws -> Value) {
do {
self = try .success(value())
} catch {
self = .failure(error)
}
}
/// Returns the success value, or throws the failure error.
///
/// let possibleString: Result<String> = .success("success")
/// try print(possibleString.unwrap())
/// // Prints "success"
///
/// let noString: Result<String> = .failure(error)
/// try print(noString.unwrap())
/// // Throws error
public func unwrap() throws -> Value {
switch self {
case .success(let value):
return value
case .failure(let error):
throw error
}
}
/// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter.
///
/// Use the `map` method with a closure that does not throw. For example:
///
/// let possibleData: Result<Data> = .success(Data())
/// let possibleInt = possibleData.map { $0.count }
/// try print(possibleInt.unwrap())
/// // Prints "0"
///
/// let noData: Result<Data> = .failure(error)
/// let noInt = noData.map { $0.count }
/// try print(noInt.unwrap())
/// // Throws error
///
/// - parameter transform: A closure that takes the success value of the `Result` instance.
///
/// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the
/// same failure.
public func map<T>(_ transform: (Value) -> T) -> Result<T> {
switch self {
case .success(let value):
return .success(transform(value))
case .failure(let error):
return .failure(error)
}
}
/// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter.
///
/// Use the `flatMap` method with a closure that may throw an error. For example:
///
/// let possibleData: Result<Data> = .success(Data(...))
/// let possibleObject = possibleData.flatMap {
/// 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.
public func flatMap<T>(_ transform: (Value) throws -> T) -> Result<T> {
switch self {
case .success(let value):
do {
return try .success(transform(value))
} catch {
return .failure(error)
}
case .failure(let error):
return .failure(error)
}
}
/// Evaluates the specified closure when the `Result` 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: Result<Data> = .failure(someError)
/// let withMyError: Result<Data> = possibleData.mapError { MyError.error($0) }
///
/// - Parameter transform: A 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 instance.
public func mapError<T: Error>(_ transform: (Error) -> T) -> Result {
switch self {
case .failure(let error):
return .failure(transform(error))
case .success:
return self
}
}
/// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `flatMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: Result<Data> = .success(Data(...))
/// let possibleObject = possibleData.flatMapError {
/// 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 instance.
public func flatMapError<T: Error>(_ transform: (Error) throws -> T) -> Result {
switch self {
case .failure(let error):
do {
return try .failure(transform(error))
} catch {
return .failure(error)
}
case .success:
return self
}
}
/// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter.
///
/// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance.
///
/// - Parameter closure: A closure that takes the success value of this instance.
/// - Returns: This `Result` instance, unmodified.
@discardableResult
public func withValue(_ closure: (Value) throws -> Void) rethrows -> Result {
if case let .success(value) = self { try closure(value) }
return self
}
/// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance.
///
/// - Parameter closure: A closure that takes the success value of this instance.
/// - Returns: This `Result` instance, unmodified.
@discardableResult
public func withError(_ closure: (Error) throws -> Void) rethrows -> Result {
if case let .failure(error) = self { try closure(error) }
return self
}
/// Evaluates the specified closure when the `Result` is a success.
///
/// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance.
///
/// - Parameter closure: A `Void` closure.
/// - Returns: This `Result` instance, unmodified.
@discardableResult
public func ifSuccess(_ closure: () throws -> Void) rethrows -> Result {
if isSuccess { try closure() }
return self
}
/// Evaluates the specified closure when the `Result` is a failure.
///
/// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance.
///
/// - Parameter closure: A `Void` closure.
/// - Returns: This `Result` instance, unmodified.
@discardableResult
public func ifFailure(_ closure: () throws -> Void) rethrows -> Result {
if isFailure { try closure() }
return self
}
}
+307
View File
@@ -0,0 +1,307 @@
//
// ServerTrustPolicy.swift
//
// Copyright (c) 2014 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 `ServerTrustPolicy` objects to a given host.
open class ServerTrustPolicyManager {
/// The dictionary of policies mapped to a particular host.
public let policies: [String: ServerTrustPolicy]
/// Initializes the `ServerTrustPolicyManager` instance with the given policies.
///
/// Since different servers and web services can have different leaf certificates, intermediate and even root
/// certficates, 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.
///
/// - parameter policies: A dictionary of all policies mapped to a particular host.
///
/// - returns: The new `ServerTrustPolicyManager` instance.
public init(policies: [String: ServerTrustPolicy]) {
self.policies = policies
}
/// Returns the `ServerTrustPolicy` for the given host if applicable.
///
/// 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 server trust policy for the given host if found.
open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
return policies[host]
}
}
// MARK: -
extension URLSession {
private struct AssociatedKeys {
static var managerKey = "URLSession.ServerTrustPolicyManager"
}
var serverTrustPolicyManager: ServerTrustPolicyManager? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager
}
set (manager) {
objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - ServerTrustPolicy
/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
/// with a given set of criteria to determine whether the server trust is valid and the connection should be made.
///
/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
/// to route all communication over an HTTPS connection with pinning enabled.
///
/// - performDefaultEvaluation: 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.
///
/// - performRevokedEvaluation: 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.
///
/// - pinCertificates: 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.
///
/// - pinPublicKeys: 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.
///
/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
///
/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust.
public enum ServerTrustPolicy {
case performDefaultEvaluation(validateHost: Bool)
case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags)
case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
case disableEvaluation
case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool)
// MARK: - Bundle Location
/// Returns all certificates within the given bundle with a `.cer` file extension.
///
/// - parameter bundle: The bundle to search for all `.cer` files.
///
/// - returns: All certificates within the given bundle.
public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] {
var certificates: [SecCertificate] = []
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil)
}.joined())
for path in paths {
if
let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
let certificate = SecCertificateCreateWithData(nil, certificateData)
{
certificates.append(certificate)
}
}
return certificates
}
/// Returns all public keys within the given bundle with a `.cer` file extension.
///
/// - parameter bundle: The bundle to search for all `*.cer` files.
///
/// - returns: All public keys within the given bundle.
public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] {
var publicKeys: [SecKey] = []
for certificate in certificates(in: bundle) {
if let publicKey = publicKey(for: certificate) {
publicKeys.append(publicKey)
}
}
return publicKeys
}
// MARK: - Evaluation
/// Evaluates whether the server trust is valid for the given host.
///
/// - parameter serverTrust: The server trust to evaluate.
/// - parameter host: The host of the challenge protection space.
///
/// - returns: Whether the server trust is valid.
public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool {
var serverTrustIsValid = false
switch self {
case let .performDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
serverTrustIsValid = trustIsValid(serverTrust)
case let .performRevokedEvaluation(validateHost, revocationFlags):
let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
let revokedPolicy = SecPolicyCreateRevocation(revocationFlags)
SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef)
serverTrustIsValid = trustIsValid(serverTrust)
case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
serverTrustIsValid = trustIsValid(serverTrust)
} else {
let serverCertificatesDataArray = certificateData(for: serverTrust)
let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates)
outerLoop: for serverCertificateData in serverCertificatesDataArray {
for pinnedCertificateData in pinnedCertificatesDataArray {
if serverCertificateData == pinnedCertificateData {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
var certificateChainEvaluationPassed = true
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
if certificateChainEvaluationPassed {
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] {
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
if serverPublicKey.isEqual(pinnedPublicKey) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case .disableEvaluation:
serverTrustIsValid = true
case let .customEvaluation(closure):
serverTrustIsValid = closure(serverTrust, host)
}
return serverTrustIsValid
}
// MARK: - Private - Trust Validation
private func trustIsValid(_ trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType.unspecified
let proceed = SecTrustResultType.proceed
isValid = result == unspecified || result == proceed
}
return isValid
}
// MARK: - Private - Certificate Data
private func certificateData(for trust: SecTrust) -> [Data] {
var certificates: [SecCertificate] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
certificates.append(certificate)
}
}
return certificateData(for: certificates)
}
private func certificateData(for certificates: [SecCertificate]) -> [Data] {
return certificates.map { SecCertificateCopyData($0) as Data }
}
// MARK: - Private - Public Key Extraction
private static func publicKeys(for trust: SecTrust) -> [SecKey] {
var publicKeys: [SecKey] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if
let certificate = SecTrustGetCertificateAtIndex(trust, index),
let publicKey = publicKey(for: certificate)
{
publicKeys.append(publicKey)
}
}
return publicKeys
}
private static func publicKey(for certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust, trustCreationStatus == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust)
}
return publicKey
}
}
+725
View File
@@ -0,0 +1,725 @@
//
// SessionDelegate.swift
//
// Copyright (c) 2014 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 handling all delegate callbacks for the underlying session.
open class SessionDelegate: NSObject {
// MARK: URLSessionDelegate Overrides
/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`.
open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)?
/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`.
open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`.
open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`.
open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)?
// MARK: URLSessionTaskDelegate Overrides
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`.
open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
/// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and
/// requires the caller to call the `completionHandler`.
open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`.
open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and
/// requires the caller to call the `completionHandler`.
open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`.
open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
/// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and
/// requires the caller to call the `completionHandler`.
open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`.
open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`.
open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)?
// MARK: URLSessionDataDelegate Overrides
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`.
open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
/// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and
/// requires caller to call the `completionHandler`.
open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`.
open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`.
open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`.
open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
/// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and
/// requires caller to call the `completionHandler`.
open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)?
// MARK: URLSessionDownloadDelegate Overrides
/// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`.
open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
/// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`.
open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`.
open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: URLSessionStreamDelegate Overrides
#if !os(watchOS)
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? {
get {
return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void
}
set {
_streamTaskReadClosed = newValue
}
}
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? {
get {
return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void
}
set {
_streamTaskWriteClosed = newValue
}
}
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? {
get {
return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void
}
set {
_streamTaskBetterRouteDiscovered = newValue
}
}
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? {
get {
return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void
}
set {
_streamTaskDidBecomeInputStream = newValue
}
}
var _streamTaskReadClosed: Any?
var _streamTaskWriteClosed: Any?
var _streamTaskBetterRouteDiscovered: Any?
var _streamTaskDidBecomeInputStream: Any?
#endif
// MARK: Properties
var retrier: RequestRetrier?
weak var sessionManager: SessionManager?
var requests: [Int: Request] = [:]
private let lock = NSLock()
/// Access the task delegate for the specified task in a thread-safe manner.
open subscript(task: URLSessionTask) -> Request? {
get {
lock.lock() ; defer { lock.unlock() }
return requests[task.taskIdentifier]
}
set {
lock.lock() ; defer { lock.unlock() }
requests[task.taskIdentifier] = newValue
}
}
// MARK: Lifecycle
/// Initializes the `SessionDelegate` instance.
///
/// - returns: The new `SessionDelegate` instance.
public override init() {
super.init()
}
// MARK: NSObject Overrides
/// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond
/// to a specified message.
///
/// - parameter selector: A selector that identifies a message.
///
/// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`.
open override func responds(to selector: Selector) -> Bool {
#if !os(macOS)
if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) {
return sessionDidFinishEventsForBackgroundURLSession != nil
}
#endif
#if !os(watchOS)
if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) {
switch selector {
case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)):
return streamTaskReadClosed != nil
case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)):
return streamTaskWriteClosed != nil
case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)):
return streamTaskBetterRouteDiscovered != nil
case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)):
return streamTaskDidBecomeInputAndOutputStreams != nil
default:
break
}
}
#endif
switch selector {
case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default:
return type(of: self).instancesRespond(to: selector)
}
}
}
// MARK: - URLSessionDelegate
extension SessionDelegate: URLSessionDelegate {
/// Tells the delegate that the session has been invalidated.
///
/// - parameter session: The session object that was invalidated.
/// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
sessionDidBecomeInvalidWithError?(session, error)
}
/// Requests credentials from the delegate in response to a session-level authentication request from the
/// remote server.
///
/// - parameter session: The session containing the task that requested authentication.
/// - parameter challenge: An object that contains the request for authentication.
/// - parameter completionHandler: A handler that your delegate method must call providing the disposition
/// and credential.
open func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
#if !os(macOS)
/// Tells the delegate that all messages enqueued for a session have been delivered.
///
/// - parameter session: The session that no longer has any outstanding requests.
open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
#endif
}
// MARK: - URLSessionTaskDelegate
extension SessionDelegate: URLSessionTaskDelegate {
/// Tells the delegate that the remote server requested an HTTP redirect.
///
/// - parameter session: The session containing the task whose request resulted in a redirect.
/// - parameter task: The task whose request resulted in a redirect.
/// - parameter response: An object containing the servers response to the original request.
/// - parameter request: A URL request object filled out with the new location.
/// - parameter completionHandler: A closure that your handler should call with either the value of the request
/// parameter, a modified URL request object, or NULL to refuse the redirect and
/// return the body of the redirect response.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/// Requests credentials from the delegate in response to an authentication request from the remote server.
///
/// - parameter session: The session containing the task whose request requires authentication.
/// - parameter task: The task whose request requires authentication.
/// - parameter challenge: An object that contains the request for authentication.
/// - parameter completionHandler: A handler that your delegate method must call providing the disposition
/// and credential.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task]?.delegate {
delegate.urlSession(
session,
task: task,
didReceive: challenge,
completionHandler: completionHandler
)
} else {
urlSession(session, didReceive: challenge, completionHandler: completionHandler)
}
}
/// Tells the delegate when a task requires a new request body stream to send to the remote server.
///
/// - parameter session: The session containing the task that needs a new body stream.
/// - parameter task: The task that needs a new body stream.
/// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task]?.delegate {
delegate.urlSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/// Periodically informs the delegate of the progress of sending body content to the server.
///
/// - parameter session: The session containing the data task.
/// - parameter task: The data task.
/// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
/// - parameter totalBytesSent: The total number of bytes sent so far.
/// - parameter totalBytesExpectedToSend: The expected length of the body data.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task]?.delegate as? UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
#if !os(watchOS)
/// Tells the delegate that the session finished collecting metrics for the task.
///
/// - parameter session: The session collecting the metrics.
/// - parameter task: The task whose metrics have been collected.
/// - parameter metrics: The collected metrics.
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
@objc(URLSession:task:didFinishCollectingMetrics:)
open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
self[task]?.delegate.metrics = metrics
}
#endif
/// Tells the delegate that the task finished transferring data.
///
/// - parameter session: The session containing the task whose request finished transferring data.
/// - parameter task: The task whose request finished transferring data.
/// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
/// Executed after it is determined that the request is not going to be retried
let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in
guard let strongSelf = self else { return }
strongSelf.taskDidComplete?(session, task, error)
strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error)
var userInfo: [String: Any] = [Notification.Key.Task: task]
if let data = (strongSelf[task]?.delegate as? DataTaskDelegate)?.data {
userInfo[Notification.Key.ResponseData] = data
}
NotificationCenter.default.post(
name: Notification.Name.Task.DidComplete,
object: strongSelf,
userInfo: userInfo
)
strongSelf[task] = nil
}
guard let request = self[task], let sessionManager = sessionManager else {
completeTask(session, task, error)
return
}
// Run all validations on the request before checking if an error occurred
request.validations.forEach { $0() }
// Determine whether an error has occurred
var error: Error? = error
if request.delegate.error != nil {
error = request.delegate.error
}
/// If an error occurred and the retrier is set, asynchronously ask the retrier if the request
/// should be retried. Otherwise, complete the task by notifying the task delegate.
if let retrier = retrier, let error = error {
retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in
guard shouldRetry else { completeTask(session, task, error) ; return }
DispatchQueue.utility.after(timeDelay) { [weak self] in
guard let strongSelf = self else { return }
let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false
if retrySucceeded, let task = request.task {
strongSelf[task] = request
return
} else {
completeTask(session, task, error)
}
}
}
} else {
completeTask(session, task, error)
}
}
}
// MARK: - URLSessionDataDelegate
extension SessionDelegate: URLSessionDataDelegate {
/// Tells the delegate that the data task received the initial reply (headers) from the server.
///
/// - parameter session: The session containing the data task that received an initial reply.
/// - parameter dataTask: The data task that received an initial reply.
/// - parameter response: A URL response object populated with headers.
/// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
/// constant to indicate whether the transfer should continue as a data task or
/// should become a download task.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: URLSession.ResponseDisposition = .allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/// Tells the delegate that the data task was changed to a download task.
///
/// - parameter session: The session containing the task that was replaced by a download task.
/// - parameter dataTask: The data task that was replaced by a download task.
/// - parameter downloadTask: The new download task that replaced the data task.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask)
}
}
/// Tells the delegate that the data task has received some of the expected data.
///
/// - parameter session: The session containing the data task that provided data.
/// - parameter dataTask: The data task that provided data.
/// - parameter data: A data object containing the transferred data.
open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
delegate.urlSession(session, dataTask: dataTask, didReceive: data)
}
}
/// Asks the delegate whether the data (or upload) task should store the response in the cache.
///
/// - parameter session: The session containing the data (or upload) task.
/// - parameter dataTask: The data (or upload) task.
/// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
/// caching policy and the values of certain received headers, such as the Pragma
/// and Cache-Control headers.
/// - parameter completionHandler: A block that your handler must call, providing either the original proposed
/// response, a modified version of that response, or NULL to prevent caching the
/// response. If your delegate implements this method, it must call this completion
/// handler; otherwise, your app leaks memory.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
delegate.urlSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
}
// MARK: - URLSessionDownloadDelegate
extension SessionDelegate: URLSessionDownloadDelegate {
/// Tells the delegate that a download task has finished downloading.
///
/// - parameter session: The session containing the download task that finished.
/// - parameter downloadTask: The download task that finished.
/// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either
/// open the file for reading or move it to a permanent location in your apps sandbox
/// container directory before returning from this delegate method.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
}
}
/// Periodically informs the delegate about the downloads progress.
///
/// - parameter session: The session containing the download task.
/// - parameter downloadTask: The download task.
/// - parameter bytesWritten: The number of bytes transferred since the last time this delegate
/// method was called.
/// - parameter totalBytesWritten: The total number of bytes transferred so far.
/// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
/// header. If this header was not provided, the value is
/// `NSURLSessionTransferSizeUnknown`.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/// Tells the delegate that the download task has resumed downloading.
///
/// - parameter session: The session containing the download task that finished.
/// - parameter downloadTask: The download task that resumed. See explanation in the discussion.
/// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
/// existing content, then this value is zero. Otherwise, this value is an
/// integer representing the number of bytes on disk that do not need to be
/// retrieved again.
/// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
/// If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
}
// MARK: - URLSessionStreamDelegate
#if !os(watchOS)
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
extension SessionDelegate: URLSessionStreamDelegate {
/// Tells the delegate that the read side of the connection has been closed.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) {
streamTaskReadClosed?(session, streamTask)
}
/// Tells the delegate that the write side of the connection has been closed.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) {
streamTaskWriteClosed?(session, streamTask)
}
/// Tells the delegate that the system has determined that a better route to the host is available.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) {
streamTaskBetterRouteDiscovered?(session, streamTask)
}
/// Tells the delegate that the stream task has been completed and provides the unopened stream objects.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
/// - parameter inputStream: The new input stream.
/// - parameter outputStream: The new output stream.
open func urlSession(
_ session: URLSession,
streamTask: URLSessionStreamTask,
didBecome inputStream: InputStream,
outputStream: OutputStream)
{
streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream)
}
}
#endif
+899
View File
@@ -0,0 +1,899 @@
//
// SessionManager.swift
//
// Copyright (c) 2014 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 creating and managing `Request` objects, as well as their underlying `NSURLSession`.
open class SessionManager {
// MARK: - Helper Types
/// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
/// associated values.
///
/// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with
/// streaming information.
/// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
/// error.
public enum MultipartFormDataEncodingResult {
case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?)
case failure(Error)
}
// MARK: - Properties
/// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use
/// directly for any ad hoc requests.
public static let `default`: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
/// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
public static let defaultHTTPHeaders: HTTPHeaders = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joined(separator: ", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`
let userAgent: String = {
if let info = Bundle.main.infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] 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)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(macOS)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion: String = {
guard
let afInfo = Bundle(for: SessionManager.self).infoDictionary,
let build = afInfo["CFBundleShortVersionString"]
else { return "Unknown" }
return "Alamofire/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
/// Default memory threshold used when encoding `MultipartFormData` in bytes.
public static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000
/// The underlying session.
public let session: URLSession
/// The session delegate handling all the task and session delegate callbacks.
public let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
open var startRequestsImmediately: Bool = true
/// The request adapter called each time a new request is created.
open var adapter: RequestAdapter?
/// The request retrier called each time a request encounters an error to determine whether to retry the request.
open var retrier: RequestRetrier? {
get { return delegate.retrier }
set { delegate.retrier = newValue }
}
/// The background completion handler closure provided by the UIApplicationDelegate
/// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
/// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
/// will automatically call the handler.
///
/// If you need to handle your own events before the handler is called, then you need to override the
/// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
///
/// `nil` by default.
open var backgroundCompletionHandler: (() -> Void)?
let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString)
// MARK: - Lifecycle
/// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter configuration: The configuration used to construct the managed session.
/// `URLSessionConfiguration.default` by default.
/// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
/// default.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance.
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter session: The URL session.
/// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise.
public init?(
session: URLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionManager = self
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Data Request
/// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding`
/// and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `DataRequest`.
@discardableResult
open func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
var originalRequest: URLRequest?
do {
originalRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)
return request(encodedURLRequest)
} catch {
return request(originalRequest, failedWith: error)
}
}
/// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `DataRequest`.
@discardableResult
open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
var originalRequest: URLRequest?
do {
originalRequest = try urlRequest.asURLRequest()
let originalTask = DataRequest.Requestable(urlRequest: originalRequest!)
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
let request = DataRequest(session: session, requestTask: .data(originalTask, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return request(originalRequest, failedWith: error)
}
}
// MARK: Private - Request Implementation
private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest {
var requestTask: Request.RequestTask = .data(nil, nil)
if let urlRequest = urlRequest {
let originalTask = DataRequest.Requestable(urlRequest: urlRequest)
requestTask = .data(originalTask, nil)
}
let underlyingError = error.underlyingAdaptError ?? error
let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError)
if let retrier = retrier, error is AdaptError {
allowRetrier(retrier, toRetry: request, with: underlyingError)
} else {
if startRequestsImmediately { request.resume() }
}
return request
}
// MARK: - Download Request
// MARK: URL Request
/// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`,
/// `headers` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return download(encodedURLRequest, to: destination)
} catch {
return download(nil, to: destination, failedWith: error)
}
}
/// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save
/// them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ urlRequest: URLRequestConvertible,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try urlRequest.asURLRequest()
return download(.request(urlRequest), to: destination)
} catch {
return download(nil, to: destination, failedWith: error)
}
}
// MARK: Resume Data
/// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve
/// the contents of the original request and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `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 following Stack Overflow post:
///
/// - http://stackoverflow.com/a/39347461/1342462
///
/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for
/// additional information.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
resumingWith resumeData: Data,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return download(.resumeData(resumeData), to: destination)
}
// MARK: Private - Download Implementation
private func download(
_ downloadable: DownloadRequest.Downloadable,
to destination: DownloadRequest.DownloadFileDestination?)
-> DownloadRequest
{
do {
let task = try downloadable.task(session: session, adapter: adapter, queue: queue)
let download = DownloadRequest(session: session, requestTask: .download(downloadable, task))
download.downloadDelegate.destination = destination
delegate[task] = download
if startRequestsImmediately { download.resume() }
return download
} catch {
return download(downloadable, to: destination, failedWith: error)
}
}
private func download(
_ downloadable: DownloadRequest.Downloadable?,
to destination: DownloadRequest.DownloadFileDestination?,
failedWith error: Error)
-> DownloadRequest
{
var downloadTask: Request.RequestTask = .download(nil, nil)
if let downloadable = downloadable {
downloadTask = .download(downloadable, nil)
}
let underlyingError = error.underlyingAdaptError ?? error
let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError)
download.downloadDelegate.destination = destination
if let retrier = retrier, error is AdaptError {
allowRetrier(retrier, toRetry: download, with: underlyingError)
} else {
if startRequestsImmediately { download.resume() }
}
return download
}
// MARK: - Upload Request
// MARK: File
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ fileURL: URL,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(fileURL, with: urlRequest)
} catch {
return upload(nil, failedWith: error)
}
}
/// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.file(fileURL, urlRequest))
} catch {
return upload(nil, failedWith: error)
}
}
// MARK: Data
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ data: Data,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(data, with: urlRequest)
} catch {
return upload(nil, failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.data(data, urlRequest))
} catch {
return upload(nil, failedWith: error)
}
}
// MARK: InputStream
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(stream, with: urlRequest)
} catch {
return upload(nil, failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.stream(stream, urlRequest))
} catch {
return upload(nil, failedWith: error)
}
}
// MARK: MultipartFormData
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `url`, `method` and `headers`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// 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.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
queue: DispatchQueue? = nil,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
with: urlRequest,
queue: queue,
encodingCompletion: encodingCompletion
)
} catch {
(queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) }
}
}
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `urlRequest`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// 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.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter urlRequest: The URL request.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
with urlRequest: URLRequestConvertible,
queue: DispatchQueue? = nil,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
DispatchQueue.global(qos: .utility).async {
let formData = MultipartFormData()
multipartFormData(formData)
var tempFileURL: URL?
do {
var urlRequestWithContentType = try urlRequest.asURLRequest()
urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
let isBackgroundSession = self.session.configuration.identifier != nil
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
let data = try formData.encode()
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(data, with: urlRequestWithContentType),
streamingFromDisk: false,
streamFileURL: nil
)
(queue ?? DispatchQueue.main).async { encodingCompletion?(encodingResult) }
} else {
let fileManager = FileManager.default
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
tempFileURL = fileURL
var directoryError: Error?
// Create directory inside serial queue to ensure two threads don't do this in parallel
self.queue.sync {
do {
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
directoryError = error
}
}
if let directoryError = directoryError { throw directoryError }
try formData.writeEncodedData(to: fileURL)
let upload = self.upload(fileURL, with: urlRequestWithContentType)
// Cleanup the temp file once the upload is complete
upload.delegate.queue.addOperation {
do {
try FileManager.default.removeItem(at: fileURL)
} catch {
// No-op
}
}
(queue ?? DispatchQueue.main).async {
let encodingResult = MultipartFormDataEncodingResult.success(
request: upload,
streamingFromDisk: true,
streamFileURL: fileURL
)
encodingCompletion?(encodingResult)
}
}
} catch {
// Cleanup the temp file in the event that the multipart form data encoding failed
if let tempFileURL = tempFileURL {
do {
try FileManager.default.removeItem(at: tempFileURL)
} catch {
// No-op
}
}
(queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) }
}
}
}
// MARK: Private - Upload Implementation
private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest {
do {
let task = try uploadable.task(session: session, adapter: adapter, queue: queue)
let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task))
if case let .stream(inputStream, _) = uploadable {
upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream }
}
delegate[task] = upload
if startRequestsImmediately { upload.resume() }
return upload
} catch {
return upload(uploadable, failedWith: error)
}
}
private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest {
var uploadTask: Request.RequestTask = .upload(nil, nil)
if let uploadable = uploadable {
uploadTask = .upload(uploadable, nil)
}
let underlyingError = error.underlyingAdaptError ?? error
let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError)
if let retrier = retrier, error is AdaptError {
allowRetrier(retrier, toRetry: upload, with: underlyingError)
} else {
if startRequestsImmediately { upload.resume() }
}
return upload
}
#if !os(watchOS)
// MARK: - Stream Request
// MARK: Hostname and Port
/// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter hostName: The hostname of the server to connect to.
/// - parameter port: The port of the server to connect to.
///
/// - returns: The created `StreamRequest`.
@discardableResult
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open func stream(withHostName hostName: String, port: Int) -> StreamRequest {
return stream(.stream(hostName: hostName, port: port))
}
// MARK: NetService
/// Creates a `StreamRequest` for bidirectional streaming using the `netService`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter netService: The net service used to identify the endpoint.
///
/// - returns: The created `StreamRequest`.
@discardableResult
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open func stream(with netService: NetService) -> StreamRequest {
return stream(.netService(netService))
}
// MARK: Private - Stream Implementation
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest {
do {
let task = try streamable.task(session: session, adapter: adapter, queue: queue)
let request = StreamRequest(session: session, requestTask: .stream(streamable, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return stream(failedWith: error)
}
}
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
private func stream(failedWith error: Error) -> StreamRequest {
let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error)
if startRequestsImmediately { stream.resume() }
return stream
}
#endif
// MARK: - Internal - Retry Request
func retry(_ request: Request) -> Bool {
guard let originalTask = request.originalTask else { return false }
do {
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
if let originalTask = request.task {
delegate[originalTask] = nil // removes the old request to avoid endless growth
}
request.delegate.task = task // resets all task delegate data
request.retryCount += 1
request.startTime = CFAbsoluteTimeGetCurrent()
request.endTime = nil
task.resume()
return true
} catch {
request.delegate.error = error.underlyingAdaptError ?? error
return false
}
}
private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) {
DispatchQueue.utility.async { [weak self] in
guard let strongSelf = self else { return }
retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in
guard let strongSelf = self else { return }
guard shouldRetry else {
if strongSelf.startRequestsImmediately { request.resume() }
return
}
DispatchQueue.utility.after(timeDelay) {
guard let strongSelf = self else { return }
let retrySucceeded = strongSelf.retry(request)
if retrySucceeded, let task = request.task {
strongSelf.delegate[task] = request
} else {
if strongSelf.startRequestsImmediately { request.resume() }
}
}
}
}
}
}
+466
View File
@@ -0,0 +1,466 @@
//
// TaskDelegate.swift
//
// Copyright (c) 2014 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
/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
/// executing all operations attached to the serial operation queue upon task completion.
open class TaskDelegate: NSObject {
// MARK: Properties
/// The serial operation queue used to execute all operations after the task completes.
public let queue: OperationQueue
/// The data returned by the server.
public var data: Data? { return nil }
/// The error generated throughout the lifecyle of the task.
public var error: Error?
var task: URLSessionTask? {
set {
taskLock.lock(); defer { taskLock.unlock() }
_task = newValue
}
get {
taskLock.lock(); defer { taskLock.unlock() }
return _task
}
}
var initialResponseTime: CFAbsoluteTime?
var credential: URLCredential?
var metrics: AnyObject? // URLSessionTaskMetrics
private var _task: URLSessionTask? {
didSet { reset() }
}
private let taskLock = NSLock()
// MARK: Lifecycle
init(task: URLSessionTask?) {
_task = task
self.queue = {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
operationQueue.qualityOfService = .utility
return operationQueue
}()
}
func reset() {
error = nil
initialResponseTime = nil
}
// MARK: URLSessionTaskDelegate
var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)?
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
@objc(URLSession:task:didReceiveChallenge:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
@objc(URLSession:task:needNewBodyStream:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
var bodyStream: InputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
@objc(URLSession:task:didCompleteWithError:)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
if self.error == nil { self.error = error }
if
let downloadDelegate = self as? DownloadTaskDelegate,
let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data
{
downloadDelegate.resumeData = resumeData
}
}
queue.isSuspended = false
}
}
}
// MARK: -
class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
// MARK: Properties
var dataTask: URLSessionDataTask { return task as! URLSessionDataTask }
override var data: Data? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var dataStream: ((_ data: Data) -> Void)?
private var totalBytesReceived: Int64 = 0
private var mutableData: Data
private var expectedContentLength: Int64?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
mutableData = Data()
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
totalBytesReceived = 0
mutableData = Data()
expectedContentLength = nil
}
// MARK: URLSessionDataDelegate
var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
var disposition: URLSession.ResponseDisposition = .allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data)
} else {
mutableData.append(data)
}
let bytesReceived = Int64(data.count)
totalBytesReceived += bytesReceived
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
var cachedResponse: CachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
// MARK: -
class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate {
// MARK: Properties
var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask }
var progress: Progress
var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
var resumeData: Data?
override var data: Data? { return resumeData }
var destination: DownloadRequest.DownloadFileDestination?
var temporaryURL: URL?
var destinationURL: URL?
var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL }
// MARK: Lifecycle
override init(task: URLSessionTask?) {
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
resumeData = nil
}
// MARK: URLSessionDownloadDelegate
var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
temporaryURL = location
guard
let destination = destination,
let response = downloadTask.response as? HTTPURLResponse
else { return }
let result = destination(location, response)
let destinationURL = result.destinationURL
let options = result.options
self.destinationURL = destinationURL
do {
if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) {
try FileManager.default.removeItem(at: destinationURL)
}
if options.contains(.createIntermediateDirectories) {
let directory = destinationURL.deletingLastPathComponent()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
try FileManager.default.moveItem(at: location, to: destinationURL)
} catch {
self.error = error
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
// MARK: -
class UploadTaskDelegate: DataTaskDelegate {
// MARK: Properties
var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask }
var uploadProgress: Progress
var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
uploadProgress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
uploadProgress = Progress(totalUnitCount: 0)
}
// MARK: URLSessionTaskDelegate
var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
func URLSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
if let uploadProgressHandler = uploadProgressHandler {
uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) }
}
}
}
}
+136
View File
@@ -0,0 +1,136 @@
//
// Timeline.swift
//
// Copyright (c) 2014 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 computing the timing metrics for the complete lifecycle of a `Request`.
public struct Timeline {
/// The time the request was initialized.
public let requestStartTime: CFAbsoluteTime
/// The time the first bytes were received from or sent to the server.
public let initialResponseTime: CFAbsoluteTime
/// The time when the request was completed.
public let requestCompletedTime: CFAbsoluteTime
/// The time when the response serialization was completed.
public let serializationCompletedTime: CFAbsoluteTime
/// The time interval in seconds from the time the request started to the initial response from the server.
public let latency: TimeInterval
/// The time interval in seconds from the time the request started to the time the request completed.
public let requestDuration: TimeInterval
/// The time interval in seconds from the time the request completed to the time response serialization completed.
public let serializationDuration: TimeInterval
/// The time interval in seconds from the time the request started to the time response serialization completed.
public let totalDuration: TimeInterval
/// Creates a new `Timeline` instance with the specified request times.
///
/// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`.
/// - parameter initialResponseTime: The time the first bytes were received from or sent to the server.
/// Defaults to `0.0`.
/// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`.
/// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults
/// to `0.0`.
///
/// - returns: The new `Timeline` instance.
public init(
requestStartTime: CFAbsoluteTime = 0.0,
initialResponseTime: CFAbsoluteTime = 0.0,
requestCompletedTime: CFAbsoluteTime = 0.0,
serializationCompletedTime: CFAbsoluteTime = 0.0)
{
self.requestStartTime = requestStartTime
self.initialResponseTime = initialResponseTime
self.requestCompletedTime = requestCompletedTime
self.serializationCompletedTime = serializationCompletedTime
self.latency = initialResponseTime - requestStartTime
self.requestDuration = requestCompletedTime - requestStartTime
self.serializationDuration = serializationCompletedTime - requestCompletedTime
self.totalDuration = serializationCompletedTime - requestStartTime
}
}
// MARK: - CustomStringConvertible
extension Timeline: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the latency, the request
/// duration and the total duration.
public var description: String {
let latency = String(format: "%.3f", self.latency)
let requestDuration = String(format: "%.3f", self.requestDuration)
let serializationDuration = String(format: "%.3f", self.serializationDuration)
let totalDuration = String(format: "%.3f", self.totalDuration)
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
let timings = [
"\"Latency\": " + latency + " secs",
"\"Request Duration\": " + requestDuration + " secs",
"\"Serialization Duration\": " + serializationDuration + " secs",
"\"Total Duration\": " + totalDuration + " secs"
]
return "Timeline: { " + timings.joined(separator: ", ") + " }"
}
}
// MARK: - CustomDebugStringConvertible
extension Timeline: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes the request start time, the
/// initial response time, the request completed time, the serialization completed time, the latency, the request
/// duration and the total duration.
public var debugDescription: String {
let requestStartTime = String(format: "%.3f", self.requestStartTime)
let initialResponseTime = String(format: "%.3f", self.initialResponseTime)
let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime)
let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime)
let latency = String(format: "%.3f", self.latency)
let requestDuration = String(format: "%.3f", self.requestDuration)
let serializationDuration = String(format: "%.3f", self.serializationDuration)
let totalDuration = String(format: "%.3f", self.totalDuration)
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
let timings = [
"\"Request Start Time\": " + requestStartTime,
"\"Initial Response Time\": " + initialResponseTime,
"\"Request Completed Time\": " + requestCompletedTime,
"\"Serialization Completed Time\": " + serializationCompletedTime,
"\"Latency\": " + latency + " secs",
"\"Request Duration\": " + requestDuration + " secs",
"\"Serialization Duration\": " + serializationDuration + " secs",
"\"Total Duration\": " + totalDuration + " secs"
]
return "Timeline: { " + timings.joined(separator: ", ") + " }"
}
}
+315
View File
@@ -0,0 +1,315 @@
//
// Validation.swift
//
// Copyright (c) 2014 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 validation was successful or encountered an error resulting in a failure.
///
/// - success: The validation was successful.
/// - failure: The validation failed encountering the provided error.
public enum ValidationResult {
case success
case failure(Error)
}
fileprivate struct MIMEType {
let type: String
let subtype: String
var isWildcard: Bool { return type == "*" && subtype == "*" }
init?(_ string: String) {
let components: [String] = {
let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines)
#if swift(>=3.2)
let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)]
#else
let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)
#endif
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: [Int] { return Array(200..<300) }
fileprivate var acceptableContentTypes: [String] {
if let accept = request?.value(forHTTPHeaderField: "Accept") {
return accept.components(separatedBy: ",")
}
return ["*/*"]
}
// MARK: Status Code
fileprivate func validate<S: Sequence>(
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<S: Sequence>(
contentType acceptableContentTypes: S,
response: HTTPURLResponse,
data: Data?)
-> ValidationResult
where S.Iterator.Element == String
{
guard let data = data, data.count > 0 else { return .success }
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: Array(acceptableContentTypes))
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: Array(acceptableContentTypes),
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 the request, using the specified closure.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter validation: A closure to validate the request.
///
/// - returns: The request.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validationExecution: () -> Void = { [unowned self] in
if
let response = self.response,
self.delegate.error == nil,
case let .failure(error) = validation(self.request, response, self.delegate.data)
{
self.delegate.error = error
}
}
validations.append(validationExecution)
return self
}
/// 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 range: The range of acceptable status codes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
return validate { [unowned self] _, response, _ in
return 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<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
return validate { [unowned self] _, response, data in
return 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 {
return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes)
}
}
// 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,
_ temporaryURL: URL?,
_ destinationURL: URL?)
-> ValidationResult
/// Validates the request, using the specified closure.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter validation: A closure to validate the request.
///
/// - returns: The request.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validationExecution: () -> Void = { [unowned self] in
let request = self.request
let temporaryURL = self.downloadDelegate.temporaryURL
let destinationURL = self.downloadDelegate.destinationURL
if
let response = self.response,
self.delegate.error == nil,
case let .failure(error) = validation(request, response, temporaryURL, destinationURL)
{
self.delegate.error = error
}
}
validations.append(validationExecution)
return self
}
/// 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 range: The range of acceptable status codes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
return validate { [unowned self] _, response, _, _ in
return 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<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
return validate { [unowned self] _, response, _, _ in
let fileURL = self.downloadDelegate.fileURL
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 {
return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes)
}
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 - 2015 Atsushi Kiwaki (@_tid_)
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.
+3
View File
@@ -0,0 +1,3 @@
#import <libxml2/libxml/HTMLtree.h>
#import <libxml2/libxml/xpath.h>
#import <libxml2/libxml/xpathInternals.h>
+6
View File
@@ -0,0 +1,6 @@
module libxmlKanna [system] {
link "xml2"
umbrella header "libxml2-kanna.h"
export *
module * { export * }
}
+228
View File
@@ -0,0 +1,228 @@
Kanna(鉋)
=================
Kanna(鉋) is an XML/HTML parser for cross-platform(macOS, iOS, tvOS, watchOS and Linux!).
It was inspired by [Nokogiri](https://github.com/sparklemotion/nokogiri)(鋸).
[![Build Status](https://travis-ci.org/tid-kijyun/Kanna.svg?branch=master)](https://travis-ci.org/tid-kijyun/Kanna)
[![Platform](http://img.shields.io/badge/platform-ios_osx_watchos_tvos_linux-lightgrey.svg?style=flat)](https://developer.apple.com/resources/)
[![Cocoapod](http://img.shields.io/cocoapods/v/Kanna.svg?style=flat)](http://cocoadocs.org/docsets/Kanna/)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Swift Package Manager](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager)
[![Reference Status](https://www.versioneye.com/objective-c/kanna/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/kanna/references)
:information_source: [Documentation](http://tid-kijyun.github.io/Kanna/)
Features:
=================
- [x] XPath 1.0 support for document searching
- [x] CSS3 selector support for document searching
- [x] Support for namespaces
- [x] Comprehensive test suite
Installation:
=================
### Swift 5
##### CocoaPods
Adding it to your `Podfile`:
```ruby
use_frameworks!
pod 'Kanna', '~> 5.0.0'
```
##### Carthage
Adding it to your `Cartfile`:
```ogdl
github "tid-kijyun/Kanna" ~> 5.0.0
```
1. In the project settings add `$(SDKROOT)/usr/include/libxml2` to the "header search paths" field
##### Others(Swift PM and manual Installation)
Please refer to the case of Swift 4.
### Swift 4
##### CocoaPods
**:warning: CocoaPods (`1.1.0 or later`) is required.**
Adding it to your `Podfile`:
```ruby
use_frameworks!
pod 'Kanna', '~> 4.0.0'
```
##### Carthage
Adding it to your `Cartfile`:
```ogdl
github "tid-kijyun/Kanna" ~> 4.0.0
```
1. In the project settings add `$(SDKROOT)/usr/include/libxml2` to the "header search paths" field
##### Swift Package Manager
Installing libxml2 to your computer:
```bash
// macOS
$ brew install libxml2
$ brew link --force libxml2
// Linux(Ubuntu)
$ sudo apt-get install libxml2-dev
```
Adding it to your `Package.swift`:
```swift
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "YourProject",
dependencies: [
.package(url: "https://github.com/tid-kijyun/Kanna.git", from: "4.0.0")
],
targets: [
.target(
name: "YourTarget",
dependencies: ["Kanna"]),
]
)
```
```bash
$ swift build
```
*Note: When a build error occurs, please try run the following command:*
```bash
$ sudo apt-get install pkg-config
```
##### Manual Installation
1. Add these files to your project:
[Kanna.swift](Source/Kanna.swift)
[CSS.swift](Source/CSS.swift)
[libxmlHTMLDocument.swift](Source/libxml/libxmlHTMLDocument.swift)
[libxmlHTMLNode.swift](Source/libxml/libxmlHTMLNode.swift)
[libxmlParserOption.swift](Source/libxml/libxmlParserOption.swift)
[Modules](Modules)
1. In the target settings add `$(SDKROOT)/usr/include/libxml2` to the `Search Paths > Header Search Paths` field
1. In the target settings add `$(SRCROOT)/Modules` to the `Swift Compiler - Search Paths > Import Paths` field
### Swift 3.0
For now, please use the `feature/v3.0.0` branch.
##### CocoaPods
**:warning: CocoaPods (`1.1.0 or later`) is required.**
Adding it to your `Podfile`:
```ruby
use_frameworks!
pod 'Kanna', :git => 'https://github.com/tid-kijyun/Kanna', :branch => 'feature/v3.0.0'
```
##### Carthage
Adding it to your `Cartfile`:
```ogdl
github "tid-kijyun/Kanna" "feature/v3.0.0"
```
1. In the project settings add `$(SDKROOT)/usr/include/libxml2` to the "header search paths" field
##### Swift Package Manager
Installing libxml2 to your computer:
```bash
// macOS
$ brew install libxml2
$ brew link --force libxml2
// Linux(Ubuntu)
$ sudo apt-get install libxml2-dev
```
Adding it to your `Package.swift`:
```swift
import PackageDescription
let package = Package(
name: "YourProject",
dependencies: [
.Package(url: "https://github.com/tid-kijyun/Kanna.git", majorVersion: 2)
]
)
```
```bash
$ swift build
```
*Note: When a build error occurs, please try run the following command:*
```bash
$ sudo apt-get install pkg-config
```
##### Manual Installation
1. Add these files to your project:
[Kanna.swift](Source/Kanna.swift)
[CSS.swift](Source/CSS.swift)
[libxmlHTMLDocument.swift](Source/libxml/libxmlHTMLDocument.swift)
[libxmlHTMLNode.swift](Source/libxml/libxmlHTMLNode.swift)
[libxmlParserOption.swift](Source/libxml/libxmlParserOption.swift)
[Modules](Modules)
1. In the target settings add `$(SDKROOT)/usr/include/libxml2` to the `Search Paths > Header Search Paths` field
1. In the target settings add `$(SRCROOT)/Modules` to the `Swift Compiler - Search Paths > Import Paths` field
Synopsis:
=================
```swift
import Kanna
let html = "<html>...</html>"
if let doc = try? HTML(html: html, encoding: .utf8) {
print(doc.title)
// Search for nodes by CSS
for link in doc.css("a, link") {
print(link.text)
print(link["href"])
}
// Search for nodes by XPath
for link in doc.xpath("//a | //link") {
print(link.text)
print(link["href"])
}
}
```
```swift
let xml = "..."
if let doc = try? Kanna.XML(xml: xml, encoding: .utf8) {
let namespaces = [
"o": "urn:schemas-microsoft-com:office:office",
"ss": "urn:schemas-microsoft-com:office:spreadsheet"
]
if let author = doc.at_xpath("//o:Author", namespaces: namespaces) {
print(author.text)
}
}
```
License:
=================
The MIT License. See the LICENSE file for more information.
+366
View File
@@ -0,0 +1,366 @@
/**@file CSS.swift
Kanna
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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
import libxmlKanna
typealias AKRegularExpression = NSRegularExpression
#if os(Linux) && swift(>=4)
typealias AKTextCheckingResult = NSTextCheckingResult
#elseif os(Linux) && swift(>=3)
typealias AKTextCheckingResult = TextCheckingResult
#else
typealias AKTextCheckingResult = NSTextCheckingResult
#endif
public enum CSSError: Error {
case UnsupportSyntax(String)
}
/**
CSS
*/
public enum CSS {
/**
CSS3 selector to XPath
@param selector CSS3 selector
@return XPath
*/
public static func toXPath(_ css: String) throws -> String {
let selectorGroups = css.components(separatedBy: ",")
return try selectorGroups
.map { try toXPath(selector: $0) }
.joined(separator: " | ")
}
private static func toXPath(selector: String) throws -> String {
var xpath = "//"
var str = selector
var prev = str
while !str.isEmpty {
var attributes: [String] = []
var combinator: String = ""
str = str.trimmingCharacters(in: .whitespaces)
// element
let element = getElement(&str)
// class / id
while let attr = getClassId(&str) {
attributes.append(attr)
}
// attribute
while let attr = getAttribute(&str) {
attributes.append(attr)
}
// matchCombinator
if let combi = genCombinator(&str) {
combinator = combi
}
// generate xpath phrase
let attr = attributes.joined(separator: " and ")
if attr.isEmpty {
xpath += "\(element)\(combinator)"
} else {
xpath += "\(element)[\(attr)]\(combinator)"
}
if str == prev {
throw CSSError.UnsupportSyntax(selector)
}
prev = str
}
return xpath
}
}
private func firstMatch(_ pattern: String) -> (String) -> AKTextCheckingResult? {
return { str in
let length = str.utf16.count
do {
let regex = try AKRegularExpression(pattern: pattern, options: .caseInsensitive)
if let result = regex.firstMatch(in: str, options: .reportProgress, range: NSRange(location: 0, length: length)) {
return result
}
} catch _ {
}
return nil
}
}
private func nth(prefix: String, a: Int, b: Int) -> String {
let sibling = "\(prefix)-sibling::*"
if a == 0 {
return "count(\(sibling)) = \(b-1)"
} else if a > 0 {
if b != 0 {
return "((count(\(sibling)) + 1) >= \(b)) and ((((count(\(sibling)) + 1)-\(b)) mod \(a)) = 0)"
}
return "((count(\(sibling)) + 1) mod \(a)) = 0"
}
let a = abs(a)
return "(count(\(sibling)) + 1) <= \(b)" + ((a != 1) ? " and ((((count(\(sibling)) + 1)-\(b)) mod \(a) = 0)" : "")
}
// a(n) + b | a(n) - b
private func nth_child(a: Int, b: Int) -> String {
return nth(prefix: "preceding", a: a, b: b)
}
private func nth_last_child(a: Int, b: Int) -> String {
return nth(prefix: "following", a: a, b: b)
}
private let escapePattern = "(?:\\\\([!\"#\\$%&\'\\(\\)\\*\\+,\\./:;<=>\\?@\\[\\\\\\]\\^`\\{\\|\\}~]))"
private let escapeRepeatPattern = "\(escapePattern)*"
private let matchElement = firstMatch("^((?:[a-z0-9\\*_-]+\(escapeRepeatPattern))+)((\\|)((?:[a-z0-9\\*_-]+\(escapeRepeatPattern))+))?")
private let matchClassId = firstMatch("^([#.])((?:[a-z0-9\\*_-]+\(escapeRepeatPattern))+)")
private let matchAttr1 = firstMatch("^\\[([^\\]]*)\\]")
private let matchAttr2 = firstMatch("^\\[\\s*([^~\\|\\^\\$\\*=\\s]+)\\s*([~\\|\\^\\$\\*]?=)\\s*(.*)\\s*\\]")
private let matchAttrN = firstMatch("^:not\\((.*?\\)?)\\)")
private let matchPseudo = firstMatch("^:([\'\"()a-z0-9_+-]+)")
private let matchCombinator = firstMatch("^\\s*([\\s>+~,])\\s*")
private let matchSubNthChild = firstMatch("^(nth-child|nth-last-child)\\(\\s*(odd|even|\\d+)\\s*\\)")
private let matchSubNthChildN = firstMatch("^(nth-child|nth-last-child)\\(\\s*(-?\\d*)n(\\+\\d+)?\\s*\\)")
private let matchSubNthOfType = firstMatch("nth-of-type\\((odd|even|\\d+)\\)")
private let matchSubContains = firstMatch("contains\\([\"\'](.*?)[\"\']\\)")
private func substringWithRangeAtIndex(_ result: AKTextCheckingResult, str: String, at: Int) -> String {
if result.numberOfRanges > at {
#if swift(>=4.0) || os(Linux)
let range = result.range(at: at)
#else
let range = result.rangeAt(at)
#endif
if range.length > 0 {
let startIndex = str.index(str.startIndex, offsetBy: range.location)
let endIndex = str.index(startIndex, offsetBy: range.length)
return String(str[startIndex..<endIndex])
}
}
return ""
}
private func escapeCSS(_ text: String) -> String {
return text.replacingOccurrences(of: escapePattern, with: "$1", options: .regularExpression, range: nil)
}
private func getElement(_ str: inout String, skip: Bool = true) -> String {
if let result = matchElement(str) {
let (text, text2) = (escapeCSS(substringWithRangeAtIndex(result, str: str, at: 1)),
escapeCSS(substringWithRangeAtIndex(result, str: str, at: 5)))
if skip {
str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..<str.endIndex])
}
// tag with namespace
if !text.isEmpty && !text2.isEmpty {
return "\(text):\(text2)"
}
// tag
if !text.isEmpty {
return text
}
}
return "*"
}
private func getClassId(_ str: inout String, skip: Bool = true) -> String? {
if let result = matchClassId(str) {
let (attr, text) = (escapeCSS(substringWithRangeAtIndex(result, str: str, at: 1)),
escapeCSS(substringWithRangeAtIndex(result, str: str, at: 2)))
if skip {
str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..<str.endIndex])
}
if attr.hasPrefix("#") {
return "@id = '\(text)'"
} else if attr.hasPrefix(".") {
return "contains(concat(' ', normalize-space(@class), ' '), ' \(text) ')"
}
}
return nil
}
private func getAttribute(_ str: inout String, skip: Bool = true) -> String? {
if let result = matchAttr2(str) {
let (attr, expr, text) = (escapeCSS(substringWithRangeAtIndex(result, str: str, at: 1)),
substringWithRangeAtIndex(result, str: str, at: 2),
escapeCSS(substringWithRangeAtIndex(result, str: str, at: 3).replacingOccurrences(of: "[\'\"](.*)[\'\"]", with: "$1", options: .regularExpression, range: nil)))
if skip {
str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..<str.endIndex])
}
switch expr {
case "!=":
return "@\(attr) != \(text)"
case "~=":
return "contains(concat(' ', @\(attr), ' '),concat(' ', '\(text)', ' '))"
case "|=":
return "@\(attr) = '\(text)' or starts-with(@\(attr),concat('\(text)', '-'))"
case "^=":
return "starts-with(@\(attr), '\(text)')"
case "$=":
return "substring(@\(attr), string-length(@\(attr)) - string-length('\(text)') + 1, string-length('\(text)')) = '\(text)'"
case "*=":
return "contains(@\(attr), '\(text)')"
default:
return "@\(attr) = '\(text)'"
}
} else if let result = matchAttr1(str) {
let atr = substringWithRangeAtIndex(result, str: str, at: 1)
if skip {
str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..<str.endIndex])
}
return "@\(atr)"
} else if str.hasPrefix("[") {
// bad syntax attribute
return nil
} else if let attr = getAttrNot(&str) {
return "not(\(attr))"
} else if let result = matchPseudo(str) {
let one = substringWithRangeAtIndex(result, str: str, at: 1)
if skip {
str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..<str.endIndex])
}
switch one {
case "first-child":
return "count(preceding-sibling::*) = 0"
case "last-child":
return "count(following-sibling::*) = 0"
case "only-child":
return "count(preceding-sibling::*) = 0 and count(following-sibling::*) = 0"
case "first-of-type":
return "position() = 1"
case "last-of-type":
return "position() = last()"
case "only-of-type":
return "last() = 1"
case "empty":
return "not(node())"
case "root":
return "not(parent::*)"
default:
if let sub = matchSubNthChild(one) {
let (nth, arg1) = (substringWithRangeAtIndex(sub, str: one, at: 1),
substringWithRangeAtIndex(sub, str: one, at: 2))
let nthFunc = (nth == "nth-child") ? nth_child : nth_last_child
if arg1 == "odd" {
return nthFunc(2, 1)
} else if arg1 == "even" {
return nthFunc(2, 0)
} else {
return nthFunc(0, Int(arg1)!)
}
} else if let sub = matchSubNthChildN(one) {
let (nth, arg1, arg2) = (substringWithRangeAtIndex(sub, str: one, at: 1),
substringWithRangeAtIndex(sub, str: one, at: 2),
substringWithRangeAtIndex(sub, str: one, at: 3))
let nthFunc = (nth == "nth-child") ? nth_child : nth_last_child
let a: Int = (arg1 == "-") ? -1 : Int(arg1)!
let b: Int = (arg2.isEmpty) ? 0 : Int(arg2)!
return nthFunc(a, b)
} else if let sub = matchSubNthOfType(one) {
let arg1 = substringWithRangeAtIndex(sub, str: one, at: 1)
if arg1 == "odd" {
return "(position() >= 1) and (((position()-1) mod 2) = 0)"
} else if arg1 == "even" {
return "(position() mod 2) = 0"
} else {
return "position() = \(arg1)"
}
} else if let sub = matchSubContains(one) {
let text = substringWithRangeAtIndex(sub, str: one, at: 1)
return "contains(., '\(text)')"
} else {
return nil
}
}
}
return nil
}
private func getAttrNot(_ str: inout String, skip: Bool = true) -> String? {
if let result = matchAttrN(str) {
var one = substringWithRangeAtIndex(result, str: str, at: 1)
if skip {
str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..<str.endIndex])
}
if let attr = getAttribute(&one, skip: false) {
return attr
} else if let sub = matchElement(one) {
#if swift(>=4.0) || os(Linux)
let range = sub.range(at: 1)
#else
let range = sub.rangeAt(1)
#endif
let startIndex = one.index(one.startIndex, offsetBy: range.location)
let endIndex = one.index(startIndex, offsetBy: range.length)
let elem = one[startIndex ..< endIndex]
return "self::\(elem)"
} else if let attr = getClassId(&one) {
return attr
}
}
return nil
}
private func genCombinator(_ str: inout String, skip: Bool = true) -> String? {
if let result = matchCombinator(str) {
let one = substringWithRangeAtIndex(result, str: str, at: 1)
if skip {
str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..<str.endIndex])
}
switch one {
case ">":
return "/"
case "+":
return "/following-sibling::*[1]/self::"
case "~":
return "/following-sibling::"
default:
return "//"
}
}
return nil
}
+45
View File
@@ -0,0 +1,45 @@
//
// Deprecated.swift
// Kanna
//
// Created by Atsushi Kiwaki on 2017/10/27.
// Copyright © 2017 Atsushi Kiwaki. All rights reserved.
//
import Foundation
//-------------------------------------------------------------
// XML
//-------------------------------------------------------------
@available(*, unavailable, message: "Use XML(xml: String, url: String?, encoding: String.Encoding, option: ParseOption). The type of the second argument has been changed to String.Encoding from UInt.")
public func XML(xml: String, url: String? = nil, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? {
return nil
}
@available(*, unavailable, message: "Use XML(xml: Data, url: String?, encoding: String.Encoding, option: ParseOption). The type of the first argument has been changed to Data and the type of the second argument has been changed to String.Encoding from UInt.")
public func XML(xml: NSData, url: String? = nil, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? {
return nil
}
@available(*, unavailable, message: "Use XML(url: URL, encoding: String.Encoding, option: ParseOption). The type of the second argument has been changed to String.Encoding from UInt.")
public func XML(url: URL, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? {
return nil
}
//-------------------------------------------------------------
// HTML
//-------------------------------------------------------------
@available(*, unavailable, message: "Use HTML(html: String, url: String?, encoding: String.Encoding, option: ParseOption). The type of the second argument has been changed to String.Encoding from UInt.")
public func HTML(html: String, url: String? = nil, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? {
return nil
}
@available(*, unavailable, message: "Use HTML(html: Data, url: String?, encoding: String.Encoding, option: ParseOption). The type of the first argument has been changed to Data and the type of the second argument has been changed to String.Encoding from UInt.")
public func HTML(html: NSData, url: String? = nil, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? {
return nil
}
@available(*, unavailable, message: "Use HTML(url: URL, encoding: String.Encoding, option: ParseOption). The type of the second argument has been changed to String.Encoding from UInt.")
public func HTML(url: URL, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? {
return nil
}
+33
View File
@@ -0,0 +1,33 @@
/**@file Kanna.h
Kanna
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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/Foundation.h>
//! Project version number for Kanna.
FOUNDATION_EXPORT double KannaVersionNumber;
//! Project version string for Kanna.
FOUNDATION_EXPORT const unsigned char KannaVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <Kanna/PublicHeader.h>
+381
View File
@@ -0,0 +1,381 @@
/**@file Kanna.swift
Kanna
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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
import libxmlKanna
/*
ParseOption
*/
public enum ParseOption {
// libxml2
case xmlParseUseLibxml(Libxml2XMLParserOptions)
case htmlParseUseLibxml(Libxml2HTMLParserOptions)
}
public let kDefaultXmlParseOption = ParseOption.xmlParseUseLibxml([.RECOVER, .NOERROR, .NOWARNING])
public let kDefaultHtmlParseOption = ParseOption.htmlParseUseLibxml([.RECOVER, .NOERROR, .NOWARNING])
public enum ParseError: Error {
case Empty
case EncodingMismatch
case InvalidOptions
}
/**
Parse XML
@param xml an XML string
@param url the base URL to use for the document
@param encoding the document encoding
@param options a ParserOption
*/
public func XML(xml: String, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) throws -> XMLDocument {
switch option {
case .xmlParseUseLibxml(let opt):
return try libxmlXMLDocument(xml: xml, url: url, encoding: encoding, option: opt.rawValue)
default:
throw ParseError.InvalidOptions
}
}
// NSData
public func XML(xml: Data, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) throws -> XMLDocument {
guard let xmlStr = String(data: xml, encoding: encoding) else {
throw ParseError.EncodingMismatch
}
return try XML(xml: xmlStr, url: url, encoding: encoding, option: option)
}
// NSURL
public func XML(url: URL, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) throws -> XMLDocument {
guard let data = try? Data(contentsOf: url) else {
throw ParseError.EncodingMismatch
}
return try XML(xml: data, url: url.absoluteString, encoding: encoding, option: option)
}
/**
Parse HTML
@param html an HTML string
@param url the base URL to use for the document
@param encoding the document encoding
@param options a ParserOption
*/
public func HTML(html: String, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) throws -> HTMLDocument {
switch option {
case .htmlParseUseLibxml(let opt):
return try libxmlHTMLDocument(html: html, url: url, encoding: encoding, option: opt.rawValue)
default:
throw ParseError.InvalidOptions
}
}
// NSData
public func HTML(html: Data, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) throws -> HTMLDocument {
guard let htmlStr = String(data: html, encoding: encoding) else {
throw ParseError.EncodingMismatch
}
return try HTML(html: htmlStr, url: url, encoding: encoding, option: option)
}
// NSURL
public func HTML(url: URL, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) throws -> HTMLDocument {
guard let data = try? Data(contentsOf: url) else {
throw ParseError.EncodingMismatch
}
return try HTML(html: data, url: url.absoluteString, encoding: encoding, option: option)
}
/**
Searchable
*/
public protocol Searchable {
/**
Search for node from current node by XPath.
@param xpath
*/
func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject
func xpath(_ xpath: String) -> XPathObject
func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement?
func at_xpath(_ xpath: String) -> XMLElement?
/**
Search for node from current node by CSS selector.
@param selector a CSS selector
*/
func css(_ selector: String, namespaces: [String:String]?) -> XPathObject
func css(_ selector: String) -> XPathObject
func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement?
func at_css(_ selector: String) -> XMLElement?
}
/**
SearchableNode
*/
public protocol SearchableNode: Searchable {
var text: String? { get }
var toHTML: String? { get }
var toXML: String? { get }
var innerHTML: String? { get }
var className: String? { get }
var tagName: String? { get set }
var content: String? { get set }
}
/**
XMLElement
*/
public protocol XMLElement: SearchableNode {
var parent: XMLElement? { get set }
subscript(attr: String) -> String? { get set }
func addPrevSibling(_ node: XMLElement)
func addNextSibling(_ node: XMLElement)
func removeChild(_ node: XMLElement)
var nextSibling: XMLElement? { get }
var previousSibling: XMLElement? { get }
}
/**
XMLDocument
*/
public protocol XMLDocument: class, SearchableNode {
}
/**
HTMLDocument
*/
public protocol HTMLDocument: XMLDocument {
var title: String? { get }
var head: XMLElement? { get }
var body: XMLElement? { get }
}
/**
XMLNodeSet
*/
public final class XMLNodeSet {
fileprivate var nodes: [XMLElement] = []
public var toHTML: String? {
let html = nodes.reduce("") {
if let text = $1.toHTML {
return $0 + text
}
return $0
}
return html.isEmpty == false ? html : nil
}
public var innerHTML: String? {
let html = nodes.reduce("") {
if let text = $1.innerHTML {
return $0 + text
}
return $0
}
return html.isEmpty == false ? html : nil
}
public var text: String? {
let html = nodes.reduce("") {
if let text = $1.text {
return $0 + text
}
return $0
}
return html
}
public subscript(index: Int) -> XMLElement {
return nodes[index]
}
public var count: Int {
return nodes.count
}
internal init() {
}
internal init(nodes: [XMLElement]) {
self.nodes = nodes
}
public func at(_ index: Int) -> XMLElement? {
return count > index ? nodes[index] : nil
}
public var first: XMLElement? {
return at(0)
}
public var last: XMLElement? {
return at(count-1)
}
}
extension XMLNodeSet: Sequence {
public typealias Iterator = AnyIterator<XMLElement>
public func makeIterator() -> Iterator {
var index = 0
return AnyIterator {
if index < self.nodes.count {
let n = self.nodes[index]
index += 1
return n
}
return nil
}
}
}
/**
XPathObject
*/
public enum XPathObject {
case none
case NodeSet(nodeset: XMLNodeSet)
case Bool(bool: Swift.Bool)
case Number(num: Double)
case String(text: Swift.String)
}
extension XPathObject {
internal init(document: XMLDocument?, docPtr: xmlDocPtr, object: xmlXPathObject) {
switch object.type {
case XPATH_NODESET:
let nodeSet = object.nodesetval
if nodeSet == nil || nodeSet?.pointee.nodeNr == 0 || nodeSet?.pointee.nodeTab == nil {
self = .none
return
}
var nodes : [XMLElement] = []
let size = Int((nodeSet?.pointee.nodeNr)!)
for i in 0 ..< size {
let node: xmlNodePtr = nodeSet!.pointee.nodeTab[i]!
let htmlNode = libxmlHTMLNode(document: document, docPtr: docPtr, node: node)
nodes.append(htmlNode)
}
self = .NodeSet(nodeset: XMLNodeSet(nodes: nodes))
return
case XPATH_BOOLEAN:
self = .Bool(bool: object.boolval != 0)
return
case XPATH_NUMBER:
self = .Number(num: object.floatval)
case XPATH_STRING:
guard let str = UnsafeRawPointer(object.stringval)?.assumingMemoryBound(to: CChar.self) else {
self = .String(text: "")
return
}
self = .String(text: Swift.String(cString: str))
return
default:
self = .none
return
}
}
public subscript(index: Int) -> XMLElement {
return nodeSet![index]
}
public var first: XMLElement? {
return nodeSet?.first
}
public var count: Int {
guard let nodeset = nodeSet else {
return 0
}
return nodeset.count
}
var nodeSet: XMLNodeSet? {
if case let .NodeSet(nodeset) = self {
return nodeset
}
return nil
}
var bool: Swift.Bool? {
if case let .Bool(value) = self {
return value
}
return nil
}
var number: Double? {
if case let .Number(value) = self {
return value
}
return nil
}
var string: Swift.String? {
if case let .String(value) = self {
return value
}
return nil
}
var nodeSetValue: XMLNodeSet {
return nodeSet ?? XMLNodeSet()
}
var boolValue: Swift.Bool {
return bool ?? false
}
var numberValue: Double {
return number ?? 0.0
}
var stringValue: Swift.String {
return string ?? ""
}
}
extension XPathObject: Sequence {
public typealias Iterator = AnyIterator<XMLElement>
public func makeIterator() -> Iterator {
var index = 0
return AnyIterator {
if index < self.nodeSetValue.count {
let obj = self.nodeSetValue[index]
index += 1
return obj
}
return nil
}
}
}
+393
View File
@@ -0,0 +1,393 @@
/**@file libxmlHTMLDocument.swift
Kanna
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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
import CoreFoundation
import libxmlKanna
extension String.Encoding {
var IANACharSetName: String? {
#if os(Linux) && swift(>=4)
switch self {
case .ascii:
return "us-ascii"
case .iso2022JP:
return "iso-2022-jp"
case .isoLatin1:
return "iso-8859-1"
case .isoLatin2:
return "iso-8859-2"
case .japaneseEUC:
return "euc-jp"
case .macOSRoman:
return "macintosh"
case .nextstep:
return "x-nextstep"
case .nonLossyASCII:
return nil
case .shiftJIS:
return "cp932"
case .symbol:
return "x-mac-symbol"
case .unicode:
return "utf-16"
case .utf16:
return "utf-16"
case .utf16BigEndian:
return "utf-16be"
case .utf32:
return "utf-32"
case .utf32BigEndian:
return "utf-32be"
case .utf32LittleEndian:
return "utf-32le"
case .utf8:
return "utf-8"
case .windowsCP1250:
return "windows-1250"
case .windowsCP1251:
return "windows-1251"
case .windowsCP1252:
return "windows-1252"
case .windowsCP1253:
return "windows-1253"
case .windowsCP1254:
return "windows-1254"
default:
return nil
}
#elseif os(Linux) && swift(>=3)
switch self {
case String.Encoding.ascii:
return "us-ascii"
case String.Encoding.iso2022JP:
return "iso-2022-jp"
case String.Encoding.isoLatin1:
return "iso-8859-1"
case String.Encoding.isoLatin2:
return "iso-8859-2"
case String.Encoding.japaneseEUC:
return "euc-jp"
case String.Encoding.macOSRoman:
return "macintosh"
case String.Encoding.nextstep:
return "x-nextstep"
case String.Encoding.nonLossyASCII:
return nil
case String.Encoding.shiftJIS:
return "cp932"
case String.Encoding.symbol:
return "x-mac-symbol"
case String.Encoding.unicode:
return "utf-16"
case String.Encoding.utf16:
return "utf-16"
case String.Encoding.utf16BigEndian:
return "utf-16be"
case String.Encoding.utf32:
return "utf-32"
case String.Encoding.utf32BigEndian:
return "utf-32be"
case String.Encoding.utf32LittleEndian:
return "utf-32le"
case String.Encoding.utf8:
return "utf-8"
case String.Encoding.windowsCP1250:
return "windows-1250"
case String.Encoding.windowsCP1251:
return "windows-1251"
case String.Encoding.windowsCP1252:
return "windows-1252"
case String.Encoding.windowsCP1253:
return "windows-1253"
case String.Encoding.windowsCP1254:
return "windows-1254"
default:
return nil
}
#else
let cfenc = CFStringConvertNSStringEncodingToEncoding(self.rawValue)
guard let cfencstr = CFStringConvertEncodingToIANACharSetName(cfenc) else {
return nil
}
return String(describing: cfencstr)
#endif
}
}
/*
libxmlHTMLDocument
*/
internal final class libxmlHTMLDocument: HTMLDocument {
fileprivate var docPtr: htmlDocPtr? = nil
fileprivate var rootNode: XMLElement?
fileprivate var html: String
fileprivate var url: String?
fileprivate var encoding: String.Encoding
var text: String? {
return rootNode?.text
}
var toHTML: String? {
let buf = xmlBufferCreate()
let outputBuf = xmlOutputBufferCreateBuffer(buf, nil)
defer {
xmlOutputBufferClose(outputBuf)
xmlBufferFree(buf)
}
htmlDocContentDumpOutput(outputBuf, docPtr, nil)
let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf)))
return html
}
var toXML: String? {
var buf: UnsafeMutablePointer<xmlChar>? = nil
let size: UnsafeMutablePointer<Int32>? = nil
defer {
xmlFree(buf)
}
xmlDocDumpMemory(docPtr, &buf, size)
let html = String(cString: UnsafePointer<UInt8>(buf!))
return html
}
var innerHTML: String? {
return rootNode?.innerHTML
}
var className: String? {
return nil
}
var tagName: String? {
get {
return nil
}
set {
}
}
var content: String? {
get {
return text
}
set {
rootNode?.content = newValue
}
}
init(html: String, url: String?, encoding: String.Encoding, option: UInt) throws {
self.html = html
self.url = url
self.encoding = encoding
guard html.lengthOfBytes(using: encoding) > 0 else {
throw ParseError.Empty
}
guard let charsetName = encoding.IANACharSetName,
let cur = html.cString(using: encoding) else {
throw ParseError.EncodingMismatch
}
let url : String = ""
docPtr = htmlReadDoc(UnsafeRawPointer(cur).assumingMemoryBound(to: xmlChar.self), url, charsetName, CInt(option))
guard let docPtr = docPtr else {
throw ParseError.EncodingMismatch
}
rootNode = libxmlHTMLNode(document: self, docPtr: docPtr)
}
deinit {
xmlFreeDoc(self.docPtr)
}
var title: String? { return at_xpath("//title")?.text }
var head: XMLElement? { return at_xpath("//head") }
var body: XMLElement? { return at_xpath("//body") }
func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject {
return rootNode?.xpath(xpath, namespaces: namespaces) ?? XPathObject.none
}
func xpath(_ xpath: String) -> XPathObject {
return self.xpath(xpath, namespaces: nil)
}
func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? {
return rootNode?.at_xpath(xpath, namespaces: namespaces)
}
func at_xpath(_ xpath: String) -> XMLElement? {
return self.at_xpath(xpath, namespaces: nil)
}
func css(_ selector: String, namespaces: [String:String]?) -> XPathObject {
return rootNode?.css(selector, namespaces: namespaces) ?? XPathObject.none
}
func css(_ selector: String) -> XPathObject {
return self.css(selector, namespaces: nil)
}
func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? {
return rootNode?.at_css(selector, namespaces: namespaces)
}
func at_css(_ selector: String) -> XMLElement? {
return self.at_css(selector, namespaces: nil)
}
}
/*
libxmlXMLDocument
*/
internal final class libxmlXMLDocument: XMLDocument {
fileprivate var docPtr: xmlDocPtr? = nil
fileprivate var rootNode: XMLElement?
fileprivate var xml: String
fileprivate var url: String?
fileprivate var encoding: String.Encoding
var text: String? {
return rootNode?.text
}
var toHTML: String? {
let buf = xmlBufferCreate()
let outputBuf = xmlOutputBufferCreateBuffer(buf, nil)
defer {
xmlOutputBufferClose(outputBuf)
xmlBufferFree(buf)
}
htmlDocContentDumpOutput(outputBuf, docPtr, nil)
let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf)))
return html
}
var toXML: String? {
var buf: UnsafeMutablePointer<xmlChar>? = nil
let size: UnsafeMutablePointer<Int32>? = nil
defer {
xmlFree(buf)
}
xmlDocDumpMemory(docPtr, &buf, size)
let html = String(cString: UnsafePointer<UInt8>(buf!))
return html
}
var innerHTML: String? {
return rootNode?.innerHTML
}
var className: String? {
return nil
}
var tagName: String? {
get {
return nil
}
set {
}
}
var content: String? {
get {
return text
}
set {
rootNode?.content = newValue
}
}
init(xml: String, url: String?, encoding: String.Encoding, option: UInt) throws {
self.xml = xml
self.url = url
self.encoding = encoding
if xml.isEmpty {
throw ParseError.Empty
}
guard let charsetName = encoding.IANACharSetName,
let cur = xml.cString(using: encoding) else {
throw ParseError.EncodingMismatch
}
let url : String = ""
docPtr = xmlReadDoc(UnsafeRawPointer(cur).assumingMemoryBound(to: xmlChar.self), url, charsetName, CInt(option))
rootNode = libxmlHTMLNode(document: self, docPtr: docPtr!)
}
deinit {
xmlFreeDoc(self.docPtr)
}
func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject {
return rootNode?.xpath(xpath, namespaces: namespaces) ?? XPathObject.none
}
func xpath(_ xpath: String) -> XPathObject {
return self.xpath(xpath, namespaces: nil)
}
func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? {
return rootNode?.at_xpath(xpath, namespaces: namespaces)
}
func at_xpath(_ xpath: String) -> XMLElement? {
return self.at_xpath(xpath, namespaces: nil)
}
func css(_ selector: String, namespaces: [String:String]?) -> XPathObject {
return rootNode?.css(selector, namespaces: namespaces) ?? XPathObject.none
}
func css(_ selector: String) -> XPathObject {
return self.css(selector, namespaces: nil)
}
func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? {
return rootNode?.at_css(selector, namespaces: namespaces)
}
func at_css(_ selector: String) -> XMLElement? {
return self.at_css(selector, namespaces: nil)
}
}
+300
View File
@@ -0,0 +1,300 @@
/**@file libxmlHTMLNode.swift
Kanna
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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
import libxmlKanna
/**
libxmlHTMLNode
*/
internal final class libxmlHTMLNode: XMLElement {
var text: String? {
if nodePtr != nil {
return libxmlGetNodeContent(nodePtr!)
}
return nil
}
var toHTML: String? {
let buf = xmlBufferCreate()
htmlNodeDump(buf, docPtr, nodePtr)
let html = String(cString: UnsafePointer<UInt8>((buf?.pointee.content)!))
xmlBufferFree(buf)
return html
}
var toXML: String? {
let buf = xmlBufferCreate()
xmlNodeDump(buf, docPtr, nodePtr, 0, 0)
let html = String(cString: UnsafePointer<UInt8>((buf?.pointee.content)!))
xmlBufferFree(buf)
return html
}
var innerHTML: String? {
if let html = self.toHTML {
let inner = html.replacingOccurrences(of: "</[^>]*>$", with: "", options: .regularExpression, range: nil)
.replacingOccurrences(of: "^<[^>]*>", with: "", options: .regularExpression, range: nil)
return inner
}
return nil
}
var className: String? {
return self["class"]
}
var tagName: String? {
get {
guard let name = nodePtr?.pointee.name else {
return nil
}
return String(cString: name)
}
set {
if let newValue = newValue {
xmlNodeSetName(nodePtr, newValue)
}
}
}
var content: String? {
get {
return text
}
set {
if let newValue = newValue {
let v = escape(newValue)
xmlNodeSetContent(nodePtr, v)
}
}
}
var parent: XMLElement? {
get {
return libxmlHTMLNode(document: doc, docPtr: docPtr!, node: (nodePtr?.pointee.parent)!)
}
set {
if let node = newValue as? libxmlHTMLNode {
node.addChild(self)
}
}
}
var nextSibling: XMLElement? {
let val = xmlNextElementSibling(self.nodePtr)
return self.node(from: val)
}
var previousSibling: XMLElement? {
let val = xmlPreviousElementSibling(self.nodePtr)
return self.node(from: val)
}
fileprivate weak var weakDocument: XMLDocument?
fileprivate var document: XMLDocument?
fileprivate var docPtr: htmlDocPtr? = nil
fileprivate var nodePtr: xmlNodePtr? = nil
fileprivate var isRoot: Bool = false
fileprivate var doc: XMLDocument? {
return weakDocument ?? document
}
subscript(attributeName: String) -> String?
{
get {
var attr = nodePtr?.pointee.properties
while attr != nil {
let mem = attr?.pointee
if let tagName = String(validatingUTF8: UnsafeRawPointer((mem?.name)!).assumingMemoryBound(to: CChar.self)) {
if attributeName == tagName {
if let children = mem?.children {
return libxmlGetNodeContent(children)
} else {
return ""
}
}
}
attr = attr?.pointee.next
}
return nil
}
set(newValue) {
if let newValue = newValue {
xmlSetProp(nodePtr, attributeName, newValue)
} else {
xmlUnsetProp(nodePtr, attributeName)
}
}
}
init(document: XMLDocument?, docPtr: xmlDocPtr) {
self.weakDocument = document
self.docPtr = docPtr
self.nodePtr = xmlDocGetRootElement(docPtr)
self.isRoot = true
}
init(document: XMLDocument?, docPtr: xmlDocPtr, node: xmlNodePtr) {
self.document = document
self.docPtr = docPtr
self.nodePtr = node
}
// MARK: Searchable
func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject {
let ctxt = xmlXPathNewContext(docPtr)
if ctxt == nil {
return XPathObject.none
}
ctxt?.pointee.node = nodePtr
if let nsDictionary = namespaces {
for (ns, name) in nsDictionary {
xmlXPathRegisterNs(ctxt, ns, name)
}
}
let result = xmlXPathEvalExpression(xpath, ctxt)
defer {
xmlXPathFreeObject(result)
}
xmlXPathFreeContext(ctxt)
if result == nil {
return XPathObject.none
}
return XPathObject(document: doc, docPtr: docPtr!, object: result!.pointee)
}
func xpath(_ xpath: String) -> XPathObject {
return self.xpath(xpath, namespaces: nil)
}
func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? {
return self.xpath(xpath, namespaces: namespaces).nodeSetValue.first
}
func at_xpath(_ xpath: String) -> XMLElement? {
return self.at_xpath(xpath, namespaces: nil)
}
func css(_ selector: String, namespaces: [String:String]?) -> XPathObject {
if let xpath = try? CSS.toXPath(selector) {
if isRoot {
return self.xpath(xpath, namespaces: namespaces)
} else {
return self.xpath("." + xpath, namespaces: namespaces)
}
}
return XPathObject.none
}
func css(_ selector: String) -> XPathObject {
return self.css(selector, namespaces: nil)
}
func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? {
return self.css(selector, namespaces: namespaces).nodeSetValue.first
}
func at_css(_ selector: String) -> XMLElement? {
return self.css(selector, namespaces: nil).nodeSetValue.first
}
func addPrevSibling(_ node: XMLElement) {
guard let node = node as? libxmlHTMLNode else {
return
}
xmlAddPrevSibling(nodePtr, node.nodePtr)
}
func addNextSibling(_ node: XMLElement) {
guard let node = node as? libxmlHTMLNode else {
return
}
xmlAddNextSibling(nodePtr, node.nodePtr)
}
func addChild(_ node: XMLElement) {
guard let node = node as? libxmlHTMLNode else {
return
}
xmlUnlinkNode(node.nodePtr)
xmlAddChild(nodePtr, node.nodePtr)
}
func removeChild(_ node: XMLElement) {
guard let node = node as? libxmlHTMLNode else {
return
}
xmlUnlinkNode(node.nodePtr)
xmlFree(node.nodePtr)
}
private func node(from ptr: xmlNodePtr?) -> XMLElement? {
guard let doc = self.doc, let docPtr = self.docPtr, let nodePtr = ptr else {
return nil
}
let element = libxmlHTMLNode(document: doc, docPtr: docPtr, node: nodePtr)
return element
}
}
private func libxmlGetNodeContent(_ nodePtr: xmlNodePtr) -> String? {
let content = xmlNodeGetContent(nodePtr)
defer {
#if swift(>=4.1)
content?.deallocate()
#else
content?.deallocate(capacity: 1)
#endif
}
if let result = String(validatingUTF8: UnsafeRawPointer(content!).assumingMemoryBound(to: CChar.self)) {
return result
}
return nil
}
let entities = [
"&": "&amp;",
"<" : "&lt;",
">" : "&gt;",
]
private func escape(_ str: String) -> String {
var newStr = str
for (unesc, esc) in entities {
newStr = newStr.replacingOccurrences(of: unesc, with: esc, options: .regularExpression, range: nil)
}
return newStr
}
+94
View File
@@ -0,0 +1,94 @@
/**@file libxmlParserOption.swift
Kanna
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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
import libxmlKanna
/*
Libxml2HTMLParserOptions
*/
public struct Libxml2HTMLParserOptions : OptionSet {
public typealias RawValue = UInt
private var value: UInt = 0
init(_ value: UInt) { self.value = value }
private init(_ opt: htmlParserOption) { self.value = UInt(opt.rawValue) }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: Libxml2HTMLParserOptions { return .init(0) }
static func fromMask(raw: UInt) -> Libxml2HTMLParserOptions { return .init(raw) }
public var rawValue: UInt { return self.value }
public static let STRICT = Libxml2HTMLParserOptions(0)
public static let RECOVER = Libxml2HTMLParserOptions(HTML_PARSE_RECOVER)
public static let NODEFDTD = Libxml2HTMLParserOptions(HTML_PARSE_NODEFDTD)
public static let NOERROR = Libxml2HTMLParserOptions(HTML_PARSE_NOERROR)
public static let NOWARNING = Libxml2HTMLParserOptions(HTML_PARSE_NOWARNING)
public static let PEDANTIC = Libxml2HTMLParserOptions(HTML_PARSE_PEDANTIC)
public static let NOBLANKS = Libxml2HTMLParserOptions(HTML_PARSE_NOBLANKS)
public static let NONET = Libxml2HTMLParserOptions(HTML_PARSE_NONET)
public static let NOIMPLIED = Libxml2HTMLParserOptions(HTML_PARSE_NOIMPLIED)
public static let COMPACT = Libxml2HTMLParserOptions(HTML_PARSE_COMPACT)
public static let IGNORE_ENC = Libxml2HTMLParserOptions(HTML_PARSE_IGNORE_ENC)
}
/*
Libxml2XMLParserOptions
*/
public struct Libxml2XMLParserOptions: OptionSet {
public typealias RawValue = UInt
private var value: UInt = 0
init(_ value: UInt) { self.value = value }
private init(_ opt: xmlParserOption) { self.value = UInt(opt.rawValue) }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: Libxml2XMLParserOptions { return .init(0) }
static func fromMask(raw: UInt) -> Libxml2XMLParserOptions { return .init(raw) }
public var rawValue: UInt { return self.value }
public static let STRICT = Libxml2XMLParserOptions(0)
public static let RECOVER = Libxml2XMLParserOptions(XML_PARSE_RECOVER)
public static let NOENT = Libxml2XMLParserOptions(XML_PARSE_NOENT)
public static let DTDLOAD = Libxml2XMLParserOptions(XML_PARSE_DTDLOAD)
public static let DTDATTR = Libxml2XMLParserOptions(XML_PARSE_DTDATTR)
public static let DTDVALID = Libxml2XMLParserOptions(XML_PARSE_DTDVALID)
public static let NOERROR = Libxml2XMLParserOptions(XML_PARSE_NOERROR)
public static let NOWARNING = Libxml2XMLParserOptions(XML_PARSE_NOWARNING)
public static let PEDANTIC = Libxml2XMLParserOptions(XML_PARSE_PEDANTIC)
public static let NOBLANKS = Libxml2XMLParserOptions(XML_PARSE_NOBLANKS)
public static let SAX1 = Libxml2XMLParserOptions(XML_PARSE_SAX1)
public static let XINCLUDE = Libxml2XMLParserOptions(XML_PARSE_XINCLUDE)
public static let NONET = Libxml2XMLParserOptions(XML_PARSE_NONET)
public static let NODICT = Libxml2XMLParserOptions(XML_PARSE_NODICT)
public static let NSCLEAN = Libxml2XMLParserOptions(XML_PARSE_NSCLEAN)
public static let NOCDATA = Libxml2XMLParserOptions(XML_PARSE_NOCDATA)
public static let NOXINCNODE = Libxml2XMLParserOptions(XML_PARSE_NOXINCNODE)
public static let COMPACT = Libxml2XMLParserOptions(XML_PARSE_COMPACT)
public static let OLD10 = Libxml2XMLParserOptions(XML_PARSE_OLD10)
public static let NOBASEFIX = Libxml2XMLParserOptions(XML_PARSE_NOBASEFIX)
public static let HUGE = Libxml2XMLParserOptions(XML_PARSE_HUGE)
public static let OLDSAX = Libxml2XMLParserOptions(XML_PARSE_OLDSAX)
public static let IGNORE_ENC = Libxml2XMLParserOptions(XML_PARSE_IGNORE_ENC)
public static let BIG_LINES = Libxml2XMLParserOptions(XML_PARSE_BIG_LINES)
}
+24
View File
@@ -0,0 +1,24 @@
PODS:
- Alamofire (4.8.2)
- Kanna (5.0.0)
- SwiftSoup (1.7.4)
DEPENDENCIES:
- Alamofire
- Kanna
- SwiftSoup
SPEC REPOS:
https://github.com/cocoapods/specs.git:
- Alamofire
- Kanna
- SwiftSoup
SPEC CHECKSUMS:
Alamofire: ae5c501addb7afdbb13687d7f2f722c78734c2d3
Kanna: a32875df62975f8f4b871e933b4ea1a5c3b8be0f
SwiftSoup: 92f5b348c131aed8af04f4326db1579ab19fa08c
PODFILE CHECKSUM: 30581c398549a5f1d7f1c358553c9bcad81e21a6
COCOAPODS: 1.6.1
+1637
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "3383968E74B5371B20BB519B170DC7FD"
BuildableName = "Alamofire.framework"
BlueprintName = "Alamofire"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1E0B9DFE11A3B2711C371DDBBA9BDAA6"
BuildableName = "Kanna.framework"
BlueprintName = "Kanna"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B07002B7F076BD4E872BCBC38DFC2EBE"
BuildableName = "Pods_AvH_Plan.framework"
BlueprintName = "Pods-AvH Plan"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B07002B7F076BD4E872BCBC38DFC2EBE"
BuildableName = "Pods_AvH_Plan.framework"
BlueprintName = "Pods-AvH Plan"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B8C6AD5E702222047282C46D5A957F5F"
BuildableName = "Pods_AvH_PlanTests.framework"
BlueprintName = "Pods-AvH PlanTests"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B8C6AD5E702222047282C46D5A957F5F"
BuildableName = "Pods_AvH_PlanTests.framework"
BlueprintName = "Pods-AvH PlanTests"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "4F58E6A326CFE0774A009139A52A7BFF"
BuildableName = "Pods_AvH_PlanUITests.framework"
BlueprintName = "Pods-AvH PlanUITests"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "4F58E6A326CFE0774A009139A52A7BFF"
BuildableName = "Pods_AvH_PlanUITests.framework"
BlueprintName = "Pods-AvH PlanUITests"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForAnalyzing = "YES"
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "41AEB266717A3C96C2D1E03D16B79263"
BuildableName = "SwiftSoup.framework"
BlueprintName = "SwiftSoup"
ReferencedContainer = "container:Pods.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
buildConfiguration = "Debug"
allowLocationSimulation = "YES">
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES"
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>Alamofire.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
<key>orderHint</key>
<integer>0</integer>
</dict>
<key>Kanna.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
<key>orderHint</key>
<integer>1</integer>
</dict>
<key>Pods-AvH Plan.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
<key>orderHint</key>
<integer>2</integer>
</dict>
<key>Pods-AvH PlanTests.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
<key>orderHint</key>
<integer>3</integer>
</dict>
<key>Pods-AvH PlanUITests.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
<key>orderHint</key>
<integer>4</integer>
</dict>
<key>SwiftSoup.xcscheme</key>
<dict>
<key>isShown</key>
<false/>
<key>orderHint</key>
<integer>5</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict/>
</dict>
</plist>
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Nabil Chatbi
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.
+592
View File
@@ -0,0 +1,592 @@
<p align="center" >
<img src="https://raw.githubusercontent.com/scinfu/SwiftSoup/master/swifsoup.png" alt="SwiftSoup" title="SwiftSoup">
</p>
![Platform OS X | iOS | tvOS | watchOS | Linux](https://img.shields.io/badge/platform-Linux%20%7C%20OS%20X%20%7C%20iOS%20%7C%20tvOS%20%7C%20watchOS-orange.svg)
[![SPM compatible](https://img.shields.io/badge/SPM-compatible-4BC51D.svg?style=flat)](https://github.com/apple/swift-package-manager)
![🐧 linux: ready](https://img.shields.io/badge/%F0%9F%90%A7%20linux-ready-red.svg)
![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)
[![Build Status](https://travis-ci.org/scinfu/SwiftSoup.svg?branch=master)](https://travis-ci.org/scinfu/SwiftSoup)
[![Version](https://img.shields.io/cocoapods/v/SwiftSoup.svg?style=flat)](http://cocoapods.org/pods/SwiftSoup)
[![License](https://img.shields.io/cocoapods/l/SwiftSoup.svg?style=flat)](http://cocoapods.org/pods/SwiftSoup)
[![Twitter](https://img.shields.io/badge/twitter-@scinfu-blue.svg?style=flat)](http://twitter.com/scinfu)
`SwiftSoup` is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jQuery-like methods.
`SwiftSoup` implements the WHATWG HTML5 specification, and parses HTML to the same DOM as modern browsers do.
* Scrape and parse HTML from a URL, file, or string
* Find and extract data, using DOM traversal or CSS selectors
* Manipulate the HTML elements, attributes, and text
* Clean user-submitted content against a safe white-list, to prevent XSS attacks
* Output tidy HTML
`SwiftSoup` is designed to deal with all varieties of HTML found in the wild; from pristine and validating, to invalid tag-soup; `SwiftSoup` will create a sensible parse tree.
## Installation
### Cocoapods
SwiftSoup is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:
```ruby
pod 'SwiftSoup'
```
### Carthage
SwiftSoup is also available through [Carthage](https://github.com/Carthage/Carthage). To install
it, simply add the following line to your Cartfile:
```ruby
github "scinfu/SwiftSoup"
```
### Swift Package Manager
SwiftSoup is also available through [Swift Package Manager](https://github.com/apple/swift-package-manager).
To install it, simply add the dependency to your Package.Swift file:
```swift
...
dependencies: [
.package(url: "https://github.com/scinfu/SwiftSoup.git", from: "1.5.10"),
],
targets: [
.target( name: "YourTarget", dependencies: ["SwiftSoup"]),
]
...
```
## Try
### Try out the simple online CSS selectors site:
[SwiftSoup Test Site](https://swiftsoup.herokuapp.com/)
### Try out the example project opening Terminal and type:
```shell
pod try SwiftSoup
```
<p align="center" >
<img src="https://raw.githubusercontent.com/scinfu/SwiftSoup/master/Example/img1.png" alt="SwiftSoup" title="SwiftSoup">
<img src="https://raw.githubusercontent.com/scinfu/SwiftSoup/master/Example/img2.png" alt="SwiftSoup" title="SwiftSoup">
</p>
# To parse an HTML document:
```swift
do {
let html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p></body></html>"
let doc: Document = try SwiftSoup.parse(html)
return try doc.text()
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
* Unclosed tags (e.g. `<p>Lorem <p>Ipsum` parses to `<p>Lorem</p> <p>Ipsum</p>`)
* Implicit tags (e.g. a naked `<td>Table data</td>` is wrapped into a `<table><tr><td>...`)
* Reliably creating the document structure (`html` containing a `head` and `body`, and only appropriate elements within the head)
### The object model of a document
* Documents consist of Elements and TextNodes
* The inheritance chain is: `Document` extends `Element` extends `Node.TextNode` extends `Node`.
* An Element contains a list of children Nodes, and has one parent Element. They also have provide a filtered list of child Elements only.
# Extract attributes, text, and HTML from elements
### Problem
After parsing a document, and finding some elements, you'll want to get at the data inside those elements.
### Solution
- To get the value of an attribute, use the `Node.attr(_ String key)` method
- For the text on an element (and its combined children), use `Element.text()`
- For HTML, use `Element.html()`, or `Node.outerHtml()` as appropriate
```swift
do {
let html: String = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
let doc: Document = try SwiftSoup.parse(html)
let link: Element = try doc.select("a").first()!
let text: String = try doc.body()!.text(); // "An example link"
let linkHref: String = try link.attr("href"); // "http://example.com/"
let linkText: String = try link.text(); // "example""
let linkOuterH: String = try link.outerHtml(); // "<a href="http://example.com"><b>example</b></a>"
let linkInnerH: String = try link.html(); // "<b>example</b>"
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
### Description
The methods above are the core of the element data access methods. There are additional others:
- `Element.id()`
- `Element.tagName()`
- `Element.className()` and `Element.hasClass(_ String className)`
All of these accessor methods have corresponding setter methods to change the data.
# Parse a document from a String
### Problem
You have HTML in a Swift String, and you want to parse that HTML to get at its contents, or to make sure it's well formed, or to modify it. The String may have come from user input, a file, or from the web.
### Solution
Use the static `SwiftSoup.parse(_ html: String)` method, or `SwiftSoup.parse(_ html: String, _ baseUri: String)`.
```swift
do {
let html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p></body></html>"
let doc: Document = try SwiftSoup.parse(html)
return try doc.text()
} catch Exception.Error(let type, let message) {
print("")
} catch {
print("")
}
```
### Description
The `parse(_ html: String, _ baseUri: String)` method parses the input HTML into a new `Document`. The base URI argument is used to resolve relative URLs into absolute URLs, and should be set to the URL where the document was fetched from. If that's not applicable, or if you know the HTML has a base element, you can use the `parse(_ html: String)` method.
As long as you pass in a non-null string, you're guaranteed to have a successful, sensible parse, with a Document containing (at least) a `head` and a `body` element.
Once you have a `Document`, you can get at the data using the appropriate methods in `Document` and its supers `Element` and `Node`.
# Parsing a body fragment
### Problem
You have a fragment of body HTML (e.g. `div` containing a couple of p tags; as opposed to a full HTML document) that you want to parse. Perhaps it was provided by a user submitting a comment, or editing the body of a page in a CMS.
### Solution
Use the `SwiftSoup.parseBodyFragment(_ html: String)` method.
```swift
do {
let html: String = "<div><p>Lorem ipsum.</p>"
let doc: Document = try SwiftSoup.parseBodyFragment(html)
let body: Element? = doc.body()
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
### Description
The `parseBodyFragment` method creates an empty shell document, and inserts the parsed HTML into the `body` element. If you used the normal `SwiftSoup(_ html: String)` method, you would generally get the same result, but explicitly treating the input as a body fragment ensures that any bozo HTML provided by the user is parsed into the `body` element.
The `Document.body()` method retrieves the element children of the document's `body` element; it is equivalent to `doc.getElementsByTag("body")`.
### Stay safe
If you are going to accept HTML input from a user, you need to be careful to avoid cross-site scripting attacks. See the documentation for the `Whitelist` based cleaner, and clean the input with `clean(String bodyHtml, Whitelist whitelist)`.
# Sanitize untrusted HTML (to prevent XSS)
### Problem
You want to allow untrusted users to supply HTML for output on your website (e.g. as comment submission). You need to clean this HTML to avoid [cross-site scripting](https://en.wikipedia.org/wiki/Cross-site_scripting) (XSS) attacks.
### Solution
Use the SwiftSoup HTML `Cleaner` with a configuration specified by a `Whitelist`.
```swift
do {
let unsafe: String = "<p><a href='http://example.com/' onclick='stealCookies()'>Link</a></p>"
let safe: String = try SwiftSoup.clean(unsafe, Whitelist.basic())!
// now: <p><a href="http://example.com/" rel="nofollow">Link</a></p>
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
### Discussion
A cross-site scripting attack against your site can really ruin your day, not to mention your users'. Many sites avoid XSS attacks by not allowing HTML in user submitted content: they enforce plain text only, or use an alternative markup syntax like wiki-text or Markdown. These are seldom optimal solutions for the user, as they lower expressiveness, and force the user to learn a new syntax.
A better solution may be to use a rich text WYSIWYG editor (like [CKEditor](http://ckeditor.com) or [TinyMCE](https://www.tinymce.com)). These output HTML, and allow the user to work visually. However, their validation is done on the client side: you need to apply a server-side validation to clean up the input and ensure the HTML is safe to place on your site. Otherwise, an attacker can avoid the client-side Javascript validation and inject unsafe HMTL directly into your site
The SwiftSoup whitelist sanitizer works by parsing the input HTML (in a safe, sand-boxed environment), and then iterating through the parse tree and only allowing known-safe tags and attributes (and values) through into the cleaned output.
It does not use regular expressions, which are inappropriate for this task.
SwiftSoup provides a range of `Whitelist` configurations to suit most requirements; they can be modified if necessary, but take care.
The cleaner is useful not only for avoiding XSS, but also in limiting the range of elements the user can provide: you may be OK with textual `a`, `strong` elements, but not structural `div` or `table` elements.
### See also
- See the [XSS cheat sheet](http://ha.ckers.org/xss.html) and filter evasion guide, as an example of how regular-expression filters don't work, and why a safe whitelist parser-based sanitizer is the correct approach.
- See the `Cleaner` reference if you want to get a `Document` instead of a String return
- See the `Whitelist` reference for the different canned options, and to create a custom whitelist
- The [nofollow](https://en.wikipedia.org/wiki/Nofollow) link attribute
# Set attribute values
### Problem
You have a parsed document that you would like to update attribute values on, before saving it out to disk, or sending it on as a HTTP response.
### Solution
Use the attribute setter methods `Element.attr(_ key: String, _ value: String)`, and `Elements.attr(_ key: String, _ value: String)`.
If you need to modify the class attribute of an element, use the `Element.addClass(_ className: String)` and `Element.removeClass(_ className: String)` methods.
The `Elements` collection has bulk attribute and class methods. For example, to add a `rel="nofollow"` attribute to every `a` element inside a div:
```swift
do {
try doc.select("div.comments a").attr("rel", "nofollow")
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
### Description
Like the other methods in `Element`, the attr methods return the current `Element` (or `Elements` when working on a collection from a select). This allows convenient method chaining:
```swift
do {
try doc.select("div.masthead").attr("title", "swiftsoup").addClass("round-box");
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
# Set the HTML of an element
### Problem
You need to modify the HTML of an element.
### Solution
Use the HTML setter methods in `Element`:
```swift
do {
let doc: Document = try SwiftSoup.parse("<div>One</div><span>One</span>")
let div: Element = try doc.select("div").first()! // <div></div>
try div.html("<p>lorem ipsum</p>") // <div><p>lorem ipsum</p></div>
try div.prepend("<p>First</p>")
try div.append("<p>Last</p>")
print(div)
// now div is: <div><p>First</p><p>lorem ipsum</p><p>Last</p></div>
let span: Element = try doc.select("span").first()! // <span>One</span>
try span.wrap("<li><a href='http://example.com/'></a></li>")
print(doc)
// now: <li><a href="http://example.com/"><span>One</span></a></li>
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
### Discussion
- `Element.html(_ html: String)` clears any existing inner HTML in an element, and replaces it with parsed HTML.
- `Element.prepend(_ first: String)` and `Element.append(_ last: String)` add HTML to the start or end of an element's inner HTML, respectively
- `Element.wrap(_ around: String)` wraps HTML around the outer HTML of an element.
### See also
You can also use the `Element.prependElement(_ tag: String)` and `Element.appendElement(_ tag: String)` methods to create new elements and insert them into the document flow as a child element.
# Setting the text content of elements
### Problem
You need to modify the text content of an HTML document.
# Solution
Use the text setter methods of `Element`:
```swift
do {
let doc: Document = try SwiftSoup.parse("")
let div: Element = try doc.select("div").first()! // <div></div>
try div.text("five > four") // <div>five &gt; four</div>
try div.prepend("First ")
try div.append(" Last")
// now: <div>First five &gt; four Last</div>
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
### Discussion
The text setter methods mirror the [[HTML setter|Set the HTML of an element]] methods:
- `Element.text(_ text: String)` clears any existing inner HTML in an element, and replaces it with the supplied text.
- `Element.prepend(_ first: String)` and `Element.append(_ last: String)` add text nodes to the start or end of an element's inner HTML, respectively
The text should be supplied unencoded: characters like `<`, `>` etc will be treated as literals, not HTML.
# Use DOM methods to navigate a document
### Problem
You have a HTML document that you want to extract data from. You know generally the structure of the HTML document.
### Solution
Use the DOM-like methods available after parsing HTML into a `Document`.
```swift
do {
let html: String = "<a id=1 href='?foo=bar&mid&lt=true'>One</a> <a id=2 href='?foo=bar&lt;qux&lg=1'>Two</a>"
let els: Elements = try SwiftSoup.parse(html).select("a")
for link: Element in els.array() {
let linkHref: String = try link.attr("href")
let linkText: String = try link.text()
}
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
### Description
Elements provide a range of DOM-like methods to find elements, and extract and manipulate their data. The DOM getters are contextual: called on a parent Document they find matching elements under the document; called on a child element they find elements under that child. In this way you can window in on the data you want.
### Finding elements
* `getElementById(_ id: String)`
* `getElementsByTag(_ tag:String)`
* `getElementsByClass(_ className: String)`
* `getElementsByAttribute(_ key: String)` (and related methods)
* Element siblings: `siblingElements()`, `firstElementSibling()`, `lastElementSibling()`, `nextElementSibling()`, `previousElementSibling()`
* Graph: `parent()`, `children()`, `child(_ index: Int)`
# Element data
* `attr(_ key: Strin)` to get and `attr(_ key: String, _ value: String)` to set attributes
* `attributes()` to get all attributes
* `id()`, `className()` and `classNames()`
* `text()` to get and `text(_ value: String)` to set the text content
* `html()` to get and `html(_ value: String)` to set the inner HTML content
* `outerHtml()` to get the outer HTML value
* `data()` to get data content (e.g. of script and style tags)
* `tag()` and `tagName()`
### Manipulating HTML and text
* `append(_ html: String)`, `prepend(html: String)`
* `appendText(text: String)`, `prependText(text: String)`
* `appendElement(tagName: String)`, `prependElement(tagName: String)`
* `html(_ value: String)`
# Use selector syntax to find elements
### Problem
You want to find or manipulate elements using a CSS or jQuery-like selector syntax.
### Solution
Use the `Element.select(_ selector: String)` and `Elements.select(_ selector: String)` methods:
```swift
do {
let doc: Document = try SwiftSoup.parse("...")
let links: Elements = try doc.select("a[href]") // a with href
let pngs: Elements = try doc.select("img[src$=.png]")
// img with src ending .png
let masthead: Element? = try doc.select("div.masthead").first()
// div with class=masthead
let resultLinks: Elements? = try doc.select("h3.r > a") // direct a after h3
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
```
### Description
SwiftSoup elements support a [CSS](https://www.w3.org/TR/2009/PR-css3-selectors-20091215/) (or [jQuery](http://jquery.com)) like selector syntax to find matching elements, that allows very powerful and robust queries.
The `select` method is available in a `Document`, `Element`, or in `Elements`. It is contextual, so you can filter by selecting from a specific element, or by chaining select calls.
Select returns a list of `Elements` (as `Elements`), which provides a range of methods to extract and manipulate the results.
### Selector overview
* `tagname`: find elements by tag, e.g. `a`
* `ns|tag`: find elements by tag in a namespace, e.g. `fb|name` finds `<fb:name>` elements
* `#id`: find elements by ID, e.g. `#logo`
* `.class`: find elements by class name, e.g. `.masthead`
* `[attribute]`: elements with attribute, e.g. `[href]`
* `[^attr]`: elements with an attribute name prefix, e.g. `[^data-]` finds elements with HTML5 dataset attributes
* `[attr=value]`: elements with attribute value, e.g. `[width=500]` (also quotable, like `[data-name='launch sequence']`)
* `[attr^=value]`, `[attr$=value]`, `[attr*=value]`: elements with attributes that start with, end with, or contain the value, e.g. `[href*=/path/]`
* `[attr~=regex]`: elements with attribute values that match the regular expression; e.g. `img[src~=(?i)\.(png|jpe?g)]`
* `*`: all elements, e.g. `*`
### Selector combinations
* `el#id`: elements with ID, e.g. `div#logo`
* `el.class`: elements with class, e.g. `div.masthead`
* `el[attr]`: elements with attribute, e.g. `a[href]`
* Any combination, e.g. `a[href].highlight`
* Ancestor `child`: child elements that descend from ancestor, e.g. `.body p` finds `p` elements anywhere under a block with class "body"
* `parent > child`: child elements that descend directly from parent, e.g. `div.content > p` finds p elements; and `body > *` finds the direct children of the body tag
* `siblingA + siblingB`: finds sibling B element immediately preceded by sibling A, e.g. `div.head + div`
* `siblingA ~ siblingX`: finds sibling X element preceded by sibling A, e.g. `h1 ~ p`
* `el`, `el`, `el`: group multiple selectors, find unique elements that match any of the selectors; e.g. `div.masthead`, `div.logo`
### Pseudo selectors
* `:lt(n)`: find elements whose sibling index (i.e. its position in the DOM tree relative to its parent) is less than n; e.g. `td:lt(3)`
* `:gt(n)`: find elements whose sibling index is greater than n; e.g. `div p:gt(2)`
* `:eq(n)`: find elements whose sibling index is equal to n; e.g. `form input:eq(1)`
* `:has(seletor)`: find elements that contain elements matching the selector; e.g. `div:has(p)`
* `:not(selector)`: find elements that do not match the selector; e.g. `div:not(.logo)`
* `:contains(text)`: find elements that contain the given text. The search is case-insensitive; e.g. `p:contains(swiftsoup)`
* `:containsOwn(text)`: find elements that directly contain the given text
* `:matches(regex)`: find elements whose text matches the specified regular expression; e.g. `div:matches((?i)login)`
* `:matchesOwn(regex)`: find elements whose own text matches the specified regular expression
* Note that the above indexed pseudo-selectors are 0-based, that is, the first element is at index 0, the second at 1, etc
# Examples
## To parse an HTML document from String:
```swift
let html = "<html><head><title>First parse</title></head><body><p>Parsed HTML into a doc.</p></body></html>"
guard let doc: Document = try? SwiftSoup.parse(html) else { return }
```
## Get all text nodes:
```swift
guard let elements = try? doc.getAllElements() else { return html }
for element in elements {
for textNode in element.textNodes() {
[...]
}
}
```
## Set CSS using SwiftSoup:
```swift
try doc.head()?.append("<style>html {font-size: 2em}</style>")
```
## Get HTML value
```swift
let html = "<div class=\"container-fluid\">"
+ "<div class=\"panel panel-default \">"
+ "<div class=\"panel-body\">"
+ "<form id=\"coupon_checkout\" action=\"http://uat.all.com.my/checkout/couponcode\" method=\"post\">"
+ "<input type=\"hidden\" name=\"transaction_id\" value=\"4245\">"
+ "<input type=\"hidden\" name=\"lang\" value=\"EN\">"
+ "<input type=\"hidden\" name=\"devicetype\" value=\"\">"
+ "<div class=\"input-group\">"
+ "<input type=\"text\" class=\"form-control\" id=\"coupon_code\" name=\"coupon\" placeholder=\"Coupon Code\">"
+ "<span class=\"input-group-btn\">"
+ "<button class=\"btn btn-primary\" type=\"submit\">Enter Code</button>"
+ "</span>"
+ "</div>"
+ "</form>"
+ "</div>"
+ "</div>"
guard let doc: Document = try? SwiftSoup.parse(html) else { return } // parse html
let elements = try doc.select("[name=transaction_id]") // query
let transaction_id = try elements.get(0) // select first element
let value = try transaction_id.val() // get value
print(value) // 4245
```
## How to remove all the html from a string
```swift
guard let doc: Document = try? SwiftSoup.parse(html) else { return } // parse html
guard let txt = try? doc.text() else { return }
print(txt)
```
## How to get and update XML values
```swift
let xml = "<?xml version='1' encoding='UTF-8' something='else'?><val>One</val>"
guard let doc = try? SwiftSoup.parse(xml, "", Parser.xmlParser()) else { return }
guard let element = try? doc.getElementsByTag("val").first() // Find first element
element.text("NewValue") // Edit Value
let valueString = element.text() // "NewValue"
```
## How to get all `<img src>`
```swift
do {
let doc: Document = try SwiftSoup.parse(html)
let srcs: Elements = try doc.select("img[src]")
let srcsStringArray: [String?] = srcs.array().map { try? $0.attr("src").description }
// do something with srcsStringArray
} catch Exception.Error(_, let message) {
print(message)
} catch {
print("error")
}
```
## Get all `href` of `<a>`
```swift
let html = "<a id=1 href='?foo=bar&mid&lt=true'>One</a> <a id=2 href='?foo=bar&lt;qux&lg=1'>Two</a>"
guard let els: Elements = try? SwiftSoup.parse(html).select("a") else { return }
for element: Element in els.array() {
print(try? element.attr("href"))
}
```
Output:
```
"?foo=bar&mid&lt=true"
"?foo=bar<qux&lg=1"
```
## Escape and Enescape
```swift
let text = "Hello &<> Å å π 新 there ¾ © »"
print(Entities.escape(text))
print(Entities.unescape(text))
print(Entities.escape(text, OutputSettings().encoder(String.Encoding.ascii).escapeMode(Entities.EscapeMode.base)))
print(Entities.escape(text, OutputSettings().charset(String.Encoding.ascii).escapeMode(Entities.EscapeMode.extended)))
print(Entities.escape(text, OutputSettings().charset(String.Encoding.ascii).escapeMode(Entities.EscapeMode.xhtml)))
print(Entities.escape(text, OutputSettings().charset(String.Encoding.utf8).escapeMode(Entities.EscapeMode.extended)))
print(Entities.escape(text, OutputSettings().charset(String.Encoding.utf8).escapeMode(Entities.EscapeMode.xhtml)))
```
Output:
```
"Hello &amp;&lt;&gt; Å å π 新 there ¾ © »"
"Hello &<> Å å π 新 there ¾ © »"
"Hello &amp;&lt;&gt; &Aring; &aring; &#x3c0; &#x65b0; there &frac34; &copy; &raquo;"
"Hello &amp;&lt;&gt; &angst; &aring; &pi; &#x65b0; there &frac34; &copy; &raquo;"
"Hello &amp;&lt;&gt; &#xc5; &#xe5; &#x3c0; &#x65b0; there &#xbe; &#xa9; &#xbb;"
"Hello &amp;&lt;&gt; Å å π 新 there ¾ © »"
"Hello &amp;&lt;&gt; Å å π 新 there ¾ © »"
```
## Author
Nabil Chatbi, scinfu@gmail.com
## Note
SwiftSoup was ported to Swift from Java [Jsoup](https://jsoup.org/) library.
## License
SwiftSoup is available under the MIT license. See the LICENSE file for more info.
+21
View File
@@ -0,0 +1,21 @@
//
// ArrayExt.swift
// SwifSoup
//
// Created by Nabil Chatbi on 05/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
extension Array where Element : Equatable {
func lastIndexOf(_ e: Element) -> Int {
for pos in (0..<self.count).reversed() {
let next = self[pos]
if (next == e) {
return pos
}
}
return -1
}
}
+148
View File
@@ -0,0 +1,148 @@
//
// Attribute.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class Attribute {
/// The element type of a dictionary: a tuple containing an individual
/// key-value pair.
static let booleanAttributes: [String] = [
"allowfullscreen", "async", "autofocus", "checked", "compact", "declare", "default", "defer", "disabled",
"formnovalidate", "hidden", "inert", "ismap", "itemscope", "multiple", "muted", "nohref", "noresize",
"noshade", "novalidate", "nowrap", "open", "readonly", "required", "reversed", "seamless", "selected",
"sortable", "truespeed", "typemustmatch"
]
var key: String
var value: String
public init(key: String, value: String) throws {
try Validate.notEmpty(string: key)
self.key = key.trim()
self.value = value
}
/**
Get the attribute key.
@return the attribute key
*/
open func getKey() -> String {
return key
}
/**
Set the attribute key; case is preserved.
@param key the new key; must not be null
*/
open func setKey(key: String) throws {
try Validate.notEmpty(string: key)
self.key = key.trim()
}
/**
Get the attribute value.
@return the attribute value
*/
open func getValue() -> String {
return value
}
/**
Set the attribute value.
@param value the new attribute value; must not be null
*/
@discardableResult
open func setValue(value: String) -> String {
let old = self.value
self.value = value
return old
}
/**
Get the HTML representation of this attribute; e.g. {@code href="index.html"}.
@return HTML
*/
public func html() -> String {
let accum = StringBuilder()
html(accum: accum, out: (Document("")).outputSettings())
return accum.toString()
}
public func html(accum: StringBuilder, out: OutputSettings ) {
accum.append(key)
if (!shouldCollapseAttribute(out: out)) {
accum.append("=\"")
Entities.escape(accum, value, out, true, false, false)
accum.append("\"")
}
}
/**
Get the string representation of this attribute, implemented as {@link #html()}.
@return string
*/
open func toString() -> String {
return html()
}
/**
* Create a new Attribute from an unencoded key and a HTML attribute encoded value.
* @param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars.
* @param encodedValue HTML attribute encoded value
* @return attribute
*/
public static func createFromEncoded(unencodedKey: String, encodedValue: String) throws ->Attribute {
let value = try Entities.unescape(string: encodedValue, strict: true)
return try Attribute(key: unencodedKey, value: value)
}
public func isDataAttribute() -> Bool {
return key.startsWith(Attributes.dataPrefix) && key.count > Attributes.dataPrefix.count
}
/**
* Collapsible if it's a boolean attribute and value is empty or same as name
*
* @param out Outputsettings
* @return Returns whether collapsible or not
*/
public final func shouldCollapseAttribute(out: OutputSettings) -> Bool {
return ("" == value || value.equalsIgnoreCase(string: key))
&& out.syntax() == OutputSettings.Syntax.html
&& isBooleanAttribute()
}
public func isBooleanAttribute() -> Bool {
return Attribute.booleanAttributes.contains(key)
}
public func hashCode() -> Int {
var result = key.hashValue
result = 31 * result + value.hashValue
return result
}
public func clone() -> Attribute {
do {
return try Attribute(key: key, value: value)
} catch Exception.Error( _, let msg) {
print(msg)
} catch {
}
return try! Attribute(key: "", value: "")
}
}
extension Attribute: Equatable {
static public func == (lhs: Attribute, rhs: Attribute) -> Bool {
return lhs.value == rhs.value && lhs.key == rhs.key
}
}
+264
View File
@@ -0,0 +1,264 @@
//
// Attributes.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* The attributes of an Element.
* <p>
* Attributes are treated as a map: there can be only one value associated with an attribute key/name.
* </p>
* <p>
* Attribute name and value comparisons are <b>case sensitive</b>. By default for HTML, attribute names are
* normalized to lower-case on parsing. That means you should use lower-case strings when referring to attributes by
* name.
* </p>
*
*
*/
open class Attributes: NSCopying {
public static var dataPrefix: String = "data-"
var attributes: OrderedDictionary<String, Attribute> = OrderedDictionary<String, Attribute>()
// linked hash map to preserve insertion order.
// null be default as so many elements have no attributes -- saves a good chunk of memory
public init() {}
/**
Get an attribute value by key.
@param key the (case-sensitive) attribute key
@return the attribute value if set; or empty string if not set.
@see #hasKey(String)
*/
open func get(key: String) -> String {
let attr: Attribute? = attributes.get(key: key)
return attr != nil ? attr!.getValue() : ""
}
/**
* Get an attribute's value by case-insensitive key
* @param key the attribute name
* @return the first matching attribute value if set; or empty string if not set.
*/
open func getIgnoreCase(key: String )throws -> String {
try Validate.notEmpty(string: key)
for attrKey in (attributes.keySet()) {
if attrKey.equalsIgnoreCase(string: key) {
return attributes.get(key: attrKey)!.getValue()
}
}
return ""
}
/**
Set a new attribute, or replace an existing one by key.
@param key attribute key
@param value attribute value
*/
open func put(_ key: String, _ value: String) throws {
let attr = try Attribute(key: key, value: value)
put(attribute: attr)
}
/**
Set a new boolean attribute, remove attribute if value is false.
@param key attribute key
@param value attribute value
*/
open func put(_ key: String, _ value: Bool) throws {
if (value) {
try put(attribute: BooleanAttribute(key: key))
} else {
try remove(key: key)
}
}
/**
Set a new attribute, or replace an existing one by key.
@param attribute attribute
*/
open func put(attribute: Attribute) {
attributes.put(value: attribute, forKey: attribute.getKey())
}
/**
Remove an attribute by key. <b>Case sensitive.</b>
@param key attribute key to remove
*/
open func remove(key: String)throws {
try Validate.notEmpty(string: key)
attributes.remove(key: key)
}
/**
Remove an attribute by key. <b>Case insensitive.</b>
@param key attribute key to remove
*/
open func removeIgnoreCase(key: String ) throws {
try Validate.notEmpty(string: key)
for attrKey in attributes.keySet() {
if (attrKey.equalsIgnoreCase(string: key)) {
attributes.remove(key: attrKey)
}
}
}
/**
Tests if these attributes contain an attribute with this key.
@param key case-sensitive key to check for
@return true if key exists, false otherwise
*/
open func hasKey(key: String) -> Bool {
return attributes.containsKey(key: key)
}
/**
Tests if these attributes contain an attribute with this key.
@param key key to check for
@return true if key exists, false otherwise
*/
open func hasKeyIgnoreCase(key: String) -> Bool {
for attrKey in attributes.keySet() {
if (attrKey.equalsIgnoreCase(string: key)) {
return true
}
}
return false
}
/**
Get the number of attributes in this set.
@return size
*/
open func size() -> Int {
return attributes.count//TODO: check retyrn right size
}
/**
Add all the attributes from the incoming set to this set.
@param incoming attributes to add to these attributes.
*/
open func addAll(incoming: Attributes?) {
guard let incoming = incoming else {
return
}
if (incoming.size() == 0) {
return
}
attributes.putAll(all: incoming.attributes)
}
// open func iterator() -> IndexingIterator<Array<Attribute>> {
// if (attributes.isEmpty) {
// let args: [Attribute] = []
// return args.makeIterator()
// }
// return attributes.orderedValues.makeIterator()
// }
/**
Get the attributes as a List, for iteration. Do not modify the keys of the attributes via this view, as changes
to keys will not be recognised in the containing set.
@return an view of the attributes as a List.
*/
open func asList() -> Array<Attribute> {
var list: Array<Attribute> = Array(/*attributes.size()*/)
for entry in attributes.orderedValues {
list.append(entry)
}
return list
}
/**
* Retrieves a filtered view of attributes that are HTML5 custom data attributes; that is, attributes with keys
* starting with {@code data-}.
* @return map of custom data attributes.
*/
//Map<String, String>
open func dataset() -> Dictionary<String, String> {
var dataset = Dictionary<String, String>()
for attribute in attributes {
let attr = attribute.1
if(attr.isDataAttribute()) {
let key = attr.getKey().substring(Attributes.dataPrefix.count)
dataset[key] = attribute.1.getValue()
}
}
return dataset
}
/**
Get the HTML representation of these attributes.
@return HTML
@throws SerializationException if the HTML representation of the attributes cannot be constructed.
*/
open func html()throws -> String {
let accum = StringBuilder()
try html(accum: accum, out: Document("").outputSettings()) // output settings a bit funky, but this html() seldom used
return accum.toString()
}
public func html(accum: StringBuilder, out: OutputSettings ) throws {
for attribute in attributes.orderedValues {
accum.append(" ")
attribute.html(accum: accum, out: out)
}
}
open func toString()throws -> String {
return try html()
}
/**
* Checks if these attributes are equal to another set of attributes, by comparing the two sets
* @param o attributes to compare with
* @return if both sets of attributes have the same content
*/
open func equals(o: AnyObject?) -> Bool {
if(o == nil) {return false}
if (self === o.self) {return true}
guard let that: Attributes = o as? Attributes else {return false}
return (attributes == that.attributes)
}
/**
* Calculates the hashcode of these attributes, by iterating all attributes and summing their hashcodes.
* @return calculated hashcode
*/
open func hashCode() -> Int {
return attributes.hashCode()
}
public func copy(with zone: NSZone? = nil) -> Any {
let clone = Attributes()
clone.attributes = attributes.clone()
return clone
}
open func clone() -> Attributes {
return self.copy() as! Attributes
}
fileprivate static func dataKey(key: String) -> String {
return dataPrefix + key
}
}
extension Attributes: Sequence {
public func makeIterator() -> AnyIterator<Attribute> {
var list = attributes.orderedValues
return AnyIterator {
return list.count > 0 ? list.removeFirst() : nil
}
}
}
+26
View File
@@ -0,0 +1,26 @@
//
// BooleanAttribute.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* A boolean attribute that is written out without any value.
*/
open class BooleanAttribute: Attribute {
/**
* Create a new boolean attribute from unencoded (raw) key.
* @param key attribute key
*/
init(key: String) throws {
try super.init(key: key, value: "")
}
override public func isBooleanAttribute() -> Bool {
return true
}
}
+81
View File
@@ -0,0 +1,81 @@
//
// CharacterExt.swift
// SwifSoup
//
// Created by Nabil Chatbi on 08/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
extension Character {
public static let space: Character = " "
public static let BackslashT: Character = "\t"
public static let BackslashN: Character = "\n"
public static let BackslashF: Character = Character(UnicodeScalar(12))
public static let BackslashR: Character = "\r"
public static let BackshashRBackslashN: Character = "\r\n"
//http://www.unicode.org/glossary/#supplementary_code_point
public static let MIN_SUPPLEMENTARY_CODE_POINT: UInt32 = 0x010000
/// True for any space character, and the control characters \t, \n, \r, \f, \v.
var isWhitespace: Bool {
switch self {
case Character.space, Character.BackslashT, Character.BackslashN, Character.BackslashF, Character.BackslashR: return true
case Character.BackshashRBackslashN: return true
default: return false
}
}
/// `true` if `self` normalized contains a single code unit that is in the category of Decimal Numbers.
var isDigit: Bool {
return isMemberOfCharacterSet(CharacterSet.decimalDigits)
}
/// Lowercase `self`.
var lowercase: Character {
let str = String(self).lowercased()
return str[str.startIndex]
}
/// Return `true` if `self` normalized contains a single code unit that is a member of the supplied character set.
///
/// - parameter set: The `NSCharacterSet` used to test for membership.
/// - returns: `true` if `self` normalized contains a single code unit that is a member of the supplied character set.
func isMemberOfCharacterSet(_ set: CharacterSet) -> Bool {
let normalized = String(self).precomposedStringWithCanonicalMapping
let unicodes = normalized.unicodeScalars
guard unicodes.count == 1 else { return false }
return set.contains(UnicodeScalar(unicodes.first!.value)!)
}
static func convertFromIntegerLiteral(value: IntegerLiteralType) -> Character {
return Character(UnicodeScalar(value)!)
}
static func isLetter(_ char: Character) -> Bool {
return char.isLetter()
}
func isLetter() -> Bool {
return self.isMemberOfCharacterSet(CharacterSet.letters)
}
static func isLetterOrDigit(_ char: Character) -> Bool {
return char.isLetterOrDigit()
}
func isLetterOrDigit() -> Bool {
if(self.isLetter()) {return true}
return self.isDigit
}
}
+463
View File
@@ -0,0 +1,463 @@
//
// CharacterReader.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 10/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
CharacterReader consumes tokens off a string. To replace the old TokenQueue.
*/
public final class CharacterReader {
private static let empty = ""
public static let EOF: UnicodeScalar = "\u{FFFF}"//65535
private let input: [UnicodeScalar]
private let length: Int
private var pos: Int = 0
private var mark: Int = 0
//private let stringCache: Array<String?> // holds reused strings in this doc, to lessen garbage
public init(_ input: String) {
self.input = Array(input.unicodeScalars)
self.length = self.input.count
//stringCache = Array(repeating:nil, count:512)
}
public func getPos() -> Int {
return self.pos
}
public func isEmpty() -> Bool {
return pos >= length
}
public func current() -> UnicodeScalar {
return (pos >= length) ? CharacterReader.EOF : input[pos]
}
@discardableResult
public func consume() -> UnicodeScalar {
let val = (pos >= length) ? CharacterReader.EOF : input[pos]
pos += 1
return val
}
public func unconsume() {
pos -= 1
}
public func advance() {
pos += 1
}
public func markPos() {
mark = pos
}
public func rewindToMark() {
pos = mark
}
public func consumeAsString() -> String {
let p = pos
pos+=1
return String(input[p])
//return String(input, pos+=1, 1)
}
/**
* Returns the number of characters between the current position and the next instance of the input char
* @param c scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
public func nextIndexOf(_ c: UnicodeScalar) -> Int {
// doesn't handle scanning for surrogates
for i in pos..<length {
if (c == input[i]) {
return i - pos
}
}
return -1
}
/**
* Returns the number of characters between the current position and the next instance of the input sequence
*
* @param seq scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
public func nextIndexOf(_ seq: String) -> Int {
// doesn't handle scanning for surrogates
if(seq.isEmpty) {return -1}
let startChar: UnicodeScalar = seq.unicodeScalar(0)
for var offset in pos..<length {
// scan to first instance of startchar:
if (startChar != input[offset]) {
offset+=1
while(offset < length && startChar != input[offset]) { offset+=1 }
}
var i = offset + 1
let last = i + seq.unicodeScalars.count-1
if (offset < length && last <= length) {
var j = 1
while i < last && seq.unicodeScalar(j) == input[i] {
j+=1
i+=1
}
// found full sequence
if (i == last) {
return offset - pos
}
}
}
return -1
}
public func consumeTo(_ c: UnicodeScalar) -> String {
let offset = nextIndexOf(c)
if (offset != -1) {
let consumed = cacheString(pos, offset)
pos += offset
return consumed
} else {
return consumeToEnd()
}
}
public func consumeTo(_ seq: String) -> String {
let offset = nextIndexOf(seq)
if (offset != -1) {
let consumed = cacheString(pos, offset)
pos += offset
return consumed
} else {
return consumeToEnd()
}
}
public func consumeToAny(_ chars: UnicodeScalar...) -> String {
return consumeToAny(chars)
}
public func consumeToAny(_ chars: [UnicodeScalar]) -> String {
let start: Int = pos
let remaining: Int = length
let val = input
OUTER: while (pos < remaining) {
if chars.contains(val[pos]) {
break OUTER
}
// for c in chars {
// if (val[pos] == c){
// break OUTER
// }
// }
pos += 1
}
return pos > start ? cacheString(start, pos-start) : CharacterReader.empty
}
public func consumeToAnySorted(_ chars: UnicodeScalar...) -> String {
return consumeToAnySorted(chars)
}
public func consumeToAnySorted(_ chars: [UnicodeScalar]) -> String {
let start = pos
let remaining = length
let val = input
while (pos < remaining) {
if chars.contains(val[pos]) {
break
}
pos += 1
}
return pos > start ? cacheString(start, pos-start) : CharacterReader.empty
}
public func consumeData() -> String {
// &, <, null
let start = pos
let remaining = length
let val = input
while (pos < remaining) {
let c: UnicodeScalar = val[pos]
if (c == UnicodeScalar.Ampersand || c == UnicodeScalar.LessThan || c == TokeniserStateVars.nullScalr) {
break
}
pos += 1
}
return pos > start ? cacheString(start, pos-start) : CharacterReader.empty
}
public func consumeTagName() -> String {
// '\t', '\n', '\r', '\f', ' ', '/', '>', nullChar
let start = pos
let remaining = length
let val = input
while (pos < remaining) {
let c: UnicodeScalar = val[pos]
if (c == UnicodeScalar.BackslashT || c == UnicodeScalar.BackslashN || c == UnicodeScalar.BackslashR || c == UnicodeScalar.BackslashF || c == UnicodeScalar.Space || c == UnicodeScalar.Slash || c == UnicodeScalar.GreaterThan || c == TokeniserStateVars.nullScalr) {
break
}
pos += 1
}
return pos > start ? cacheString(start, pos-start) : CharacterReader.empty
}
public func consumeToEnd() -> String {
let data = cacheString(pos, length-pos)
pos = length
return data
}
public func consumeLetterSequence() -> String {
let start = pos
while (pos < length) {
let c: UnicodeScalar = input[pos]
if ((c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)) {
pos += 1
} else {
break
}
}
return cacheString(start, pos - start)
}
public func consumeLetterThenDigitSequence() -> String {
let start = pos
while (pos < length) {
let c = input[pos]
if ((c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)) {
pos += 1
} else {
break
}
}
while (!isEmpty()) {
let c = input[pos]
if (c >= "0" && c <= "9") {
pos += 1
} else {
break
}
}
return cacheString(start, pos - start)
}
public func consumeHexSequence() -> String {
let start = pos
while (pos < length) {
let c = input[pos]
if ((c >= "0" && c <= "9") || (c >= "A" && c <= "F") || (c >= "a" && c <= "f")) {
pos+=1
} else {
break
}
}
return cacheString(start, pos - start)
}
public func consumeDigitSequence() -> String {
let start = pos
while (pos < length) {
let c = input[pos]
if (c >= "0" && c <= "9") {
pos+=1
} else {
break
}
}
return cacheString(start, pos - start)
}
public func matches(_ c: UnicodeScalar) -> Bool {
return !isEmpty() && input[pos] == c
}
public func matches(_ seq: String) -> Bool {
let scanLength = seq.unicodeScalars.count
if (scanLength > length - pos) {
return false
}
for offset in 0..<scanLength {
if (seq.unicodeScalar(offset) != input[pos+offset]) {
return false
}
}
return true
}
public func matchesIgnoreCase(_ seq: String ) -> Bool {
let scanLength = seq.unicodeScalars.count
if(scanLength == 0) {
return false
}
if (scanLength > length - pos) {
return false
}
for offset in 0..<scanLength {
let upScan: UnicodeScalar = seq.unicodeScalar(offset).uppercase
let upTarget: UnicodeScalar = input[pos+offset].uppercase
if (upScan != upTarget) {
return false
}
}
return true
}
public func matchesAny(_ seq: UnicodeScalar...) -> Bool {
if (isEmpty()) {
return false
}
let c: UnicodeScalar = input[pos]
for seek in seq {
if (seek == c) {
return true
}
}
return false
}
public func matchesAnySorted(_ seq: [UnicodeScalar]) -> Bool {
return !isEmpty() && seq.contains(input[pos])
}
public func matchesLetter() -> Bool {
if (isEmpty()) {
return false
}
let c = input[pos]
return (c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)
}
public func matchesDigit() -> Bool {
if (isEmpty()) {
return false
}
let c = input[pos]
return (c >= "0" && c <= "9")
}
@discardableResult
public func matchConsume(_ seq: String) -> Bool {
if (matches(seq)) {
pos += seq.unicodeScalars.count
return true
} else {
return false
}
}
@discardableResult
public func matchConsumeIgnoreCase(_ seq: String) -> Bool {
if (matchesIgnoreCase(seq)) {
pos += seq.unicodeScalars.count
return true
} else {
return false
}
}
public func containsIgnoreCase(_ seq: String ) -> Bool {
// used to check presence of </title>, </style>. only finds consistent case.
let loScan = seq.lowercased(with: Locale(identifier: "en"))
let hiScan = seq.uppercased(with: Locale(identifier: "eng"))
return (nextIndexOf(loScan) > -1) || (nextIndexOf(hiScan) > -1)
}
public func toString() -> String {
return String(input[pos..<length])
//return String.unicodescalars(Array(input[pos..<length]))
//return input.string(pos, length - pos)
}
/**
* Caches short strings, as a flywheel pattern, to reduce GC load. Just for this doc, to prevent leaks.
* <p />
* Simplistic, and on hash collisions just falls back to creating a new string, vs a full HashMap with Entry list.
* That saves both having to create objects as hash keys, and running through the entry list, at the expense of
* some more duplicates.
*/
private func cacheString(_ start: Int, _ count: Int) -> String {
return String(input[start..<start+count])
// Too Slow
// var cache: [String?] = stringCache
//
// // limit (no cache):
// if (count > CharacterReader.maxCacheLen) {
// return String(val[start..<start+count].flatMap { Character($0) })
// }
//
// // calculate hash:
// var hash: Int = 0
// var offset = start
// for _ in 0..<count {
// let ch = val[offset].value
// hash = Int.addWithOverflow(Int.multiplyWithOverflow(31, hash).0, Int(ch)).0
// offset+=1
// }
//
// // get from cache
// hash = abs(hash)
// let i = hash % cache.count
// let index: Int = abs(i) //Int(hash & Int(cache.count) - 1)
// var cached = cache[index]
//
// if (cached == nil) { // miss, add
// cached = String(val[start..<start+count].flatMap { Character($0) })
// //cached = val.string(start, count)
// cache[Int(index)] = cached
// } else { // hashcode hit, check equality
// if (rangeEquals(start, count, cached!)) { // hit
// return cached!
// } else { // hashcode conflict
// cached = String(val[start..<start+count].flatMap { Character($0) })
// //cached = val.string(start, count)
// cache[index] = cached // update the cache, as recently used strings are more likely to show up again
// }
// }
// return cached!
}
// /**
// * Check if the value of the provided range equals the string.
// */
// public func rangeEquals(_ start: Int, _ count: Int, _ cached: String) -> Bool {
// if (count == cached.unicodeScalars.count) {
// var count = count
// let one = input
// var i = start
// var j = 0
// while (count != 0) {
// count -= 1
// if (one[i] != cached.unicodeScalar(j) ) {
// return false
// }
// j += 1
// i += 1
// }
// return true
// }
// return false
// }
}
extension CharacterReader: CustomDebugStringConvertible {
public var debugDescription: String {
return self.toString()
}
}
+150
View File
@@ -0,0 +1,150 @@
//
// Cleaner.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 15/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class Cleaner {
fileprivate let whitelist: Whitelist
/**
Create a new cleaner, that sanitizes documents using the supplied whitelist.
@param whitelist white-list to clean with
*/
public init(_ whitelist: Whitelist) {
self.whitelist = whitelist
}
/**
Creates a new, clean document, from the original dirty document, containing only elements allowed by the whitelist.
The original document is not modified. Only elements from the dirt document's <code>body</code> are used.
@param dirtyDocument Untrusted base document to clean.
@return cleaned document.
*/
public func clean(_ dirtyDocument: Document)throws->Document {
//Validate.notNull(dirtyDocument)
let clean: Document = Document.createShell(dirtyDocument.getBaseUri())
if (dirtyDocument.body() != nil && clean.body() != nil) // frameset documents won't have a body. the clean doc will have empty body.
{
try copySafeNodes(dirtyDocument.body()!, clean.body()!)
}
return clean
}
/**
Determines if the input document is valid, against the whitelist. It is considered valid if all the tags and attributes
in the input HTML are allowed by the whitelist.
<p>
This method can be used as a validator for user input forms. An invalid document will still be cleaned successfully
using the {@link #clean(Document)} document. If using as a validator, it is recommended to still clean the document
to ensure enforced attributes are set correctly, and that the output is tidied.
</p>
@param dirtyDocument document to test
@return true if no tags or attributes need to be removed; false if they do
*/
public func isValid(_ dirtyDocument: Document)throws->Bool {
//Validate.notNull(dirtyDocument)
let clean: Document = Document.createShell(dirtyDocument.getBaseUri())
let numDiscarded: Int = try copySafeNodes(dirtyDocument.body()!, clean.body()!)
return numDiscarded == 0
}
@discardableResult
fileprivate func copySafeNodes(_ source: Element, _ dest: Element)throws->Int {
let cleaningVisitor: Cleaner.CleaningVisitor = Cleaner.CleaningVisitor(source, dest, self)
let traversor: NodeTraversor = NodeTraversor(cleaningVisitor)
try traversor.traverse(source)
return cleaningVisitor.numDiscarded
}
fileprivate func createSafeElement(_ sourceEl: Element)throws->ElementMeta {
let sourceTag: String = sourceEl.tagName()
let destAttrs: Attributes = Attributes()
let dest: Element = try Element(Tag.valueOf(sourceTag), sourceEl.getBaseUri(), destAttrs)
var numDiscarded: Int = 0
if let sourceAttrs = sourceEl.getAttributes() {
for sourceAttr: Attribute in sourceAttrs {
if (try whitelist.isSafeAttribute(sourceTag, sourceEl, sourceAttr)) {
destAttrs.put(attribute: sourceAttr)
} else {
numDiscarded+=1
}
}
}
let enforcedAttrs: Attributes = try whitelist.getEnforcedAttributes(sourceTag)
destAttrs.addAll(incoming: enforcedAttrs)
return ElementMeta(dest, numDiscarded)
}
}
extension Cleaner {
fileprivate final class CleaningVisitor: NodeVisitor {
var numDiscarded: Int = 0
let root: Element
var destination: Element? // current element to append nodes to
private var cleaner: Cleaner
public init(_ root: Element, _ destination: Element, _ cleaner: Cleaner) {
self.root = root
self.destination = destination
self.cleaner = cleaner
}
public func head(_ source: Node, _ depth: Int)throws {
if let sourceEl = (source as? Element) {
if (cleaner.whitelist.isSafeTag(sourceEl.tagName())) { // safe, clone and copy safe attrs
let meta: Cleaner.ElementMeta = try cleaner.createSafeElement(sourceEl)
let destChild: Element = meta.el
try destination?.appendChild(destChild)
numDiscarded += meta.numAttribsDiscarded
destination = destChild
} else if (source != root) { // not a safe tag, so don't add. don't count root against discarded.
numDiscarded+=1
}
} else if let sourceText = (source as? TextNode) {
let destText: TextNode = TextNode(sourceText.getWholeText(), source.getBaseUri())
try destination?.appendChild(destText)
} else if let sourceData = (source as? DataNode) {
if sourceData.parent() != nil && cleaner.whitelist.isSafeTag(sourceData.parent()!.nodeName()) {
//let sourceData: DataNode = (DataNode) source
let destData: DataNode = DataNode(sourceData.getWholeData(), source.getBaseUri())
try destination?.appendChild(destData)
} else {
numDiscarded+=1
}
} else { // else, we don't care about comments, xml proc instructions, etc
numDiscarded+=1
}
}
public func tail(_ source: Node, _ depth: Int)throws {
if let x = (source as? Element) {
if cleaner.whitelist.isSafeTag(x.nodeName()) {
// would have descended, so pop destination stack
destination = destination?.parent()
}
}
}
}
}
extension Cleaner {
fileprivate struct ElementMeta {
let el: Element
let numAttribsDiscarded: Int
init(_ el: Element, _ numAttribsDiscarded: Int) {
self.el = el
self.numAttribsDiscarded = numAttribsDiscarded
}
}
}
+59
View File
@@ -0,0 +1,59 @@
//
// Collector.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 22/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* Collects a list of elements that match the supplied criteria.
*
*/
open class Collector {
private init() {
}
/**
Build a list of elements, by visiting root and every descendant of root, and testing it against the evaluator.
@param eval Evaluator to test elements against
@param root root of tree to descend
@return list of matches; empty if none
*/
public static func collect (_ eval: Evaluator, _ root: Element)throws->Elements {
let elements: Elements = Elements()
try NodeTraversor(Accumulator(root, elements, eval)).traverse(root)
return elements
}
}
private final class Accumulator: NodeVisitor {
private let root: Element
private let elements: Elements
private let eval: Evaluator
init(_ root: Element, _ elements: Elements, _ eval: Evaluator) {
self.root = root
self.elements = elements
self.eval = eval
}
public func head(_ node: Node, _ depth: Int) {
guard let el = node as? Element else {
return
}
do {
if try eval.matches(root, el) {
elements.add(el)
}
} catch {}
}
public func tail(_ node: Node, _ depth: Int) {
// void
}
}
+127
View File
@@ -0,0 +1,127 @@
//
// CombiningEvaluator.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 23/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* Base combining (and, or) evaluator.
*/
public class CombiningEvaluator: Evaluator {
public private(set) var evaluators: Array<Evaluator>
var num: Int = 0
public override init() {
evaluators = Array<Evaluator>()
super.init()
}
public init(_ evaluators: Array<Evaluator>) {
self.evaluators = evaluators
super.init()
updateNumEvaluators()
}
public init(_ evaluators: Evaluator...) {
self.evaluators = evaluators
super.init()
updateNumEvaluators()
}
func rightMostEvaluator() -> Evaluator? {
return num > 0 && evaluators.count > 0 ? evaluators[num - 1] : nil
}
func replaceRightMostEvaluator(_ replacement: Evaluator) {
evaluators[num - 1] = replacement
}
func updateNumEvaluators() {
// used so we don't need to bash on size() for every match test
num = evaluators.count
}
public final class And: CombiningEvaluator {
public override init(_ evaluators: [Evaluator]) {
super.init(evaluators)
}
public override init(_ evaluators: Evaluator...) {
super.init(evaluators)
}
public override func matches(_ root: Element, _ node: Element) -> Bool {
for index in 0..<num {
let evaluator = evaluators[index]
do {
if (try !evaluator.matches(root, node)) {
return false
}
} catch {}
}
return true
}
public override func toString() -> String {
let array: [String] = evaluators.map { String($0.toString()) }
return StringUtil.join(array, sep: " ")
}
}
public final class Or: CombiningEvaluator {
/**
* Create a new Or evaluator. The initial evaluators are ANDed together and used as the first clause of the OR.
* @param evaluators initial OR clause (these are wrapped into an AND evaluator).
*/
public override init(_ evaluators: [Evaluator]) {
super.init()
if num > 1 {
self.evaluators.append(And(evaluators))
} else { // 0 or 1
self.evaluators.append(contentsOf: evaluators)
}
updateNumEvaluators()
}
override init(_ evaluators: Evaluator...) {
super.init()
if num > 1 {
self.evaluators.append(And(evaluators))
} else { // 0 or 1
self.evaluators.append(contentsOf: evaluators)
}
updateNumEvaluators()
}
override init() {
super.init()
}
public func add(_ evaluator: Evaluator) {
evaluators.append(evaluator)
updateNumEvaluators()
}
public override func matches(_ root: Element, _ node: Element) -> Bool {
for index in 0..<num {
let evaluator: Evaluator = evaluators[index]
do {
if (try evaluator.matches(root, node)) {
return true
}
} catch {}
}
return false
}
public override func toString() -> String {
return ":or\(evaluators.map {String($0.toString())})"
}
}
}
+66
View File
@@ -0,0 +1,66 @@
//
// Comment.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 22/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
A comment node.
*/
public class Comment: Node {
private static let COMMENT_KEY: String = "comment"
/**
Create a new comment node.
@param data The contents of the comment
@param baseUri base URI
*/
public init(_ data: String, _ baseUri: String) {
super.init(baseUri)
do {
try attributes?.put(Comment.COMMENT_KEY, data)
} catch {}
}
public override func nodeName() -> String {
return "#comment"
}
/**
Get the contents of the comment.
@return comment content
*/
public func getData() -> String {
return attributes!.get(key: Comment.COMMENT_KEY)
}
override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {
if (out.prettyPrint()) {
indent(accum, depth, out)
}
accum
.append("<!--")
.append(getData())
.append("-->")
}
override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {}
public override func copy(with zone: NSZone? = nil) -> Any {
let clone = Comment(attributes!.get(key: Comment.COMMENT_KEY), baseUri!)
return copy(clone: clone)
}
public override func copy(parent: Node?) -> Node {
let clone = Comment(attributes!.get(key: Comment.COMMENT_KEY), baseUri!)
return copy(clone: clone, parent: parent)
}
public override func copy(clone: Node, parent: Node?) -> Node {
return super.copy(clone: clone, parent: parent)
}
}
+10
View File
@@ -0,0 +1,10 @@
//
// Connection.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
//TODO:
+85
View File
@@ -0,0 +1,85 @@
//
// DataNode.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
A data node, for contents of style, script tags etc, where contents should not show in text().
*/
open class DataNode: Node {
private static let DATA_KEY: String = "data"
/**
Create a new DataNode.
@param data data contents
@param baseUri base URI
*/
public init(_ data: String, _ baseUri: String) {
super.init(baseUri)
do {
try attributes?.put(DataNode.DATA_KEY, data)
} catch {}
}
open override func nodeName() -> String {
return "#data"
}
/**
Get the data contents of this node. Will be unescaped and with original new lines, space etc.
@return data
*/
open func getWholeData() -> String {
return attributes!.get(key: DataNode.DATA_KEY)
}
/**
* Set the data contents of this node.
* @param data unencoded data
* @return this node, for chaining
*/
@discardableResult
open func setWholeData(_ data: String) -> DataNode {
do {
try attributes?.put(DataNode.DATA_KEY, data)
} catch {}
return self
}
override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings)throws {
accum.append(getWholeData()) // data is not escaped in return from data nodes, so " in script, style is plain
}
override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {}
/**
Create a new DataNode from HTML encoded data.
@param encodedData encoded data
@param baseUri bass URI
@return new DataNode
*/
public static func createFromEncoded(_ encodedData: String, _ baseUri: String)throws->DataNode {
let data = try Entities.unescape(encodedData)
return DataNode(data, baseUri)
}
public override func copy(with zone: NSZone? = nil) -> Any {
let clone = DataNode(attributes!.get(key: DataNode.DATA_KEY), baseUri!)
return copy(clone: clone)
}
public override func copy(parent: Node?) -> Node {
let clone = DataNode(attributes!.get(key: DataNode.DATA_KEY), baseUri!)
return copy(clone: clone, parent: parent)
}
public override func copy(clone: Node, parent: Node?) -> Node {
return super.copy(clone: clone, parent: parent)
}
}
+24
View File
@@ -0,0 +1,24 @@
//
// DataUtil.swift
// SwifSoup
//
// Created by Nabil Chatbi on 02/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* Internal static utilities for handling data.
*
*/
class DataUtil {
static let charsetPattern = "(?i)\\bcharset=\\s*(?:\"|')?([^\\s,;\"']*)"
static let defaultCharset = "UTF-8" // used if not found in header or meta charset
static let bufferSize = 0x20000 // ~130K.
static let UNICODE_BOM = 0xFEFF
static let mimeBoundaryChars = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
static let boundaryLength = 32
}
+562
View File
@@ -0,0 +1,562 @@
//
// Document.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class Document: Element {
public enum QuirksMode {
case noQuirks, quirks, limitedQuirks
}
private var _outputSettings: OutputSettings = OutputSettings()
private var _quirksMode: Document.QuirksMode = QuirksMode.noQuirks
private let _location: String
private var updateMetaCharset: Bool = false
/**
Create a new, empty Document.
@param baseUri base URI of document
@see org.jsoup.Jsoup#parse
@see #createShell
*/
public init(_ baseUri: String) {
self._location = baseUri
super.init(try! Tag.valueOf("#root", ParseSettings.htmlDefault), baseUri)
}
/**
Create a valid, empty shell of a document, suitable for adding more elements to.
@param baseUri baseUri of document
@return document with html, head, and body elements.
*/
static public func createShell(_ baseUri: String) -> Document {
let doc: Document = Document(baseUri)
let html: Element = try! doc.appendElement("html")
try! html.appendElement("head")
try! html.appendElement("body")
return doc
}
/**
* Get the URL this Document was parsed from. If the starting URL is a redirect,
* this will return the final URL from which the document was served from.
* @return location
*/
public func location() -> String {
return _location
}
/**
Accessor to the document's {@code head} element.
@return {@code head}
*/
public func head() -> Element? {
return findFirstElementByTagName("head", self)
}
/**
Accessor to the document's {@code body} element.
@return {@code body}
*/
public func body() -> Element? {
return findFirstElementByTagName("body", self)
}
/**
Get the string contents of the document's {@code title} element.
@return Trimmed title, or empty string if none set.
*/
public func title()throws->String {
// title is a preserve whitespace tag (for document output), but normalised here
let titleEl: Element? = try getElementsByTag("title").first()
return titleEl != nil ? try StringUtil.normaliseWhitespace(titleEl!.text()).trim() : ""
}
/**
Set the document's {@code title} element. Updates the existing element, or adds {@code title} to {@code head} if
not present
@param title string to set as title
*/
public func title(_ title: String)throws {
let titleEl: Element? = try getElementsByTag("title").first()
if (titleEl == nil) { // add to head
try head()?.appendElement("title").text(title)
} else {
try titleEl?.text(title)
}
}
/**
Create a new Element, with this document's base uri. Does not make the new element a child of this document.
@param tagName element tag name (e.g. {@code a})
@return new element
*/
public func createElement(_ tagName: String)throws->Element {
return try Element(Tag.valueOf(tagName, ParseSettings.preserveCase), self.getBaseUri())
}
/**
Normalise the document. This happens after the parse phase so generally does not need to be called.
Moves any text content that is not in the body element into the body.
@return this document after normalisation
*/
@discardableResult
public func normalise()throws->Document {
var htmlE: Element? = findFirstElementByTagName("html", self)
if (htmlE == nil) {
htmlE = try appendElement("html")
}
let htmlEl: Element = htmlE!
if (head() == nil) {
try htmlEl.prependElement("head")
}
if (body() == nil) {
try htmlEl.appendElement("body")
}
// pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care
// of. do in inverse order to maintain text order.
try normaliseTextNodes(head()!)
try normaliseTextNodes(htmlEl)
try normaliseTextNodes(self)
try normaliseStructure("head", htmlEl)
try normaliseStructure("body", htmlEl)
try ensureMetaCharsetElement()
return self
}
// does not recurse.
private func normaliseTextNodes(_ element: Element)throws {
var toMove: Array<Node> = Array<Node>()
for node: Node in element.childNodes {
if let tn = (node as? TextNode) {
if (!tn.isBlank()) {
toMove.append(tn)
}
}
}
for i in (0..<toMove.count).reversed() {
let node: Node = toMove[i]
try element.removeChild(node)
try body()?.prependChild(TextNode(" ", ""))
try body()?.prependChild(node)
}
}
// merge multiple <head> or <body> contents into one, delete the remainder, and ensure they are owned by <html>
private func normaliseStructure(_ tag: String, _ htmlEl: Element)throws {
let elements: Elements = try self.getElementsByTag(tag)
let master: Element? = elements.first() // will always be available as created above if not existent
if (elements.size() > 1) { // dupes, move contents to master
var toMove: Array<Node> = Array<Node>()
for i in 1..<elements.size() {
let dupe: Node = elements.get(i)
for node: Node in dupe.childNodes {
toMove.append(node)
}
try dupe.remove()
}
for dupe: Node in toMove {
try master?.appendChild(dupe)
}
}
// ensure parented by <html>
if (!(master != nil && master!.parent() != nil && master!.parent()!.equals(htmlEl))) {
try htmlEl.appendChild(master!) // includes remove()
}
}
// fast method to get first by tag name, used for html, head, body finders
private func findFirstElementByTagName(_ tag: String, _ node: Node) -> Element? {
if (node.nodeName()==tag) {
return node as? Element
} else {
for child: Node in node.childNodes {
let found: Element? = findFirstElementByTagName(tag, child)
if (found != nil) {
return found
}
}
}
return nil
}
open override func outerHtml()throws->String {
return try super.html() // no outer wrapper tag
}
/**
Set the text of the {@code body} of this document. Any existing nodes within the body will be cleared.
@param text unencoded text
@return this document
*/
@discardableResult
public override func text(_ text: String)throws->Element {
try body()?.text(text) // overridden to not nuke doc structure
return self
}
open override func nodeName() -> String {
return "#document"
}
/**
* Sets the charset used in this document. This method is equivalent
* to {@link OutputSettings#charset(java.nio.charset.Charset)
* OutputSettings.charset(Charset)} but in addition it updates the
* charset / encoding element within the document.
*
* <p>This enables
* {@link #updateMetaCharsetElement(boolean) meta charset update}.</p>
*
* <p>If there's no element with charset / encoding information yet it will
* be created. Obsolete charset / encoding definitions are removed!</p>
*
* <p><b>Elements used:</b></p>
*
* <ul>
* <li><b>Html:</b> <i>&lt;meta charset="CHARSET"&gt;</i></li>
* <li><b>Xml:</b> <i>&lt;?xml version="1.0" encoding="CHARSET"&gt;</i></li>
* </ul>
*
* @param charset Charset
*
* @see #updateMetaCharsetElement(boolean)
* @see OutputSettings#charset(java.nio.charset.Charset)
*/
public func charset(_ charset: String.Encoding)throws {
updateMetaCharsetElement(true)
_outputSettings.charset(charset)
try ensureMetaCharsetElement()
}
/**
* Returns the charset used in this document. This method is equivalent
* to {@link OutputSettings#charset()}.
*
* @return Current Charset
*
* @see OutputSettings#charset()
*/
public func charset()->String.Encoding {
return _outputSettings.charset()
}
/**
* Sets whether the element with charset information in this document is
* updated on changes through {@link #charset(java.nio.charset.Charset)
* Document.charset(Charset)} or not.
*
* <p>If set to <tt>false</tt> <i>(default)</i> there are no elements
* modified.</p>
*
* @param update If <tt>true</tt> the element updated on charset
* changes, <tt>false</tt> if not
*
* @see #charset(java.nio.charset.Charset)
*/
public func updateMetaCharsetElement(_ update: Bool) {
self.updateMetaCharset = update
}
/**
* Returns whether the element with charset information in this document is
* updated on changes through {@link #charset(java.nio.charset.Charset)
* Document.charset(Charset)} or not.
*
* @return Returns <tt>true</tt> if the element is updated on charset
* changes, <tt>false</tt> if not
*/
public func updateMetaCharsetElement() -> Bool {
return updateMetaCharset
}
/**
* Ensures a meta charset (html) or xml declaration (xml) with the current
* encoding used. This only applies with
* {@link #updateMetaCharsetElement(boolean) updateMetaCharset} set to
* <tt>true</tt>, otherwise this method does nothing.
*
* <ul>
* <li>An exsiting element gets updated with the current charset</li>
* <li>If there's no element yet it will be inserted</li>
* <li>Obsolete elements are removed</li>
* </ul>
*
* <p><b>Elements used:</b></p>
*
* <ul>
* <li><b>Html:</b> <i>&lt;meta charset="CHARSET"&gt;</i></li>
* <li><b>Xml:</b> <i>&lt;?xml version="1.0" encoding="CHARSET"&gt;</i></li>
* </ul>
*/
private func ensureMetaCharsetElement()throws {
if (updateMetaCharset) {
let syntax: OutputSettings.Syntax = outputSettings().syntax()
if (syntax == OutputSettings.Syntax.html) {
let metaCharset: Element? = try select("meta[charset]").first()
if (metaCharset != nil) {
try metaCharset?.attr("charset", charset().displayName())
} else {
let head: Element? = self.head()
if (head != nil) {
try head?.appendElement("meta").attr("charset", charset().displayName())
}
}
// Remove obsolete elements
let s = try select("meta[name=charset]")
try s.remove()
} else if (syntax == OutputSettings.Syntax.xml) {
let node: Node = getChildNodes()[0]
if let decl = (node as? XmlDeclaration) {
if (decl.name()=="xml") {
try decl.attr("encoding", charset().displayName())
_ = try decl.attr("version")
try decl.attr("version", "1.0")
} else {
try Validate.notNull(obj: baseUri)
let decl = XmlDeclaration("xml", baseUri!, false)
try decl.attr("version", "1.0")
try decl.attr("encoding", charset().displayName())
try prependChild(decl)
}
} else {
try Validate.notNull(obj: baseUri)
let decl = XmlDeclaration("xml", baseUri!, false)
try decl.attr("version", "1.0")
try decl.attr("encoding", charset().displayName())
try prependChild(decl)
}
}
}
}
/**
* Get the document's current output settings.
* @return the document's current output settings.
*/
public func outputSettings() -> OutputSettings {
return _outputSettings
}
/**
* Set the document's output settings.
* @param outputSettings new output settings.
* @return this document, for chaining.
*/
@discardableResult
public func outputSettings(_ outputSettings: OutputSettings) -> Document {
self._outputSettings = outputSettings
return self
}
public func quirksMode()->Document.QuirksMode {
return _quirksMode
}
@discardableResult
public func quirksMode(_ quirksMode: Document.QuirksMode) -> Document {
self._quirksMode = quirksMode
return self
}
public override func copy(with zone: NSZone? = nil) -> Any {
let clone = Document(_location)
return copy(clone: clone)
}
public override func copy(parent: Node?) -> Node {
let clone = Document(_location)
return copy(clone: clone, parent: parent)
}
public override func copy(clone: Node, parent: Node?) -> Node {
let clone = clone as! Document
clone._outputSettings = _outputSettings.copy() as! OutputSettings
clone._quirksMode = _quirksMode
clone.updateMetaCharset = updateMetaCharset
return super.copy(clone: clone, parent: parent)
}
}
public class OutputSettings: NSCopying {
/**
* The output serialization syntax.
*/
public enum Syntax {case html, xml}
private var _escapeMode: Entities.EscapeMode = Entities.EscapeMode.base
private var _encoder: String.Encoding = String.Encoding.utf8 // Charset.forName("UTF-8")
private var _prettyPrint: Bool = true
private var _outline: Bool = false
private var _indentAmount: UInt = 1
private var _syntax = Syntax.html
public init() {}
/**
* Get the document's current HTML escape mode: <code>base</code>, which provides a limited set of named HTML
* entities and escapes other characters as numbered entities for maximum compatibility; or <code>extended</code>,
* which uses the complete set of HTML named entities.
* <p>
* The default escape mode is <code>base</code>.
* @return the document's current escape mode
*/
public func escapeMode() -> Entities.EscapeMode {
return _escapeMode
}
/**
* Set the document's escape mode, which determines how characters are escaped when the output character set
* does not support a given character:- using either a named or a numbered escape.
* @param escapeMode the new escape mode to use
* @return the document's output settings, for chaining
*/
@discardableResult
public func escapeMode(_ escapeMode: Entities.EscapeMode) -> OutputSettings {
self._escapeMode = escapeMode
return self
}
/**
* Get the document's current output charset, which is used to control which characters are escaped when
* generating HTML (via the <code>html()</code> methods), and which are kept intact.
* <p>
* Where possible (when parsing from a URL or File), the document's output charset is automatically set to the
* input charset. Otherwise, it defaults to UTF-8.
* @return the document's current charset.
*/
public func encoder() -> String.Encoding {
return _encoder
}
public func charset() -> String.Encoding {
return _encoder
}
/**
* Update the document's output charset.
* @param charset the new charset to use.
* @return the document's output settings, for chaining
*/
@discardableResult
public func encoder(_ encoder: String.Encoding) -> OutputSettings {
self._encoder = encoder
return self
}
@discardableResult
public func charset(_ e: String.Encoding) -> OutputSettings {
return encoder(e)
}
/**
* Get the document's current output syntax.
* @return current syntax
*/
public func syntax() -> Syntax {
return _syntax
}
/**
* Set the document's output syntax. Either {@code html}, with empty tags and boolean attributes (etc), or
* {@code xml}, with self-closing tags.
* @param syntax serialization syntax
* @return the document's output settings, for chaining
*/
@discardableResult
public func syntax(syntax: Syntax) -> OutputSettings {
_syntax = syntax
return self
}
/**
* Get if pretty printing is enabled. Default is true. If disabled, the HTML output methods will not re-format
* the output, and the output will generally look like the input.
* @return if pretty printing is enabled.
*/
public func prettyPrint() -> Bool {
return _prettyPrint
}
/**
* Enable or disable pretty printing.
* @param pretty new pretty print setting
* @return this, for chaining
*/
@discardableResult
public func prettyPrint(pretty: Bool) -> OutputSettings {
_prettyPrint = pretty
return self
}
/**
* Get if outline mode is enabled. Default is false. If enabled, the HTML output methods will consider
* all tags as block.
* @return if outline mode is enabled.
*/
public func outline() -> Bool {
return _outline
}
/**
* Enable or disable HTML outline mode.
* @param outlineMode new outline setting
* @return this, for chaining
*/
@discardableResult
public func outline(outlineMode: Bool) -> OutputSettings {
_outline = outlineMode
return self
}
/**
* Get the current tag indent amount, used when pretty printing.
* @return the current indent amount
*/
public func indentAmount() -> UInt {
return _indentAmount
}
/**
* Set the indent amount for pretty printing
* @param indentAmount number of spaces to use for indenting each level. Must be {@literal >=} 0.
* @return this, for chaining
*/
@discardableResult
public func indentAmount(indentAmount: UInt) -> OutputSettings {
_indentAmount = indentAmount
return self
}
public func copy(with zone: NSZone? = nil) -> Any {
let clone: OutputSettings = OutputSettings()
clone.charset(_encoder) // new charset and charset encoder
clone._escapeMode = _escapeMode//Entities.EscapeMode.valueOf(escapeMode.name())
// indentAmount, prettyPrint are primitives so object.clone() will handle
return clone
}
}
+129
View File
@@ -0,0 +1,129 @@
//
// DocumentType.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* A {@code <!DOCTYPE>} node.
*/
public class DocumentType: Node {
static let PUBLIC_KEY: String = "PUBLIC"
static let SYSTEM_KEY: String = "SYSTEM"
private static let NAME: String = "name"
private static let PUB_SYS_KEY: String = "pubSysKey"; // PUBLIC or SYSTEM
private static let PUBLIC_ID: String = "publicId"
private static let SYSTEM_ID: String = "systemId"
// todo: quirk mode from publicId and systemId
/**
* Create a new doctype element.
* @param name the doctype's name
* @param publicId the doctype's public ID
* @param systemId the doctype's system ID
* @param baseUri the doctype's base URI
*/
public init(_ name: String, _ publicId: String, _ systemId: String, _ baseUri: String) {
super.init(baseUri)
do {
try attr(DocumentType.NAME, name)
try attr(DocumentType.PUBLIC_ID, publicId)
if (has(DocumentType.PUBLIC_ID)) {
try attr(DocumentType.PUB_SYS_KEY, DocumentType.PUBLIC_KEY)
}
try attr(DocumentType.SYSTEM_ID, systemId)
} catch {}
}
/**
* Create a new doctype element.
* @param name the doctype's name
* @param publicId the doctype's public ID
* @param systemId the doctype's system ID
* @param baseUri the doctype's base URI
*/
public init(_ name: String, _ pubSysKey: String?, _ publicId: String, _ systemId: String, _ baseUri: String) {
super.init(baseUri)
do {
try attr(DocumentType.NAME, name)
if(pubSysKey != nil) {
try attr(DocumentType.PUB_SYS_KEY, pubSysKey!)
}
try attr(DocumentType.PUBLIC_ID, publicId)
try attr(DocumentType.SYSTEM_ID, systemId)
} catch {}
}
public override func nodeName() -> String {
return "#doctype"
}
override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {
if (out.syntax() == OutputSettings.Syntax.html && !has(DocumentType.PUBLIC_ID) && !has(DocumentType.SYSTEM_ID)) {
// looks like a html5 doctype, go lowercase for aesthetics
accum.append("<!doctype")
} else {
accum.append("<!DOCTYPE")
}
if (has(DocumentType.NAME)) {
do {
accum.append(" ").append(try attr(DocumentType.NAME))
} catch {}
}
if (has(DocumentType.PUB_SYS_KEY)) {
do {
try accum.append(" ").append(attr(DocumentType.PUB_SYS_KEY))
} catch {}
}
if (has(DocumentType.PUBLIC_ID)) {
do {
try accum.append(" \"").append(attr(DocumentType.PUBLIC_ID)).append("\"")
} catch {}
}
if (has(DocumentType.SYSTEM_ID)) {
do {
accum.append(" \"").append(try attr(DocumentType.SYSTEM_ID)).append("\"")
} catch {}
}
accum.append(">")
}
override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {
}
private func has(_ attribute: String) -> Bool {
do {
return !StringUtil.isBlank(try attr(attribute))
} catch {return false}
}
public override func copy(with zone: NSZone? = nil) -> Any {
let clone = DocumentType(attributes!.get(key: DocumentType.NAME),
attributes!.get(key: DocumentType.PUBLIC_ID),
attributes!.get(key: DocumentType.SYSTEM_ID),
baseUri!)
return copy(clone: clone)
}
public override func copy(parent: Node?) -> Node {
let clone = DocumentType(attributes!.get(key: DocumentType.NAME),
attributes!.get(key: DocumentType.PUBLIC_ID),
attributes!.get(key: DocumentType.SYSTEM_ID),
baseUri!)
return copy(clone: clone, parent: parent)
}
public override func copy(clone: Node, parent: Node?) -> Node {
return super.copy(clone: clone, parent: parent)
}
}
File diff suppressed because it is too large Load Diff
+616
View File
@@ -0,0 +1,616 @@
//
// Elements.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 20/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
/**
A list of {@link Element}s, with methods that act on every element in the list.
<p>
To get an {@code Elements} object, use the {@link Element#select(String)} method.
</p>
*/
import Foundation
//open typealias Elements = Array<Element>
//typealias E = Element
open class Elements: NSCopying {
fileprivate var this: Array<Element> = Array<Element>()
///base init
public init() {
}
///Initialized with an array
public init(_ a: Array<Element>) {
this = a
}
///Initialized with an order set
public init(_ a: OrderedSet<Element>) {
this.append(contentsOf: a)
}
/**
* Creates a deep copy of these elements.
* @return a deep copy
*/
public func copy(with zone: NSZone? = nil) -> Any {
let clone: Elements = Elements()
for e: Element in this {
clone.add(e.copy() as! Element)
}
return clone
}
// attribute methods
/**
Get an attribute value from the first matched element that has the attribute.
@param attributeKey The attribute key.
@return The attribute value from the first matched element that has the attribute.. If no elements were matched (isEmpty() == true),
or if the no elements have the attribute, returns empty string.
@see #hasAttr(String)
*/
open func attr(_ attributeKey: String)throws->String {
for element in this {
if (element.hasAttr(attributeKey)) {
return try element.attr(attributeKey)
}
}
return ""
}
/**
Checks if any of the matched elements have this attribute set.
@param attributeKey attribute key
@return true if any of the elements have the attribute; false if none do.
*/
open func hasAttr(_ attributeKey: String) -> Bool {
for element in this {
if element.hasAttr(attributeKey) {return true}
}
return false
}
/**
* Set an attribute on all matched elements.
* @param attributeKey attribute key
* @param attributeValue attribute value
* @return this
*/
@discardableResult
open func attr(_ attributeKey: String, _ attributeValue: String)throws->Elements {
for element in this {
try element.attr(attributeKey, attributeValue)
}
return self
}
/**
* Remove an attribute from every matched element.
* @param attributeKey The attribute to remove.
* @return this (for chaining)
*/
@discardableResult
open func removeAttr(_ attributeKey: String)throws->Elements {
for element in this {
try element.removeAttr(attributeKey)
}
return self
}
/**
Add the class name to every matched element's {@code class} attribute.
@param className class name to add
@return this
*/
@discardableResult
open func addClass(_ className: String)throws->Elements {
for element in this {
try element.addClass(className)
}
return self
}
/**
Remove the class name from every matched element's {@code class} attribute, if present.
@param className class name to remove
@return this
*/
@discardableResult
open func removeClass(_ className: String)throws->Elements {
for element: Element in this {
try element.removeClass(className)
}
return self
}
/**
Toggle the class name on every matched element's {@code class} attribute.
@param className class name to add if missing, or remove if present, from every element.
@return this
*/
@discardableResult
open func toggleClass(_ className: String)throws->Elements {
for element: Element in this {
try element.toggleClass(className)
}
return self
}
/**
Determine if any of the matched elements have this class name set in their {@code class} attribute.
@param className class name to check for
@return true if any do, false if none do
*/
open func hasClass(_ className: String) -> Bool {
for element: Element in this {
if (element.hasClass(className)) {
return true
}
}
return false
}
/**
* Get the form element's value of the first matched element.
* @return The form element's value, or empty if not set.
* @see Element#val()
*/
open func val()throws->String {
if (size() > 0) {
return try first()!.val()
}
return ""
}
/**
* Set the form element's value in each of the matched elements.
* @param value The value to set into each matched element
* @return this (for chaining)
*/
@discardableResult
open func val(_ value: String)throws->Elements {
for element: Element in this {
try element.val(value)
}
return self
}
/**
* Get the combined text of all the matched elements.
* <p>
* Note that it is possible to get repeats if the matched elements contain both parent elements and their own
* children, as the Element.text() method returns the combined text of a parent and all its children.
* @return string of all text: unescaped and no HTML.
* @see Element#text()
*/
open func text()throws->String {
let sb: StringBuilder = StringBuilder()
for element: Element in this {
if (sb.length != 0) {
sb.append(" ")
}
sb.append(try element.text())
}
return sb.toString()
}
/// Check if an element has text
open func hasText() -> Bool {
for element: Element in this {
if (element.hasText()) {
return true
}
}
return false
}
/**
* Get the combined inner HTML of all matched elements.
* @return string of all element's inner HTML.
* @see #text()
* @see #outerHtml()
*/
open func html()throws->String {
let sb: StringBuilder = StringBuilder()
for element: Element in this {
if (sb.length != 0) {
sb.append("\n")
}
sb.append(try element.html())
}
return sb.toString()
}
/**
* Get the combined outer HTML of all matched elements.
* @return string of all element's outer HTML.
* @see #text()
* @see #html()
*/
open func outerHtml()throws->String {
let sb: StringBuilder = StringBuilder()
for element in this {
if (sb.length != 0) {
sb.append("\n")
}
sb.append(try element.outerHtml())
}
return sb.toString()
}
/**
* Get the combined outer HTML of all matched elements. Alias of {@link #outerHtml()}.
* @return string of all element's outer HTML.
* @see #text()
* @see #html()
*/
open func toString()throws->String {
return try outerHtml()
}
/**
* Update the tag name of each matched element. For example, to change each {@code <i>} to a {@code <em>}, do
* {@code doc.select("i").tagName("em");}
* @param tagName the new tag name
* @return this, for chaining
* @see Element#tagName(String)
*/
@discardableResult
open func tagName(_ tagName: String)throws->Elements {
for element: Element in this {
try element.tagName(tagName)
}
return self
}
/**
* Set the inner HTML of each matched element.
* @param html HTML to parse and set into each matched element.
* @return this, for chaining
* @see Element#html(String)
*/
@discardableResult
open func html(_ html: String)throws->Elements {
for element: Element in this {
try element.html(html)
}
return self
}
/**
* Add the supplied HTML to the start of each matched element's inner HTML.
* @param html HTML to add inside each element, before the existing HTML
* @return this, for chaining
* @see Element#prepend(String)
*/
@discardableResult
open func prepend(_ html: String)throws->Elements {
for element: Element in this {
try element.prepend(html)
}
return self
}
/**
* Add the supplied HTML to the end of each matched element's inner HTML.
* @param html HTML to add inside each element, after the existing HTML
* @return this, for chaining
* @see Element#append(String)
*/
@discardableResult
open func append(_ html: String)throws->Elements {
for element: Element in this {
try element.append(html)
}
return self
}
/**
* Insert the supplied HTML before each matched element's outer HTML.
* @param html HTML to insert before each element
* @return this, for chaining
* @see Element#before(String)
*/
@discardableResult
open func before(_ html: String)throws->Elements {
for element: Element in this {
try element.before(html)
}
return self
}
/**
* Insert the supplied HTML after each matched element's outer HTML.
* @param html HTML to insert after each element
* @return this, for chaining
* @see Element#after(String)
*/
@discardableResult
open func after(_ html: String)throws->Elements {
for element: Element in this {
try element.after(html)
}
return self
}
/**
Wrap the supplied HTML around each matched elements. For example, with HTML
{@code <p><b>This</b> is <b>Jsoup</b></p>},
<code>doc.select("b").wrap("&lt;i&gt;&lt;/i&gt;");</code>
becomes {@code <p><i><b>This</b></i> is <i><b>jsoup</b></i></p>}
@param html HTML to wrap around each element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
@return this (for chaining)
@see Element#wrap
*/
@discardableResult
open func wrap(_ html: String)throws->Elements {
try Validate.notEmpty(string: html)
for element: Element in this {
try element.wrap(html)
}
return self
}
/**
* Removes the matched elements from the DOM, and moves their children up into their parents. This has the effect of
* dropping the elements but keeping their children.
* <p>
* This is useful for e.g removing unwanted formatting elements but keeping their contents.
* </p>
*
* E.g. with HTML: <p>{@code <div><font>One</font> <font><a href="/">Two</a></font></div>}</p>
* <p>{@code doc.select("font").unwrap();}</p>
* <p>HTML = {@code <div>One <a href="/">Two</a></div>}</p>
*
* @return this (for chaining)
* @see Node#unwrap
*/
@discardableResult
open func unwrap()throws->Elements {
for element: Element in this {
try element.unwrap()
}
return self
}
/**
* Empty (remove all child nodes from) each matched element. This is similar to setting the inner HTML of each
* element to nothing.
* <p>
* E.g. HTML: {@code <div><p>Hello <b>there</b></p> <p>now</p></div>}<br>
* <code>doc.select("p").empty();</code><br>
* HTML = {@code <div><p></p> <p></p></div>}
* @return this, for chaining
* @see Element#empty()
* @see #remove()
*/
@discardableResult
open func empty() -> Elements {
for element: Element in this {
element.empty()
}
return self
}
/**
* Remove each matched element from the DOM. This is similar to setting the outer HTML of each element to nothing.
* <p>
* E.g. HTML: {@code <div><p>Hello</p> <p>there</p> <img /></div>}<br>
* <code>doc.select("p").remove();</code><br>
* HTML = {@code <div> <img /></div>}
* <p>
* Note that this method should not be used to clean user-submitted HTML; rather, use {@link org.jsoup.safety.Cleaner} to clean HTML.
* @return this, for chaining
* @see Element#empty()
* @see #empty()
*/
@discardableResult
open func remove()throws->Elements {
for element in this {
try element.remove()
}
return self
}
// filters
/**
* Find matching elements within this element list.
* @param query A {@link Selector} query
* @return the filtered list of elements, or an empty list if none match.
*/
open func select(_ query: String)throws->Elements {
return try Selector.select(query, this)
}
/**
* Remove elements from this list that match the {@link Selector} query.
* <p>
* E.g. HTML: {@code <div class=logo>One</div> <div>Two</div>}<br>
* <code>Elements divs = doc.select("div").not(".logo");</code><br>
* Result: {@code divs: [<div>Two</div>]}
* <p>
* @param query the selector query whose results should be removed from these elements
* @return a new elements list that contains only the filtered results
*/
open func not(_ query: String)throws->Elements {
let out: Elements = try Selector.select(query, this)
return Selector.filterOut(this, out.this)
}
/**
* Get the <i>nth</i> matched element as an Elements object.
* <p>
* See also {@link #get(int)} to retrieve an Element.
* @param index the (zero-based) index of the element in the list to retain
* @return Elements containing only the specified element, or, if that element did not exist, an empty list.
*/
open func eq(_ index: Int) -> Elements {
return size() > index ? Elements([get(index)]) : Elements()
}
/**
* Test if any of the matched elements match the supplied query.
* @param query A selector
* @return true if at least one element in the list matches the query.
*/
open func iS(_ query: String)throws->Bool {
let eval: Evaluator = try QueryParser.parse(query)
for e: Element in this {
if (try e.iS(eval)) {
return true
}
}
return false
}
/**
* Get all of the parents and ancestor elements of the matched elements.
* @return all of the parents and ancestor elements of the matched elements
*/
open func parents() -> Elements {
let combo: OrderedSet<Element> = OrderedSet<Element>()
for e: Element in this {
combo.append(contentsOf: e.parents().array())
}
return Elements(combo)
}
// list-like methods
/**
Get the first matched element.
@return The first matched element, or <code>null</code> if contents is empty.
*/
open func first() -> Element? {
return isEmpty() ? nil : get(0)
}
/// Check if no element stored
open func isEmpty() -> Bool {
return array().count == 0
}
/// Count
open func size() -> Int {
return array().count
}
/**
Get the last matched element.
@return The last matched element, or <code>null</code> if contents is empty.
*/
open func last() -> Element? {
return isEmpty() ? nil : get(size() - 1)
}
/**
* Perform a depth-first traversal on each of the selected elements.
* @param nodeVisitor the visitor callbacks to perform on each node
* @return this, for chaining
*/
@discardableResult
open func traverse(_ nodeVisitor: NodeVisitor)throws->Elements {
let traversor: NodeTraversor = NodeTraversor(nodeVisitor)
for el: Element in this {
try traversor.traverse(el)
}
return self
}
/**
* Get the {@link FormElement} forms from the selected elements, if any.
* @return a list of {@link FormElement}s pulled from the matched elements. The list will be empty if the elements contain
* no forms.
*/
open func forms()->Array<FormElement> {
var forms: Array<FormElement> = Array<FormElement>()
for el: Element in this {
if let el = el as? FormElement {
forms.append(el)
}
}
return forms
}
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
open func add(_ e: Element) {
this.append(e)
}
/**
* Insert the specified element at index.
*/
open func add(_ index: Int, _ element: Element) {
this.insert(element, at: index)
}
/// Return element at index
open func get(_ i: Int) -> Element {
return this[i]
}
/// Returns all elements
open func array()->Array<Element> {
return this
}
}
/**
* Elements extension Equatable.
*/
extension Elements: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: Elements, rhs: Elements) -> Bool {
return lhs.this == rhs.this
}
}
/**
* Elements IteratorProtocol.
*/
public struct ElementsIterator: IteratorProtocol {
/// Elements reference
let elements: Elements
//current element index
var index = 0
/// Initializer
init(_ countdown: Elements) {
self.elements = countdown
}
/// Advances to the next element and returns it, or `nil` if no next element
mutating public func next() -> Element? {
let result = index < elements.size() ? elements.get(index) : nil
index += 1
return result
}
}
/**
* Elements Extension Sequence.
*/
extension Elements: Sequence {
/// Returns an iterator over the elements of this sequence.
public func makeIterator() -> ElementsIterator {
return ElementsIterator(self)
}
}
File diff suppressed because one or more lines are too long
+720
View File
@@ -0,0 +1,720 @@
//
// Evaluator.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 22/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* Evaluates that an element matches the selector.
*/
public class Evaluator {
init () {}
/**
* Test if the element meets the evaluator's requirements.
*
* @param root Root of the matching subtree
* @param element tested element
* @return Returns <tt>true</tt> if the requirements are met or
* <tt>false</tt> otherwise
*/
open func matches(_ root: Element, _ element: Element)throws->Bool {
preconditionFailure("self method must be overridden")
}
open func toString() -> String {
preconditionFailure("self method must be overridden")
}
/**
* Evaluator for tag name
*/
public class Tag: Evaluator {
private let tagName: String
private let tagNameNormal: String
public init(_ tagName: String) {
self.tagName = tagName
self.tagNameNormal = tagName.lowercased()
}
open override func matches(_ root: Element, _ element: Element)throws->Bool {
return element.tagNameNormal() == tagNameNormal
}
open override func toString() -> String {
return String(tagName)
}
}
/**
* Evaluator for tag name that ends with
*/
public final class TagEndsWith: Evaluator {
private let tagName: String
public init(_ tagName: String) {
self.tagName = tagName
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
return (element.tagName().hasSuffix(tagName))
}
public override func toString() -> String {
return String(tagName)
}
}
/**
* Evaluator for element id
*/
public final class Id: Evaluator {
private let id: String
public init(_ id: String) {
self.id = id
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
return (id == element.id())
}
public override func toString() -> String {
return "#\(id)"
}
}
/**
* Evaluator for element class
*/
public final class Class: Evaluator {
private let className: String
public init(_ className: String) {
self.className = className
}
public override func matches(_ root: Element, _ element: Element) -> Bool {
return (element.hasClass(className))
}
public override func toString() -> String {
return ".\(className)"
}
}
/**
* Evaluator for attribute name matching
*/
public final class Attribute: Evaluator {
private let key: String
public init(_ key: String) {
self.key = key
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
return element.hasAttr(key)
}
public override func toString() -> String {
return "[\(key)]"
}
}
/**
* Evaluator for attribute name prefix matching
*/
public final class AttributeStarting: Evaluator {
private let keyPrefix: String
public init(_ keyPrefix: String)throws {
try Validate.notEmpty(string: keyPrefix)
self.keyPrefix = keyPrefix.lowercased()
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
if let values = element.getAttributes() {
for attribute in values where attribute.getKey().lowercased().hasPrefix(keyPrefix) {
return true
}
}
return false
}
public override func toString() -> String {
return "[^\(keyPrefix)]"
}
}
/**
* Evaluator for attribute name/value matching
*/
public final class AttributeWithValue: AttributeKeyPair {
public override init(_ key: String, _ value: String)throws {
try super.init(key, value)
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
if element.hasAttr(key) {
let string = try element.attr(key)
return value.equalsIgnoreCase(string: string.trim())
}
return false
}
public override func toString() -> String {
return "[\(key)=\(value)]"
}
}
/**
* Evaluator for attribute name != value matching
*/
public final class AttributeWithValueNot: AttributeKeyPair {
public override init(_ key: String, _ value: String)throws {
try super.init(key, value)
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
let string = try element.attr(key)
return !value.equalsIgnoreCase(string: string)
}
public override func toString() -> String {
return "[\(key)!=\(value)]"
}
}
/**
* Evaluator for attribute name/value matching (value prefix)
*/
public final class AttributeWithValueStarting: AttributeKeyPair {
public override init(_ key: String, _ value: String)throws {
try super.init(key, value)
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
if element.hasAttr(key) {
return try element.attr(key).lowercased().hasPrefix(value) // value is lower case already
}
return false
}
public override func toString() -> String {
return "[\(key)^=\(value)]"
}
}
/**
* Evaluator for attribute name/value matching (value ending)
*/
public final class AttributeWithValueEnding: AttributeKeyPair {
public override init(_ key: String, _ value: String)throws {
try super.init(key, value)
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
if element.hasAttr(key) {
return try element.attr(key).lowercased().hasSuffix(value) // value is lower case
}
return false
}
public override func toString() -> String {
return "[\(key)$=\(value)]"
}
}
/**
* Evaluator for attribute name/value matching (value containing)
*/
public final class AttributeWithValueContaining: AttributeKeyPair {
public override init(_ key: String, _ value: String)throws {
try super.init(key, value)
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
if element.hasAttr(key) {
return try element.attr(key).lowercased().contains(value) // value is lower case
}
return false
}
public override func toString() -> String {
return "[\(key)*=\(value)]"
}
}
/**
* Evaluator for attribute name/value matching (value regex matching)
*/
public final class AttributeWithValueMatching: Evaluator {
let key: String
let pattern: Pattern
public init(_ key: String, _ pattern: Pattern) {
self.key = key.trim().lowercased()
self.pattern = pattern
super.init()
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
if element.hasAttr(key) {
let string = try element.attr(key)
return pattern.matcher(in: string).find()
}
return false
}
public override func toString() -> String {
return "[\(key)~=\(pattern.toString())]"
}
}
/**
* Abstract evaluator for attribute name/value matching
*/
public class AttributeKeyPair: Evaluator {
let key: String
var value: String
public init(_ key: String, _ value2: String)throws {
var value2 = value2
try Validate.notEmpty(string: key)
try Validate.notEmpty(string: value2)
self.key = key.trim().lowercased()
if value2.startsWith("\"") && value2.hasSuffix("\"") || value2.startsWith("'") && value2.hasSuffix("'") {
value2 = value2.substring(1, value2.count-2)
}
self.value = value2.trim().lowercased()
}
open override func matches(_ root: Element, _ element: Element)throws->Bool {
preconditionFailure("self method must be overridden")
}
}
/**
* Evaluator for any / all element matching
*/
public final class AllElements: Evaluator {
public override func matches(_ root: Element, _ element: Element)throws->Bool {
return true
}
public override func toString() -> String {
return "*"
}
}
/**
* Evaluator for matching by sibling index number (e {@literal <} idx)
*/
public final class IndexLessThan: IndexEvaluator {
public override init(_ index: Int) {
super.init(index)
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
return try element.elementSiblingIndex() < index
}
public override func toString() -> String {
return ":lt(\(index))"
}
}
/**
* Evaluator for matching by sibling index number (e {@literal >} idx)
*/
public final class IndexGreaterThan: IndexEvaluator {
public override init(_ index: Int) {
super.init(index)
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
return try element.elementSiblingIndex() > index
}
public override func toString() -> String {
return ":gt(\(index))"
}
}
/**
* Evaluator for matching by sibling index number (e = idx)
*/
public final class IndexEquals: IndexEvaluator {
public override init(_ index: Int) {
super.init(index)
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
return try element.elementSiblingIndex() == index
}
public override func toString() -> String {
return ":eq(\(index))"
}
}
/**
* Evaluator for matching the last sibling (css :last-child)
*/
public final class IsLastChild: Evaluator {
public override func matches(_ root: Element, _ element: Element)throws->Bool {
if let parent = element.parent() {
let index = try element.elementSiblingIndex()
return !(parent is Document) && index == (parent.getChildNodes().count - 1)
}
return false
}
public override func toString() -> String {
return ":last-child"
}
}
public final class IsFirstOfType: IsNthOfType {
public init() {
super.init(0, 1)
}
public override func toString() -> String {
return ":first-of-type"
}
}
public final class IsLastOfType: IsNthLastOfType {
public init() {
super.init(0, 1)
}
public override func toString() -> String {
return ":last-of-type"
}
}
public class CssNthEvaluator: Evaluator {
public let a: Int
public let b: Int
public init(_ a: Int, _ b: Int) {
self.a = a
self.b = b
}
public init(_ b: Int) {
self.a = 0
self.b = b
}
open override func matches(_ root: Element, _ element: Element)throws->Bool {
let p: Element? = element.parent()
if (p == nil || (((p as? Document) != nil))) {return false}
let pos: Int = try calculatePosition(root, element)
if (a == 0) {return pos == b}
return (pos-b)*a >= 0 && (pos-b)%a==0
}
open override func toString() -> String {
if (a == 0) {
return ":\(getPseudoClass)(\(b))"
}
if (b == 0) {
return ":\(getPseudoClass)(\(a))"
}
return ":\(getPseudoClass)(\(a)\(b))"
}
open func getPseudoClass() -> String {
preconditionFailure("self method must be overridden")
}
open func calculatePosition(_ root: Element, _ element: Element)throws->Int {
preconditionFailure("self method must be overridden")
}
}
/**
* css-compatible Evaluator for :eq (css :nth-child)
*
* @see IndexEquals
*/
public final class IsNthChild: CssNthEvaluator {
public override init(_ a: Int, _ b: Int) {
super.init(a, b)
}
public override func calculatePosition(_ root: Element, _ element: Element)throws->Int {
return try element.elementSiblingIndex()+1
}
public override func getPseudoClass() -> String {
return "nth-child"
}
}
/**
* css pseudo class :nth-last-child)
*
* @see IndexEquals
*/
public final class IsNthLastChild: CssNthEvaluator {
public override init(_ a: Int, _ b: Int) {
super.init(a, b)
}
public override func calculatePosition(_ root: Element, _ element: Element)throws->Int {
var i = 0
if let l = element.parent() {
i = l.children().array().count
}
return i - (try element.elementSiblingIndex())
}
public override func getPseudoClass() -> String {
return "nth-last-child"
}
}
/**
* css pseudo class nth-of-type
*
*/
public class IsNthOfType: CssNthEvaluator {
public override init(_ a: Int, _ b: Int) {
super.init(a, b)
}
open override func calculatePosition(_ root: Element, _ element: Element) -> Int {
var pos = 0
let family: Elements? = element.parent()?.children()
if let array = family?.array() {
for el in array {
if (el.tag() == element.tag()) {pos+=1}
if (el === element) {break}
}
}
return pos
}
open override func getPseudoClass() -> String {
return "nth-of-type"
}
}
public class IsNthLastOfType: CssNthEvaluator {
public override init(_ a: Int, _ b: Int) {
super.init(a, b)
}
open override func calculatePosition(_ root: Element, _ element: Element)throws->Int {
var pos = 0
if let family = element.parent()?.children() {
let x = try element.elementSiblingIndex()
for i in x..<family.array().count {
if (family.get(i).tag() == element.tag()) {
pos+=1
}
}
}
return pos
}
open override func getPseudoClass() -> String {
return "nth-last-of-type"
}
}
/**
* Evaluator for matching the first sibling (css :first-child)
*/
public final class IsFirstChild: Evaluator {
public override func matches(_ root: Element, _ element: Element)throws->Bool {
let p = element.parent()
if(p != nil && !(((p as? Document) != nil))) {
return (try element.elementSiblingIndex()) == 0
}
return false
}
public override func toString() -> String {
return ":first-child"
}
}
/**
* css3 pseudo-class :root
* @see <a href="http://www.w3.org/TR/selectors/#root-pseudo">:root selector</a>
*
*/
public final class IsRoot: Evaluator {
public override func matches(_ root: Element, _ element: Element)throws->Bool {
let r: Element = ((root as? Document) != nil) ? root.child(0) : root
return element === r
}
public override func toString() -> String {
return ":root"
}
}
public final class IsOnlyChild: Evaluator {
public override func matches(_ root: Element, _ element: Element)throws->Bool {
let p = element.parent()
return p != nil && !((p as? Document) != nil) && element.siblingElements().array().count == 0
}
public override func toString() -> String {
return ":only-child"
}
}
public final class IsOnlyOfType: Evaluator {
public override func matches(_ root: Element, _ element: Element)throws->Bool {
let p = element.parent()
if (p == nil || (p as? Document) != nil) {return false}
var pos = 0
if let family = p?.children().array() {
for el in family {
if (el.tag() == element.tag()) {pos+=1}
}
}
return pos == 1
}
public override func toString() -> String {
return ":only-of-type"
}
}
public final class IsEmpty: Evaluator {
public override func matches(_ root: Element, _ element: Element)throws->Bool {
let family: Array<Node> = element.getChildNodes()
for n in family {
if (!((n as? Comment) != nil || (n as? XmlDeclaration) != nil || (n as? DocumentType) != nil)) {return false}
}
return true
}
public override func toString() -> String {
return ":empty"
}
}
/**
* Abstract evaluator for sibling index matching
*
* @author ant
*/
public class IndexEvaluator: Evaluator {
let index: Int
public init(_ index: Int) {
self.index = index
}
}
/**
* Evaluator for matching Element (and its descendants) text
*/
public final class ContainsText: Evaluator {
private let searchText: String
public init(_ searchText: String) {
self.searchText = searchText.lowercased()
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
return (try element.text().lowercased().contains(searchText))
}
public override func toString() -> String {
return ":contains(\(searchText)"
}
}
/**
* Evaluator for matching Element's own text
*/
public final class ContainsOwnText: Evaluator {
private let searchText: String
public init(_ searchText: String) {
self.searchText = searchText.lowercased()
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
return (element.ownText().lowercased().contains(searchText))
}
public override func toString() -> String {
return ":containsOwn(\(searchText)"
}
}
/**
* Evaluator for matching Element (and its descendants) text with regex
*/
public final class Matches: Evaluator {
private let pattern: Pattern
public init(_ pattern: Pattern) {
self.pattern = pattern
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
let m = try pattern.matcher(in: element.text())
return m.find()
}
public override func toString() -> String {
return ":matches(\(pattern)"
}
}
/**
* Evaluator for matching Element's own text with regex
*/
public final class MatchesOwn: Evaluator {
private let pattern: Pattern
public init(_ pattern: Pattern) {
self.pattern = pattern
}
public override func matches(_ root: Element, _ element: Element)throws->Bool {
let m = pattern.matcher(in: element.ownText())
return m.find()
}
public override func toString() -> String {
return ":matchesOwn(\(pattern.toString())"
}
}
}
+22
View File
@@ -0,0 +1,22 @@
//
// Exception.swift
// SwifSoup
//
// Created by Nabil Chatbi on 02/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
public enum ExceptionType {
case IllegalArgumentException
case IOException
case XmlDeclaration
case MalformedURLException
case CloneNotSupportedException
case SelectorParseException
}
public enum Exception: Error {
case Error(type:ExceptionType, Message: String)
}
+125
View File
@@ -0,0 +1,125 @@
//
// FormElement.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* A HTML Form Element provides ready access to the form fields/controls that are associated with it. It also allows a
* form to easily be submitted.
*/
public class FormElement: Element {
private let _elements: Elements = Elements()
/**
* Create a new, standalone form element.
*
* @param tag tag of this element
* @param baseUri the base URI
* @param attributes initial attributes
*/
public override init(_ tag: Tag, _ baseUri: String, _ attributes: Attributes) {
super.init(tag, baseUri, attributes)
}
/**
* Get the list of form control elements associated with this form.
* @return form controls associated with this element.
*/
public func elements() -> Elements {
return _elements
}
/**
* Add a form control element to this form.
* @param element form control to add
* @return this form element, for chaining
*/
@discardableResult
public func addElement(_ element: Element) -> FormElement {
_elements.add(element)
return self
}
//todo:
/**
* Prepare to submit this form. A Connection object is created with the request set up from the form values. You
* can then set up other options (like user-agent, timeout, cookies), then execute it.
* @return a connection prepared from the values of this form.
* @throws IllegalArgumentException if the form's absolute action URL cannot be determined. Make sure you pass the
* document's base URI when parsing.
*/
// public func submit()throws->Connection {
// let action: String = hasAttr("action") ? try absUrl("action") : try baseUri()
// Validate.notEmpty(action, "Could not determine a form action URL for submit. Ensure you set a base URI when parsing.")
// Connection.Method method = attr("method").toUpperCase().equals("POST") ?
// Connection.Method.POST : Connection.Method.GET
//
// return Jsoup.connect(action)
// .data(formData())
// .method(method)
// }
//todo:
/**
* Get the data that this form submits. The returned list is a copy of the data, and changes to the contents of the
* list will not be reflected in the DOM.
* @return a list of key vals
*/
// public List<Connection.KeyVal> formData() {
// ArrayList<Connection.KeyVal> data = new ArrayList<Connection.KeyVal>();
//
// // iterate the form control elements and accumulate their values
// for (Element el: elements) {
// if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable
// if (el.hasAttr("disabled")) continue; // skip disabled form inputs
// String name = el.attr("name");
// if (name.length() == 0) continue;
// String type = el.attr("type");
//
// if ("select".equals(el.tagName())) {
// Elements options = el.select("option[selected]");
// boolean set = false;
// for (Element option: options) {
// data.add(HttpConnection.KeyVal.create(name, option.val()));
// set = true;
// }
// if (!set) {
// Element option = el.select("option").first();
// if (option != null)
// data.add(HttpConnection.KeyVal.create(name, option.val()));
// }
// } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) {
// // only add checkbox or radio if they have the checked attribute
// if (el.hasAttr("checked")) {
// final String val = el.val().length() > 0 ? el.val() : "on";
// data.add(HttpConnection.KeyVal.create(name, val));
// }
// } else {
// data.add(HttpConnection.KeyVal.create(name, el.val()));
// }
// }
// return data;
// }
public override func copy(with zone: NSZone? = nil) -> Any {
let clone = FormElement(_tag, baseUri!, attributes!)
return copy(clone: clone)
}
public override func copy(parent: Node?) -> Node {
let clone = FormElement(_tag, baseUri!, attributes!)
return copy(clone: clone, parent: parent)
}
public override func copy(clone: Node, parent: Node?) -> Node {
let clone = clone as! FormElement
for att in _elements.array() {
clone._elements.add(att)
}
return super.copy(clone: clone, parent: parent)
}
}
+771
View File
@@ -0,0 +1,771 @@
//
// HtmlTreeBuilder.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 24/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* HTML Tree Builder; creates a DOM from Tokens.
*/
class HtmlTreeBuilder: TreeBuilder {
// tag searches
public static let TagsSearchInScope: [String] = ["applet", "caption", "html", "table", "td", "th", "marquee", "object"]
private static let TagSearchList: [String] = ["ol", "ul"]
private static let TagSearchButton: [String] = ["button"]
private static let TagSearchTableScope: [String] = ["html", "table"]
private static let TagSearchSelectScope: [String] = ["optgroup", "option"]
private static let TagSearchEndTags: [String] = ["dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"]
private static let TagSearchSpecial: [String] = ["address", "applet", "area", "article", "aside", "base", "basefont", "bgsound",
"blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "command", "dd",
"details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form",
"frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html",
"iframe", "img", "input", "isindex", "li", "link", "listing", "marquee", "menu", "meta", "nav",
"noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script",
"section", "select", "style", "summary", "table", "tbody", "td", "textarea", "tfoot", "th", "thead",
"title", "tr", "ul", "wbr", "xmp"]
private var _state: HtmlTreeBuilderState = HtmlTreeBuilderState.Initial // the current state
private var _originalState: HtmlTreeBuilderState = HtmlTreeBuilderState.Initial // original / marked state
private var baseUriSetFromDoc: Bool = false
private var headElement: Element? // the current head element
private var formElement: FormElement? // the current form element
private var contextElement: Element? // fragment parse context -- could be null even if fragment parsing
private var formattingElements: Array<Element?> = Array<Element?>() // active (open) formatting elements
private var pendingTableCharacters: Array<String> = Array<String>() // chars in table to be shifted out
private var emptyEnd: Token.EndTag = Token.EndTag() // reused empty end tag
private var _framesetOk: Bool = true // if ok to go into frameset
private var fosterInserts: Bool = false // if next inserts should be fostered
private var fragmentParsing: Bool = false // if parsing a fragment of html
public override init() {
super.init()
}
public override func defaultSettings() -> ParseSettings {
return ParseSettings.htmlDefault
}
override func parse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Document {
_state = HtmlTreeBuilderState.Initial
baseUriSetFromDoc = false
return try super.parse(input, baseUri, errors, settings)
}
func parseFragment(_ inputFragment: String, _ context: Element?, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Array<Node> {
// context may be null
_state = HtmlTreeBuilderState.Initial
initialiseParse(inputFragment, baseUri, errors, settings)
contextElement = context
fragmentParsing = true
var root: Element? = nil
if let context = context {
if let d = context.ownerDocument() { // quirks setup:
doc.quirksMode(d.quirksMode())
}
// initialise the tokeniser state:
let contextTag: String = context.tagName()
if (StringUtil.inString(contextTag, haystack: "title", "textarea")) {
tokeniser.transition(TokeniserState.Rcdata)
} else if (StringUtil.inString(contextTag, haystack: "iframe", "noembed", "noframes", "style", "xmp")) {
tokeniser.transition(TokeniserState.Rawtext)
} else if (contextTag=="script") {
tokeniser.transition(TokeniserState.ScriptData)
} else if (contextTag==("noscript")) {
tokeniser.transition(TokeniserState.Data) // if scripting enabled, rawtext
} else if (contextTag=="plaintext") {
tokeniser.transition(TokeniserState.Data)
} else {
tokeniser.transition(TokeniserState.Data) // default
}
root = try Element(Tag.valueOf("html", settings), baseUri)
try Validate.notNull(obj: root)
try doc.appendChild(root!)
stack.append(root!)
resetInsertionMode()
// setup form element to nearest form on context (up ancestor chain). ensures form controls are associated
// with form correctly
let contextChain: Elements = context.parents()
contextChain.add(0, context)
for parent: Element in contextChain.array() {
if let x = (parent as? FormElement) {
formElement = x
break
}
}
}
try runParser()
if (context != nil && root != nil) {
return root!.getChildNodes()
} else {
return doc.getChildNodes()
}
}
@discardableResult
public override func process(_ token: Token)throws->Bool {
currentToken = token
return try self._state.process(token, self)
}
@discardableResult
func process(_ token: Token, _ state: HtmlTreeBuilderState)throws->Bool {
currentToken = token
return try state.process(token, self)
}
func transition(_ state: HtmlTreeBuilderState) {
self._state = state
}
func state() -> HtmlTreeBuilderState {
return _state
}
func markInsertionMode() {
_originalState = _state
}
func originalState() -> HtmlTreeBuilderState {
return _originalState
}
func framesetOk(_ framesetOk: Bool) {
self._framesetOk = framesetOk
}
func framesetOk() -> Bool {
return _framesetOk
}
func getDocument() -> Document {
return doc
}
func getBaseUri() -> String {
return baseUri
}
func maybeSetBaseUri(_ base: Element)throws {
if (baseUriSetFromDoc) { // only listen to the first <base href> in parse
return
}
let href: String = try base.absUrl("href")
if (href.count != 0) { // ignore <base target> etc
baseUri = href
baseUriSetFromDoc = true
try doc.setBaseUri(href) // set on the doc so doc.createElement(Tag) will get updated base, and to update all descendants
}
}
func isFragmentParsing() -> Bool {
return fragmentParsing
}
func error(_ state: HtmlTreeBuilderState) {
if (errors.canAddError() && currentToken != nil) {
errors.add(ParseError(reader.getPos(), "Unexpected token [\(currentToken!.tokenType())] when in state [\(state.rawValue)]"))
}
}
@discardableResult
func insert(_ startTag: Token.StartTag)throws->Element {
// handle empty unknown tags
// when the spec expects an empty tag, will directly hit insertEmpty, so won't generate this fake end tag.
if (startTag.isSelfClosing()) {
let el: Element = try insertEmpty(startTag)
stack.append(el)
tokeniser.transition(TokeniserState.Data) // handles <script />, otherwise needs breakout steps from script data
try tokeniser.emit(emptyEnd.reset().name(el.tagName())) // ensure we get out of whatever state we are in. emitted for yielded processing
return el
}
try Validate.notNull(obj: startTag._attributes)
let el: Element = try Element(Tag.valueOf(startTag.name(), settings), baseUri, settings.normalizeAttributes(startTag._attributes))
try insert(el)
return el
}
@discardableResult
func insertStartTag(_ startTagName: String)throws->Element {
let el: Element = try Element(Tag.valueOf(startTagName, settings), baseUri)
try insert(el)
return el
}
func insert(_ el: Element)throws {
try insertNode(el)
stack.append(el)
}
@discardableResult
func insertEmpty(_ startTag: Token.StartTag)throws->Element {
let tag: Tag = try Tag.valueOf(startTag.name(), settings)
try Validate.notNull(obj: startTag._attributes)
let el: Element = Element(tag, baseUri, startTag._attributes)
try insertNode(el)
if (startTag.isSelfClosing()) {
if (tag.isKnownTag()) {
if (tag.isSelfClosing()) {tokeniser.acknowledgeSelfClosingFlag()} // if not acked, promulagates error
} else {
// unknown tag, remember this is self closing for output
tag.setSelfClosing()
tokeniser.acknowledgeSelfClosingFlag() // not an distinct error
}
}
return el
}
@discardableResult
func insertForm(_ startTag: Token.StartTag, _ onStack: Bool)throws->FormElement {
let tag: Tag = try Tag.valueOf(startTag.name(), settings)
try Validate.notNull(obj: startTag._attributes)
let el: FormElement = FormElement(tag, baseUri, startTag._attributes)
setFormElement(el)
try insertNode(el)
if (onStack) {
stack.append(el)
}
return el
}
func insert(_ commentToken: Token.Comment)throws {
let comment: Comment = Comment(commentToken.getData(), baseUri)
try insertNode(comment)
}
func insert(_ characterToken: Token.Char)throws {
var node: Node
// characters in script and style go in as datanodes, not text nodes
let tagName: String? = currentElement()?.tagName()
if (tagName=="script" || tagName=="style") {
try Validate.notNull(obj: characterToken.getData())
node = DataNode(characterToken.getData()!, baseUri)
} else {
try Validate.notNull(obj: characterToken.getData())
node = TextNode(characterToken.getData()!, baseUri)
}
try currentElement()?.appendChild(node) // doesn't use insertNode, because we don't foster these; and will always have a stack.
}
private func insertNode(_ node: Node)throws {
// if the stack hasn't been set up yet, elements (doctype, comments) go into the doc
if (stack.count == 0) {
try doc.appendChild(node)
} else if (isFosterInserts()) {
try insertInFosterParent(node)
} else {
try currentElement()?.appendChild(node)
}
// connect form controls to their form element
if let n = (node as? Element) {
if(n.tag().isFormListed()) {
if ( formElement != nil) {
formElement!.addElement(n)
}
}
}
}
@discardableResult
func pop() -> Element {
let size: Int = stack.count
return stack.remove(at: size-1)
}
func push(_ element: Element) {
stack.append(element)
}
func getStack()->Array<Element> {
return stack
}
@discardableResult
func onStack(_ el: Element) -> Bool {
return isElementInQueue(stack, el)
}
private func isElementInQueue(_ queue: Array<Element?>, _ element: Element?) -> Bool {
for pos in (0..<queue.count).reversed() {
let next: Element? = queue[pos]
if (next == element) {
return true
}
}
return false
}
func getFromStack(_ elName: String) -> Element? {
for pos in (0..<stack.count).reversed() {
let next: Element = stack[pos]
if next.nodeName() == elName {
return next
}
}
return nil
}
@discardableResult
func removeFromStack(_ el: Element) -> Bool {
for pos in (0..<stack.count).reversed() {
let next: Element = stack[pos]
if (next == el) {
stack.remove(at: pos)
return true
}
}
return false
}
func popStackToClose(_ elName: String) {
for pos in (0..<stack.count).reversed() {
let next: Element = stack[pos]
stack.remove(at: pos)
if (next.nodeName() == elName) {
break
}
}
}
func popStackToClose(_ elNames: String...) {
popStackToClose(elNames)
}
func popStackToClose(_ elNames: [String]) {
for pos in (0..<stack.count).reversed() {
let next: Element = stack[pos]
stack.remove(at: pos)
if (StringUtil.inString(next.nodeName(), elNames)) {
break
}
}
}
func popStackToBefore(_ elName: String) {
for pos in (0..<stack.count).reversed() {
let next: Element = stack[pos]
if (next.nodeName() == elName) {
break
} else {
stack.remove(at: pos)
}
}
}
func clearStackToTableContext() {
clearStackToContext("table")
}
func clearStackToTableBodyContext() {
clearStackToContext("tbody", "tfoot", "thead")
}
func clearStackToTableRowContext() {
clearStackToContext("tr")
}
private func clearStackToContext(_ nodeNames: String...) {
clearStackToContext(nodeNames)
}
private func clearStackToContext(_ nodeNames: [String]) {
for pos in (0..<stack.count).reversed() {
let next: Element = stack[pos]
if (StringUtil.inString(next.nodeName(), nodeNames) || next.nodeName()=="html") {
break
} else {
stack.remove(at: pos)
}
}
}
func aboveOnStack(_ el: Element) -> Element? {
//assert(onStack(el), "Invalid parameter")
onStack(el)
for pos in (0..<stack.count).reversed() {
let next: Element = stack[pos]
if (next == el) {
return stack[pos-1]
}
}
return nil
}
func insertOnStackAfter(_ after: Element, _ input: Element)throws {
let i: Int = stack.lastIndexOf(after)
try Validate.isTrue(val: i != -1)
stack.insert(input, at: i + 1 )
}
func replaceOnStack(_ out: Element, _ input: Element)throws {
try stack = replaceInQueue(stack, out, input)
}
private func replaceInQueue(_ queue: Array<Element>, _ out: Element, _ input: Element)throws->Array<Element> {
var queue = queue
let i: Int = queue.lastIndexOf(out)
try Validate.isTrue(val: i != -1)
queue[i] = input
return queue
}
private func replaceInQueue(_ queue: Array<Element?>, _ out: Element, _ input: Element)throws->Array<Element?> {
var queue = queue
var i: Int = -1
for index in 0..<queue.count {
if(out == queue[index]) {
i = index
}
}
try Validate.isTrue(val: i != -1)
queue[i] = input
return queue
}
func resetInsertionMode() {
var last = false
for pos in (0..<stack.count).reversed() {
var node: Element = stack[pos]
if (pos == 0) {
last = true
//Validate node
node = contextElement!
}
let name: String = node.nodeName()
if ("select".equals(name)) {
transition(HtmlTreeBuilderState.InSelect)
break // frag
} else if (("td".equals(name) || "th".equals(name) && !last)) {
transition(HtmlTreeBuilderState.InCell)
break
} else if ("tr".equals(name)) {
transition(HtmlTreeBuilderState.InRow)
break
} else if ("tbody".equals(name) || "thead".equals(name) || "tfoot".equals(name)) {
transition(HtmlTreeBuilderState.InTableBody)
break
} else if ("caption".equals(name)) {
transition(HtmlTreeBuilderState.InCaption)
break
} else if ("colgroup".equals(name)) {
transition(HtmlTreeBuilderState.InColumnGroup)
break // frag
} else if ("table".equals(name)) {
transition(HtmlTreeBuilderState.InTable)
break
} else if ("head".equals(name)) {
transition(HtmlTreeBuilderState.InBody)
break // frag
} else if ("body".equals(name)) {
transition(HtmlTreeBuilderState.InBody)
break
} else if ("frameset".equals(name)) {
transition(HtmlTreeBuilderState.InFrameset)
break // frag
} else if ("html".equals(name)) {
transition(HtmlTreeBuilderState.BeforeHead)
break // frag
} else if (last) {
transition(HtmlTreeBuilderState.InBody)
break // frag
}
}
}
// todo: tidy up in specific scope methods
private var specificScopeTarget: [String?] = [nil]
private func inSpecificScope(_ targetName: String, _ baseTypes: [String], _ extraTypes: [String]?)throws->Bool {
specificScopeTarget[0] = targetName
return try inSpecificScope(specificScopeTarget, baseTypes, extraTypes)
}
private func inSpecificScope(_ targetNames: [String?], _ baseTypes: [String], _ extraTypes: [String]?)throws->Bool {
for pos in (0..<stack.count).reversed() {
let el: Element = stack[pos]
let elName: String = el.nodeName()
if (StringUtil.inString(elName, targetNames)) {
return true
}
if (StringUtil.inString(elName, baseTypes)) {
return false
}
if (extraTypes != nil && StringUtil.inString(elName, extraTypes!)) {
return false
}
}
try Validate.fail(msg: "Should not be reachable")
return false
}
func inScope(_ targetNames: [String])throws->Bool {
return try inSpecificScope(targetNames, HtmlTreeBuilder.TagsSearchInScope, nil)
}
func inScope(_ targetName: String)throws->Bool {
return try inScope(targetName, nil)
}
func inScope(_ targetName: String, _ extras: [String]?)throws->Bool {
return try inSpecificScope(targetName, HtmlTreeBuilder.TagsSearchInScope, extras)
// todo: in mathml namespace: mi, mo, mn, ms, mtext annotation-xml
// todo: in svg namespace: forignOjbect, desc, title
}
func inListItemScope(_ targetName: String)throws->Bool {
return try inScope(targetName, HtmlTreeBuilder.TagSearchList)
}
func inButtonScope(_ targetName: String)throws->Bool {
return try inScope(targetName, HtmlTreeBuilder.TagSearchButton)
}
func inTableScope(_ targetName: String)throws->Bool {
return try inSpecificScope(targetName, HtmlTreeBuilder.TagSearchTableScope, nil)
}
func inSelectScope(_ targetName: String)throws->Bool {
for pos in (0..<stack.count).reversed() {
let el: Element = stack[pos]
let elName: String = el.nodeName()
if (elName.equals(targetName)) {
return true
}
if (!StringUtil.inString(elName, HtmlTreeBuilder.TagSearchSelectScope)) { // all elements except
return false
}
}
try Validate.fail(msg: "Should not be reachable")
return false
}
func setHeadElement(_ headElement: Element) {
self.headElement = headElement
}
func getHeadElement() -> Element? {
return headElement
}
func isFosterInserts() -> Bool {
return fosterInserts
}
func setFosterInserts(_ fosterInserts: Bool) {
self.fosterInserts = fosterInserts
}
func getFormElement() -> FormElement? {
return formElement
}
func setFormElement(_ formElement: FormElement?) {
self.formElement = formElement
}
func newPendingTableCharacters() {
pendingTableCharacters = Array<String>()
}
func getPendingTableCharacters()->Array<String> {
return pendingTableCharacters
}
func setPendingTableCharacters(_ pendingTableCharacters: Array<String>) {
self.pendingTableCharacters = pendingTableCharacters
}
/**
11.2.5.2 Closing elements that have implied end tags<p/>
When the steps below require the UA to generate implied end tags, then, while the current node is a dd element, a
dt element, an li element, an option element, an optgroup element, a p element, an rp element, or an rt element,
the UA must pop the current node off the stack of open elements.
@param excludeTag If a step requires the UA to generate implied end tags but lists an element to exclude from the
process, then the UA must perform the above steps as if that element was not in the above list.
*/
func generateImpliedEndTags(_ excludeTag: String?) {
while ((excludeTag != nil && !currentElement()!.nodeName().equals(excludeTag!)) &&
StringUtil.inString(currentElement()!.nodeName(), HtmlTreeBuilder.TagSearchEndTags)) {
pop()
}
}
func generateImpliedEndTags() {
generateImpliedEndTags(nil)
}
func isSpecial(_ el: Element) -> Bool {
// todo: mathml's mi, mo, mn
// todo: svg's foreigObject, desc, title
let name: String = el.nodeName()
return StringUtil.inString(name, HtmlTreeBuilder.TagSearchSpecial)
}
func lastFormattingElement() -> Element? {
return formattingElements.count > 0 ? formattingElements[formattingElements.count-1] : nil
}
func removeLastFormattingElement() -> Element? {
let size: Int = formattingElements.count
if (size > 0) {
return formattingElements.remove(at: size-1)
} else {
return nil
}
}
// active formatting elements
func pushActiveFormattingElements(_ input: Element) {
var numSeen: Int = 0
for pos in (0..<formattingElements.count).reversed() {
let el: Element? = formattingElements[pos]
if (el == nil) { // marker
break
}
if (isSameFormattingElement(input, el!)) {
numSeen += 1
}
if (numSeen == 3) {
formattingElements.remove(at: pos)
break
}
}
formattingElements.append(input)
}
private func isSameFormattingElement(_ a: Element, _ b: Element) -> Bool {
// same if: same namespace, tag, and attributes. Element.equals only checks tag, might in future check children
if(a.attributes == nil) {
return false
}
return a.nodeName().equals(b.nodeName()) &&
// a.namespace().equals(b.namespace()) &&
a.getAttributes()!.equals(o: b.getAttributes())
// todo: namespaces
}
func reconstructFormattingElements()throws {
let last: Element? = lastFormattingElement()
if (last == nil || onStack(last!)) {
return
}
var entry: Element? = last
let size: Int = formattingElements.count
var pos: Int = size - 1
var skip: Bool = false
while (true) {
if (pos == 0) { // step 4. if none before, skip to 8
skip = true
break
}
pos -= 1
entry = formattingElements[pos] // step 5. one earlier than entry
if (entry == nil || onStack(entry!)) // step 6 - neither marker nor on stack
{break} // jump to 8, else continue back to 4
}
while(true) {
if (!skip) // step 7: on later than entry
{
pos += 1
entry = formattingElements[pos]
}
try Validate.notNull(obj: entry) // should not occur, as we break at last element
// 8. create new element from element, 9 insert into current node, onto stack
skip = false // can only skip increment from 4.
let newEl: Element = try insertStartTag(entry!.nodeName()) // todo: avoid fostering here?
// newEl.namespace(entry.namespace()) // todo: namespaces
newEl.getAttributes()?.addAll(incoming: entry!.getAttributes())
// 10. replace entry with new entry
formattingElements[pos] = newEl
// 11
if (pos == size-1) // if not last entry in list, jump to 7
{break}
}
}
func clearFormattingElementsToLastMarker() {
while (!formattingElements.isEmpty) {
let el: Element? = removeLastFormattingElement()
if (el == nil) {
break
}
}
}
func removeFromActiveFormattingElements(_ el: Element?) {
for pos in (0..<formattingElements.count).reversed() {
let next: Element? = formattingElements[pos]
if (next == el) {
formattingElements.remove(at: pos)
break
}
}
}
func isInActiveFormattingElements(_ el: Element) -> Bool {
return isElementInQueue(formattingElements, el)
}
func getActiveFormattingElement(_ nodeName: String) -> Element? {
for pos in (0..<formattingElements.count).reversed() {
let next: Element? = formattingElements[pos]
if (next == nil) { // scope marker
break
} else if (next!.nodeName().equals(nodeName)) {
return next
}
}
return nil
}
func replaceActiveFormattingElement(_ out: Element, _ input: Element)throws {
try formattingElements = replaceInQueue(formattingElements, out, input)
}
func insertMarkerToFormattingElements() {
formattingElements.append(nil)
}
func insertInFosterParent(_ input: Node)throws {
let fosterParent: Element?
let lastTable: Element? = getFromStack("table")
var isLastTableParent: Bool = false
if let lastTable = lastTable {
if (lastTable.parent() != nil) {
fosterParent = lastTable.parent()!
isLastTableParent = true
} else {
fosterParent = aboveOnStack(lastTable)
}
} else { // no table == frag
fosterParent = stack[0]
}
if (isLastTableParent) {
try Validate.notNull(obj: lastTable) // last table cannot be null by this point.
try lastTable!.before(input)
} else {
try fosterParent?.appendChild(input)
}
}
}
File diff suppressed because it is too large Load Diff
+10
View File
@@ -0,0 +1,10 @@
//
// HttpStatusException.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
//TODO:
+802
View File
@@ -0,0 +1,802 @@
//
// Node.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class Node: Equatable, Hashable {
private static let abs = "abs:"
fileprivate static let empty = ""
private static let EMPTY_NODES: Array<Node> = Array<Node>()
weak var parentNode: Node?
var childNodes: Array <Node>
var attributes: Attributes?
var baseUri: String?
/**
* Get the list index of this node in its node sibling list. I.e. if this is the first node
* sibling, returns 0.
* @return position in node sibling list
* @see org.jsoup.nodes.Element#elementSiblingIndex()
*/
public private(set) var siblingIndex: Int = 0
/**
Create a new Node.
@param baseUri base URI
@param attributes attributes (not null, but may be empty)
*/
public init(_ baseUri: String, _ attributes: Attributes) {
self.childNodes = Node.EMPTY_NODES
self.baseUri = baseUri.trim()
self.attributes = attributes
}
public init(_ baseUri: String) {
childNodes = Node.EMPTY_NODES
self.baseUri = baseUri.trim()
self.attributes = Attributes()
}
/**
* Default constructor. Doesn't setup base uri, children, or attributes; use with caution.
*/
public init() {
self.childNodes = Node.EMPTY_NODES
self.attributes = nil
self.baseUri = nil
}
/**
Get the node name of this node. Use for debugging purposes and not logic switching (for that, use instanceof).
@return node name
*/
public func nodeName() -> String {
preconditionFailure("This method must be overridden")
}
/**
* Get an attribute's value by its key. <b>Case insensitive</b>
* <p>
* To get an absolute URL from an attribute that may be a relative URL, prefix the key with <code><b>abs</b></code>,
* which is a shortcut to the {@link #absUrl} method.
* </p>
* E.g.:
* <blockquote><code>String url = a.attr("abs:href");</code></blockquote>
*
* @param attributeKey The attribute key.
* @return The attribute, or empty string if not present (to avoid nulls).
* @see #attributes()
* @see #hasAttr(String)
* @see #absUrl(String)
*/
open func attr(_ attributeKey: String)throws ->String {
let val: String = try attributes!.getIgnoreCase(key: attributeKey)
if (val.count > 0) {
return val
} else if (attributeKey.lowercased().startsWith(Node.abs)) {
return try absUrl(attributeKey.substring(Node.abs.count))
} else {return Node.empty}
}
/**
* Get all of the element's attributes.
* @return attributes (which implements iterable, in same order as presented in original HTML).
*/
open func getAttributes() -> Attributes? {
return attributes
}
/**
* Set an attribute (key=value). If the attribute already exists, it is replaced.
* @param attributeKey The attribute key.
* @param attributeValue The attribute value.
* @return this (for chaining)
*/
@discardableResult
open func attr(_ attributeKey: String, _ attributeValue: String)throws->Node {
try attributes?.put(attributeKey, attributeValue)
return self
}
/**
* Test if this element has an attribute. <b>Case insensitive</b>
* @param attributeKey The attribute key to check.
* @return true if the attribute exists, false if not.
*/
open func hasAttr(_ attributeKey: String) -> Bool {
guard let attributes = attributes else {
return false
}
if (attributeKey.startsWith(Node.abs)) {
let key: String = attributeKey.substring(Node.abs.count)
do {
let abs = try absUrl(key)
if (attributes.hasKeyIgnoreCase(key: key) && !Node.empty.equals(abs)) {
return true
}
} catch {
return false
}
}
return attributes.hasKeyIgnoreCase(key: attributeKey)
}
/**
* Remove an attribute from this element.
* @param attributeKey The attribute to remove.
* @return this (for chaining)
*/
@discardableResult
open func removeAttr(_ attributeKey: String)throws->Node {
try attributes?.removeIgnoreCase(key: attributeKey)
return self
}
/**
Get the base URI of this node.
@return base URI
*/
open func getBaseUri() -> String {
return baseUri!
}
/**
Update the base URI of this node and all of its descendants.
@param baseUri base URI to set
*/
open func setBaseUri(_ baseUri: String)throws {
class nodeVisitor: NodeVisitor {
private let baseUri: String
init(_ baseUri: String) {
self.baseUri = baseUri
}
func head(_ node: Node, _ depth: Int)throws {
node.baseUri = baseUri
}
func tail(_ node: Node, _ depth: Int)throws {
}
}
try traverse(nodeVisitor(baseUri))
}
/**
* Get an absolute URL from a URL attribute that may be relative (i.e. an <code>&lta href&gt;</code> or
* <code>&lt;img src&gt;</code>).
* <p>
* E.g.: <code>String absUrl = linkEl.absUrl("href");</code>
* </p>
* <p>
* If the attribute value is already absolute (i.e. it starts with a protocol, like
* <code>http://</code> or <code>https://</code> etc), and it successfully parses as a URL, the attribute is
* returned directly. Otherwise, it is treated as a URL relative to the element's {@link #baseUri}, and made
* absolute using that.
* </p>
* <p>
* As an alternate, you can use the {@link #attr} method with the <code>abs:</code> prefix, e.g.:
* <code>String absUrl = linkEl.attr("abs:href");</code>
* </p>
*
* @param attributeKey The attribute key
* @return An absolute URL if one could be made, or an empty string (not null) if the attribute was missing or
* could not be made successfully into a URL.
* @see #attr
* @see java.net.URL#URL(java.net.URL, String)
*/
open func absUrl(_ attributeKey: String)throws->String {
try Validate.notEmpty(string: attributeKey)
if (!hasAttr(attributeKey)) {
return Node.empty // nothing to make absolute with
} else {
return StringUtil.resolve(baseUri!, relUrl: try attr(attributeKey))
}
}
/**
Get a child node by its 0-based index.
@param index index of child node
@return the child node at this index. Throws a {@code IndexOutOfBoundsException} if the index is out of bounds.
*/
open func childNode(_ index: Int) -> Node {
return childNodes[index]
}
/**
Get this node's children. Presented as an unmodifiable list: new children can not be added, but the child nodes
themselves can be manipulated.
@return list of children. If no children, returns an empty list.
*/
open func getChildNodes()->Array<Node> {
return childNodes
}
/**
* Returns a deep copy of this node's children. Changes made to these nodes will not be reflected in the original
* nodes
* @return a deep copy of this node's children
*/
open func childNodesCopy()->Array<Node> {
var children: Array<Node> = Array<Node>()
for node: Node in childNodes {
children.append(node.copy() as! Node)
}
return children
}
/**
* Get the number of child nodes that this node holds.
* @return the number of child nodes that this node holds.
*/
public func childNodeSize() -> Int {
return childNodes.count
}
final func childNodesAsArray() -> [Node] {
return childNodes as Array
}
/**
Gets this node's parent node.
@return parent node or null if no parent.
*/
open func parent() -> Node? {
return parentNode
}
/**
Gets this node's parent node. Node overridable by extending classes, so useful if you really just need the Node type.
@return parent node or null if no parent.
*/
final func getParentNode() -> Node? {
return parentNode
}
/**
* Gets the Document associated with this Node.
* @return the Document associated with this Node, or null if there is no such Document.
*/
open func ownerDocument() -> Document? {
if let this = self as? Document {
return this
} else if (parentNode == nil) {
return nil
} else {
return parentNode!.ownerDocument()
}
}
/**
* Remove (delete) this node from the DOM tree. If this node has children, they are also removed.
*/
open func remove()throws {
try parentNode?.removeChild(self)
}
/**
* Insert the specified HTML into the DOM before this node (i.e. as a preceding sibling).
* @param html HTML to add before this node
* @return this node, for chaining
* @see #after(String)
*/
@discardableResult
open func before(_ html: String)throws->Node {
try addSiblingHtml(siblingIndex, html)
return self
}
/**
* Insert the specified node into the DOM before this node (i.e. as a preceding sibling).
* @param node to add before this node
* @return this node, for chaining
* @see #after(Node)
*/
@discardableResult
open func before(_ node: Node)throws ->Node {
try Validate.notNull(obj: node)
try Validate.notNull(obj: parentNode)
try parentNode?.addChildren(siblingIndex, node)
return self
}
/**
* Insert the specified HTML into the DOM after this node (i.e. as a following sibling).
* @param html HTML to add after this node
* @return this node, for chaining
* @see #before(String)
*/
@discardableResult
open func after(_ html: String)throws ->Node {
try addSiblingHtml(siblingIndex + 1, html)
return self
}
/**
* Insert the specified node into the DOM after this node (i.e. as a following sibling).
* @param node to add after this node
* @return this node, for chaining
* @see #before(Node)
*/
@discardableResult
open func after(_ node: Node)throws->Node {
try Validate.notNull(obj: node)
try Validate.notNull(obj: parentNode)
try parentNode?.addChildren(siblingIndex+1, node)
return self
}
private func addSiblingHtml(_ index: Int, _ html: String)throws {
try Validate.notNull(obj: parentNode)
let context: Element? = parent() as? Element
let nodes: Array<Node> = try Parser.parseFragment(html, context, getBaseUri())
try parentNode?.addChildren(index, nodes)
}
/**
* Insert the specified HTML into the DOM after this node (i.e. as a following sibling).
* @param html HTML to add after this node
* @return this node, for chaining
* @see #before(String)
*/
@discardableResult
open func after(html: String)throws->Node {
try addSiblingHtml(siblingIndex + 1, html)
return self
}
/**
* Insert the specified node into the DOM after this node (i.e. as a following sibling).
* @param node to add after this node
* @return this node, for chaining
* @see #before(Node)
*/
@discardableResult
open func after(node: Node)throws->Node {
try Validate.notNull(obj: node)
try Validate.notNull(obj: parentNode)
try parentNode?.addChildren(siblingIndex + 1, node)
return self
}
open func addSiblingHtml(index: Int, _ html: String)throws {
try Validate.notNull(obj: html)
try Validate.notNull(obj: parentNode)
let context: Element? = parent() as? Element
let nodes: Array<Node> = try Parser.parseFragment(html, context, getBaseUri())
try parentNode?.addChildren(index, nodes)
}
/**
Wrap the supplied HTML around this node.
@param html HTML to wrap around this element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
@return this node, for chaining.
*/
@discardableResult
open func wrap(_ html: String)throws->Node? {
try Validate.notEmpty(string: html)
let context: Element? = parent() as? Element
var wrapChildren: Array<Node> = try Parser.parseFragment(html, context, getBaseUri())
let wrapNode: Node? = wrapChildren.count > 0 ? wrapChildren[0] : nil
if (wrapNode == nil || !(((wrapNode as? Element) != nil))) { // nothing to wrap with; noop
return nil
}
let wrap: Element = wrapNode as! Element
let deepest: Element = getDeepChild(el: wrap)
try parentNode?.replaceChild(self, wrap)
wrapChildren = wrapChildren.filter { $0 != wrap}
try deepest.addChildren(self)
// remainder (unbalanced wrap, like <div></div><p></p> -- The <p> is remainder
if (wrapChildren.count > 0) {
for i in 0..<wrapChildren.count {
let remainder: Node = wrapChildren[i]
try remainder.parentNode?.removeChild(remainder)
try wrap.appendChild(remainder)
}
}
return self
}
/**
* Removes this node from the DOM, and moves its children up into the node's parent. This has the effect of dropping
* the node but keeping its children.
* <p>
* For example, with the input html:
* </p>
* <p>{@code <div>One <span>Two <b>Three</b></span></div>}</p>
* Calling {@code element.unwrap()} on the {@code span} element will result in the html:
* <p>{@code <div>One Two <b>Three</b></div>}</p>
* and the {@code "Two "} {@link TextNode} being returned.
*
* @return the first child of this node, after the node has been unwrapped. Null if the node had no children.
* @see #remove()
* @see #wrap(String)
*/
@discardableResult
open func unwrap()throws ->Node? {
try Validate.notNull(obj: parentNode)
let firstChild: Node? = childNodes.count > 0 ? childNodes[0] : nil
try parentNode?.addChildren(siblingIndex, self.childNodesAsArray())
try self.remove()
return firstChild
}
private func getDeepChild(el: Element) -> Element {
let children = el.children()
if (children.size() > 0) {
return getDeepChild(el: children.get(0))
} else {
return el
}
}
/**
* Replace this node in the DOM with the supplied node.
* @param in the node that will will replace the existing node.
*/
public func replaceWith(_ input: Node)throws {
try Validate.notNull(obj: input)
try Validate.notNull(obj: parentNode)
try parentNode?.replaceChild(self, input)
}
public func setParentNode(_ parentNode: Node)throws {
if (self.parentNode != nil) {
try self.parentNode?.removeChild(self)
}
self.parentNode = parentNode
}
public func replaceChild(_ out: Node, _ input: Node)throws {
try Validate.isTrue(val: out.parentNode === self)
try Validate.notNull(obj: input)
if (input.parentNode != nil) {
try input.parentNode?.removeChild(input)
}
let index: Int = out.siblingIndex
childNodes[index] = input
input.parentNode = self
input.setSiblingIndex(index)
out.parentNode = nil
}
public func removeChild(_ out: Node)throws {
try Validate.isTrue(val: out.parentNode === self)
let index: Int = out.siblingIndex
childNodes.remove(at: index)
reindexChildren(index)
out.parentNode = nil
}
public func addChildren(_ children: Node...)throws {
//most used. short circuit addChildren(int), which hits reindex children and array copy
try addChildren(children)
}
public func addChildren(_ children: [Node])throws {
//most used. short circuit addChildren(int), which hits reindex children and array copy
for child in children {
try reparentChild(child)
ensureChildNodes()
childNodes.append(child)
child.setSiblingIndex(childNodes.count-1)
}
}
public func addChildren(_ index: Int, _ children: Node...)throws {
try addChildren(index, children)
}
public func addChildren(_ index: Int, _ children: [Node])throws {
ensureChildNodes()
for i in (0..<children.count).reversed() {
let input: Node = children[i]
try reparentChild(input)
childNodes.insert(input, at: index)
reindexChildren(index)
}
}
public func ensureChildNodes() {
// if (childNodes === Node.EMPTY_NODES) {
// childNodes = Array<Node>()
// }
}
public func reparentChild(_ child: Node)throws {
if (child.parentNode != nil) {
try child.parentNode?.removeChild(child)
}
try child.setParentNode(self)
}
private func reindexChildren(_ start: Int) {
for i in start..<childNodes.count {
childNodes[i].setSiblingIndex(i)
}
}
/**
Retrieves this node's sibling nodes. Similar to {@link #childNodes() node.parent.childNodes()}, but does not
include this node (a node is not a sibling of itself).
@return node siblings. If the node has no parent, returns an empty list.
*/
open func siblingNodes()->Array<Node> {
if (parentNode == nil) {
return Array<Node>()
}
let nodes: Array<Node> = parentNode!.childNodes
var siblings: Array<Node> = Array<Node>()
for node in nodes {
if (node !== self) {
siblings.append(node)
}
}
return siblings
}
/**
Get this node's next sibling.
@return next sibling, or null if this is the last sibling
*/
open func nextSibling() -> Node? {
guard let siblings: Array<Node> = parentNode?.childNodes else {
return nil
}
let index: Int = siblingIndex+1
if (siblings.count > index) {
return siblings[index]
} else {
return nil
}
}
/**
Get this node's previous sibling.
@return the previous sibling, or null if this is the first sibling
*/
open func previousSibling() -> Node? {
if (parentNode == nil) {
return nil // root
}
if (siblingIndex > 0) {
return parentNode?.childNodes[siblingIndex-1]
} else {
return nil
}
}
public func setSiblingIndex(_ siblingIndex: Int) {
self.siblingIndex = siblingIndex
}
/**
* Perform a depth-first traversal through this node and its descendants.
* @param nodeVisitor the visitor callbacks to perform on each node
* @return this node, for chaining
*/
@discardableResult
open func traverse(_ nodeVisitor: NodeVisitor)throws->Node {
let traversor: NodeTraversor = NodeTraversor(nodeVisitor)
try traversor.traverse(self)
return self
}
/**
Get the outer HTML of this node.
@return HTML
*/
open func outerHtml()throws->String {
let accum: StringBuilder = StringBuilder(128)
try outerHtml(accum)
return accum.toString()
}
public func outerHtml(_ accum: StringBuilder)throws {
try NodeTraversor(OuterHtmlVisitor(accum, getOutputSettings())).traverse(self)
}
// if this node has no document (or parent), retrieve the default output settings
func getOutputSettings() -> OutputSettings {
return ownerDocument() != nil ? ownerDocument()!.outputSettings() : (Document(Node.empty)).outputSettings()
}
/**
Get the outer HTML of this node.
@param accum accumulator to place HTML into
@throws IOException if appending to the given accumulator fails.
*/
func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) throws {
preconditionFailure("This method must be overridden")
}
func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) throws {
preconditionFailure("This method must be overridden")
}
/**
* Write this node and its children to the given {@link Appendable}.
*
* @param appendable the {@link Appendable} to write to.
* @return the supplied {@link Appendable}, for chaining.
*/
open func html(_ appendable: StringBuilder)throws -> StringBuilder {
try outerHtml(appendable)
return appendable
}
public func indent(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {
accum.append(UnicodeScalar.BackslashN).append(StringUtil.padding(depth * Int(out.indentAmount())))
}
/**
* Check if this node is the same instance of another (object identity test).
* @param o other object to compare to
* @return true if the content of this node is the same as the other
* @see Node#hasSameValue(Object) to compare nodes by their value
*/
open func equals(_ o: Node) -> Bool {
// implemented just so that javadoc is clear this is an identity test
return self === o
}
/**
* Check if this node is has the same content as another node. A node is considered the same if its name, attributes and content match the
* other node; particularly its position in the tree does not influence its similarity.
* @param o other object to compare to
* @return true if the content of this node is the same as the other
*/
open func hasSameValue(_ o: Node)throws->Bool {
if (self === o) {return true}
// if (type(of:self) != type(of: o))
// {
// return false
// }
return try self.outerHtml() == o.outerHtml()
}
/**
* Create a stand-alone, deep copy of this node, and all of its children. The cloned node will have no siblings or
* parent node. As a stand-alone object, any changes made to the clone or any of its children will not impact the
* original node.
* <p>
* The cloned node may be adopted into another Document or node structure using {@link Element#appendChild(Node)}.
* @return stand-alone cloned node
*/
public func copy(with zone: NSZone? = nil) -> Any {
return copy(clone: Node())
}
public func copy(parent: Node?) -> Node {
let clone = Node()
return copy(clone: clone, parent: parent)
}
public func copy(clone: Node) -> Node {
let thisClone: Node = copy(clone: clone, parent: nil) // splits for orphan
// Queue up nodes that need their children cloned (BFS).
var nodesToProcess: Array<Node> = Array<Node>()
nodesToProcess.append(thisClone)
while (!nodesToProcess.isEmpty) {
let currParent: Node = nodesToProcess.removeFirst()
for i in 0..<currParent.childNodes.count {
let childClone: Node = currParent.childNodes[i].copy(parent: currParent)
currParent.childNodes[i] = childClone
nodesToProcess.append(childClone)
}
}
return thisClone
}
/*
* Return a clone of the node using the given parent (which can be null).
* Not a deep copy of children.
*/
public func copy(clone: Node, parent: Node?) -> Node {
clone.parentNode = parent // can be null, to create an orphan split
clone.siblingIndex = parent == nil ? 0 : siblingIndex
clone.attributes = attributes != nil ? attributes?.clone() : nil
clone.baseUri = baseUri
clone.childNodes = Array<Node>()
for child in childNodes {
clone.childNodes.append(child)
}
return clone
}
private class OuterHtmlVisitor: NodeVisitor {
private var accum: StringBuilder
private var out: OutputSettings
static private let text = "#text"
init(_ accum: StringBuilder, _ out: OutputSettings) {
self.accum = accum
self.out = out
}
open func head(_ node: Node, _ depth: Int)throws {
try node.outerHtmlHead(accum, depth, out)
}
open func tail(_ node: Node, _ depth: Int)throws {
if (!(node.nodeName() == OuterHtmlVisitor.text)) { // saves a void hit.
try node.outerHtmlTail(accum, depth, out)
}
}
}
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: Node, rhs: Node) -> Bool {
return lhs === rhs
}
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
return description.hashValue ^ (baseUri?.hashValue ?? 31)
}
}
extension Node: CustomStringConvertible {
public var description: String {
do {
return try outerHtml()
} catch {
}
return Node.empty
}
}
extension Node: CustomDebugStringConvertible {
private static let space = " "
public var debugDescription: String {
do {
return try String(describing: type(of: self)) + Node.space + outerHtml()
} catch {
}
return String(describing: type(of: self))
}
}
+50
View File
@@ -0,0 +1,50 @@
//
// NodeTraversor.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 17/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
class NodeTraversor {
private let visitor: NodeVisitor
/**
* Create a new traversor.
* @param visitor a class implementing the {@link NodeVisitor} interface, to be called when visiting each node.
*/
public init(_ visitor: NodeVisitor) {
self.visitor = visitor
}
/**
* Start a depth-first traverse of the root and all of its descendants.
* @param root the root node point to traverse.
*/
open func traverse(_ root: Node?)throws {
var node: Node? = root
var depth: Int = 0
while (node != nil) {
try visitor.head(node!, depth)
if (node!.childNodeSize() > 0) {
node = node!.childNode(0)
depth+=1
} else {
while (node!.nextSibling() == nil && depth > 0) {
try visitor.tail(node!, depth)
node = node!.getParentNode()
depth-=1
}
try visitor.tail(node!, depth)
if (node === root) {
break
}
node = node!.nextSibling()
}
}
}
}
+37
View File
@@ -0,0 +1,37 @@
//
// NodeVisitor.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 16/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* Node visitor interface. Provide an implementing class to {@link NodeTraversor} to iterate through nodes.
* <p>
* This interface provides two methods, {@code head} and {@code tail}. The head method is called when the node is first
* seen, and the tail method when all of the node's children have been visited. As an example, head can be used to
* create a start tag for a node, and tail to create the end tag.
* </p>
*/
public protocol NodeVisitor {
/**
* Callback for when a node is first visited.
*
* @param node the node being visited.
* @param depth the depth of the node, relative to the root node. E.g., the root node has depth 0, and a child node
* of that will have depth 1.
*/
func head(_ node: Node, _ depth: Int)throws
/**
* Callback for when a node is last visited, after all of its descendants have been visited.
*
* @param node the node being visited.
* @param depth the depth of the node, relative to the root node. E.g., the root node has depth 0, and a child node
* of that will have depth 1.
*/
func tail(_ node: Node, _ depth: Int)throws
}
+430
View File
@@ -0,0 +1,430 @@
//
// LinkedHashMap.swift
// SwifSoup
//
// Created by Nabil Chatbi on 03/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
public class OrderedDictionary<Key: Hashable, Value: Equatable>: MutableCollection, Hashable {
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return _orderedKeys.index(after: i)
}
// ======================================================= //
// MARK: - Type Aliases
// ======================================================= //
public typealias Element = (Key, Value)
public typealias Index = Int
// ======================================================= //
// MARK: - Initialization
// ======================================================= //
public init() {}
public init(count: Int) {}
public init(elements: [Element]) {
for (key, value) in elements {
self[key] = value
}
}
public func copy() -> Any {
return copy(with: nil)
}
public func mutableCopy(with zone: NSZone? = nil) -> Any {
return copy()
}
public func copy(with zone: NSZone? = nil) -> Any {
let copy = OrderedDictionary<Key, Value>()
//let copy = type(of:self).init()
for element in orderedKeys {
copy.put(value: valueForKey(key: element)!, forKey: element)
}
return copy
}
func clone() -> OrderedDictionary<Key, Value> {
return copy() as! OrderedDictionary<Key, Value>
}
// ======================================================= //
// MARK: - Accessing Keys & Values
// ======================================================= //
public var orderedKeys: [Key] {
return _orderedKeys
}
public func keySet() -> [Key] {
return _orderedKeys
}
public var orderedValues: [Value] {
#if !swift(>=4.1)
return _orderedKeys.flatMap { _keysToValues[$0] }
#else
return _orderedKeys.compactMap { _keysToValues[$0] }
#endif
}
// ======================================================= //
// MARK: - Managing Content Using Keys
// ======================================================= //
public subscript(key: Key) -> Value? {
get {
return valueForKey(key: key)
}
set(newValue) {
if let newValue = newValue {
updateValue(value: newValue, forKey: key)
} else {
removeValueForKey(key: key)
}
}
}
public func containsKey(key: Key) -> Bool {
return _orderedKeys.contains(key)
}
public func valueForKey(key: Key) -> Value? {
return _keysToValues[key]
}
public func get(key: Key) -> Value? {
return valueForKey(key: key)
}
// required var for the Hashable protocol
public var hashValue: Int {
return 0
}
public func hashCode() -> Int {
return hashValue
}
@discardableResult
private func updateValue(value: Value, forKey key: Key) -> Value? {
guard let currentValue = _keysToValues[key] else {
_orderedKeys.append(key)
_keysToValues[key] = value
return nil
}
_keysToValues[key] = value
return currentValue
// if _orderedKeys.contains(key) {
// guard let currentValue = _keysToValues[key] else {
// fatalError("Inconsistency error occured in OrderedDictionary")
// }
//
// _keysToValues[key] = value
//
// return currentValue
// } else {
// _orderedKeys.append(key)
// _keysToValues[key] = value
//
// return nil
// }
}
public func put(value: Value, forKey key: Key) {
self[key] = value
}
public func putAll(all: OrderedDictionary<Key, Value>) {
for i in all.orderedKeys {
put(value: all[i]!, forKey: i)
}
}
@discardableResult
public func removeValueForKey(key: Key) -> Value? {
if let index = _orderedKeys.index(of: key) {
guard let currentValue = _keysToValues[key] else {
fatalError("Inconsistency error occured in OrderedDictionary")
}
_orderedKeys.remove(at: index)
_keysToValues[key] = nil
return currentValue
} else {
return nil
}
}
@discardableResult
public func remove(key: Key) -> Value? {
return removeValueForKey(key: key)
}
public func removeAll(keepCapacity: Bool = true) {
_orderedKeys.removeAll(keepingCapacity: keepCapacity)
_keysToValues.removeAll(keepingCapacity: keepCapacity)
}
// ======================================================= //
// MARK: - Managing Content Using Indexes
// ======================================================= //
public subscript(index: Index) -> Element {
get {
guard let element = elementAtIndex(index: index) else {
fatalError("OrderedDictionary index out of range")
}
return element
}
set(newValue) {
updateElement(element: newValue, atIndex: index)
}
}
public func indexForKey(key: Key) -> Index? {
return _orderedKeys.index(of: key)
}
public func elementAtIndex(index: Index) -> Element? {
guard _orderedKeys.indices.contains(index) else { return nil }
let key = _orderedKeys[index]
guard let value = self._keysToValues[key] else {
fatalError("Inconsistency error occured in OrderedDictionary")
}
return (key, value)
}
public func insertElementWithKey(key: Key, value: Value, atIndex index: Index) -> Value? {
return insertElement(newElement: (key, value), atIndex: index)
}
public func insertElement(newElement: Element, atIndex index: Index) -> Value? {
guard index >= 0 else {
fatalError("Negative OrderedDictionary index is out of range")
}
guard index <= count else {
fatalError("OrderedDictionary index out of range")
}
let (key, value) = newElement
let adjustedIndex: Int
let currentValue: Value?
if let currentIndex = _orderedKeys.index(of: key) {
currentValue = _keysToValues[key]
adjustedIndex = (currentIndex < index - 1) ? index - 1 : index
_orderedKeys.remove(at: currentIndex)
_keysToValues[key] = nil
} else {
currentValue = nil
adjustedIndex = index
}
_orderedKeys.insert(key, at: adjustedIndex)
_keysToValues[key] = value
return currentValue
}
@discardableResult
public func updateElement(element: Element, atIndex index: Index) -> Element? {
guard let currentElement = elementAtIndex(index: index) else {
fatalError("OrderedDictionary index out of range")
}
let (newKey, newValue) = element
_orderedKeys[index] = newKey
_keysToValues[newKey] = newValue
return currentElement
}
public func removeAtIndex(index: Index) -> Element? {
if let element = elementAtIndex(index: index) {
_orderedKeys.remove(at: index)
_keysToValues.removeValue(forKey: element.0)
return element
} else {
return nil
}
}
// ======================================================= //
// MARK: - CollectionType Conformance
// ======================================================= //
public var startIndex: Index {
return _orderedKeys.startIndex
}
public var endIndex: Index {
return _orderedKeys.endIndex
}
// ======================================================= //
// MARK: - Internal Backing Store
// ======================================================= //
/// The backing store for the ordered keys.
internal var _orderedKeys = [Key]()
/// The backing store for the mapping of keys to values.
internal var _keysToValues = [Key: Value]()
}
// ======================================================= //
// MARK: - Initializations from Literals
// ======================================================= //
//extension OrderedDictionary: ExpressibleByArrayLiteral {
//
// public convenience init(arrayLiteral elements: Element...) {
// self.init(elements: elements)
// }
//}
//
//extension OrderedDictionary: ExpressibleByDictionaryLiteral {
//
// public convenience init(dictionaryLiteral elements: Element...) {
// self.init(elements: elements)
// }
//
//}
extension OrderedDictionary: LazySequenceProtocol {
func generate() -> AnyIterator<Value> {
var i = 0
return AnyIterator {
if (i >= self.orderedValues.count) {
return nil
}
i += 1
return self.orderedValues[i-1]
}
}
}
// ======================================================= //
// MARK: - Description
// ======================================================= //
extension OrderedDictionary: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return constructDescription(debug: false)
}
public var debugDescription: String {
return constructDescription(debug: true)
}
private func constructDescription(debug: Bool) -> String {
// The implementation of the description is inspired by zwaldowski's implementation of the ordered dictionary.
// See http://bit.ly/1VL4JUR
if isEmpty { return "[:]" }
func descriptionForItem(item: Any) -> String {
var description = ""
if debug {
debugPrint(item, separator: "", terminator: "", to: &description)
} else {
print(item, separator: "", terminator: "", to: &description)
}
return description
}
let bodyComponents = map({ (key: Key, value: Value) -> String in
return descriptionForItem(item: key) + ": " + descriptionForItem(item: value)
})
let body = bodyComponents.joined(separator: ", ")
return "[\(body)]"
}
}
extension OrderedDictionary: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool {
if(lhs.count != rhs.count) {return false}
return (lhs._orderedKeys == rhs._orderedKeys) && (lhs._keysToValues == rhs._keysToValues)
}
}
//public func == <Key: Equatable, Value: Equatable>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool {
// return lhs._orderedKeys == rhs._orderedKeys && lhs._keysToValues == rhs._keysToValues
//}
/**
* Elements IteratorProtocol.
*/
public struct OrderedDictionaryIterator<Key: Hashable, Value: Equatable>: IteratorProtocol {
/// Elements reference
let orderedDictionary: OrderedDictionary<Key, Value>
//current element index
var index = 0
/// Initializer
init(_ od: OrderedDictionary<Key, Value>) {
self.orderedDictionary = od
}
/// Advances to the next element and returns it, or `nil` if no next element
mutating public func next() -> Value? {
let result = index < orderedDictionary.orderedKeys.count ? orderedDictionary[orderedDictionary.orderedKeys[index]] : nil
index += 1
return result
}
}
/**
* Elements Extension Sequence.
*/
extension OrderedDictionary: Sequence {
/// Returns an iterator over the elements of this sequence.
func generate()->OrderedDictionaryIterator<Key, Value> {
return OrderedDictionaryIterator(self)
}
}
+453
View File
@@ -0,0 +1,453 @@
//
// OrderedSet.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 12/11/16.
// Copyright © 2016 Nabil Chatbi. All rights reserved.
//
import Foundation
/// An ordered, unique collection of objects.
public class OrderedSet<T: Hashable> {
public typealias Index = Int
fileprivate var contents = [T: Index]() // Needs to have a value of Index instead of Void for fast removals
fileprivate var sequencedContents = Array<UnsafeMutablePointer<T>>()
/**
Inititalizes an empty ordered set.
- returns: An empty ordered set.
*/
public init() { }
deinit {
removeAllObjects()
}
/**
Initializes a new ordered set with the order and contents
of sequence.
If an object appears more than once in the sequence it will only appear
once in the ordered set, at the position of its first occurance.
- parameter sequence: The sequence to initialize the ordered set with.
- returns: An initialized ordered set with the contents of sequence.
*/
public init<S: Sequence>(sequence: S) where S.Iterator.Element == T {
for object in sequence {
if contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
}
public required init(arrayLiteral elements: T...) {
for object in elements {
if contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
}
/**
Locate the index of an object in the ordered set.
It is preferable to use this method over the global find() for performance reasons.
- parameter object: The object to find the index for.
- returns: The index of the object, or nil if the object is not in the ordered set.
*/
public func index(of object: T) -> Index? {
if let index = contents[object] {
return index
}
return nil
}
/**
Appends an object to the end of the ordered set.
- parameter object: The object to be appended.
*/
public func append(_ object: T) {
if let lastIndex = index(of: object) {
remove(object)
insert(object, at: lastIndex)
} else {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
/**
Appends a sequence of objects to the end of the ordered set.
- parameter sequence: The sequence of objects to be appended.
*/
public func append<S: Sequence>(contentsOf sequence: S) where S.Iterator.Element == T {
var gen = sequence.makeIterator()
while let object: T = gen.next() {
append(object)
}
}
/**
Removes an object from the ordered set.
If the object exists in the ordered set, it will be removed.
If it is not the last object in the ordered set, subsequent
objects will be shifted down one position.
- parameter object: The object to be removed.
*/
public func remove(_ object: T) {
if let index = contents[object] {
contents[object] = nil
#if !swift(>=4.1)
sequencedContents[index].deallocate(capacity: 1)
#else
sequencedContents[index].deallocate()
#endif
sequencedContents.remove(at: index)
for (object, i) in contents {
if i < index {
continue
}
contents[object] = i - 1
}
}
}
/**
Removes the given objects from the ordered set.
- parameter objects: The objects to be removed.
*/
public func remove<S: Sequence>(_ objects: S) where S.Iterator.Element == T {
var gen = objects.makeIterator()
while let object: T = gen.next() {
remove(object)
}
}
/**
Removes an object at a given index.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter index: The index of the object to be removed.
*/
public func removeObject(at index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to remove an object at an index that does not exist")
}
remove(sequencedContents[index].pointee)
}
/**
Removes all objects in the ordered set.
*/
public func removeAllObjects() {
contents.removeAll()
for sequencedContent in sequencedContents {
#if !swift(>=4.1)
sequencedContent.deallocate(capacity: 1)
#else
sequencedContent.deallocate()
#endif
}
sequencedContents.removeAll()
}
/**
Swaps two objects contained within the ordered set.
Both objects must exist within the set, or the swap will not occur.
- parameter first: The first object to be swapped.
- parameter second: The second object to be swapped.
*/
public func swapObject(_ first: T, with second: T) {
if let firstPosition = contents[first] {
if let secondPosition = contents[second] {
contents[first] = secondPosition
contents[second] = firstPosition
sequencedContents[firstPosition].pointee = second
sequencedContents[secondPosition].pointee = first
}
}
}
/**
Tests if the ordered set contains any objects within a sequence.
- parameter other: The sequence to look for the intersection in.
- returns: Returns true if the sequence and set contain any equal objects, otherwise false.
*/
public func intersects<S: Sequence>(_ other: S) -> Bool where S.Iterator.Element == T {
var gen = other.makeIterator()
while let object: T = gen.next() {
if contains(object) {
return true
}
}
return false
}
/**
Tests if a the ordered set is a subset of another sequence.
- parameter sequence: The sequence to check.
- returns: true if the sequence contains all objects contained in the receiver, otherwise false.
*/
public func isSubset<S: Sequence>(of sequence: S) -> Bool where S.Iterator.Element == T {
for (object, _) in contents {
if !sequence.contains(object) {
return false
}
}
return true
}
/**
Moves an object to a different index, shifting all objects in between the movement.
This method is a no-op if the object doesn't exist in the set or the index is the
same that the object is currently at.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter object: The object to be moved
- parameter index: The index that the object should be moved to.
*/
public func moveObject(_ object: T, toIndex index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to move an object at an index that does not exist")
}
if let position = contents[object] {
// Return if the client attempted to move to the current index
if position == index {
return
}
let adjustment = position > index ? -1 : 1
var currentIndex = position
while currentIndex != index {
let nextIndex = currentIndex + adjustment
let firstObject = sequencedContents[currentIndex].pointee
let secondObject = sequencedContents[nextIndex].pointee
sequencedContents[currentIndex].pointee = secondObject
sequencedContents[nextIndex].pointee = firstObject
contents[firstObject] = nextIndex
contents[secondObject] = currentIndex
currentIndex += adjustment
}
}
}
/**
Moves an object from one index to a different index, shifting all objects in between the movement.
This method is a no-op if the index is the same that the object is currently at.
This method will cause a fatal error if you attempt to move an object fro man index that is out of bounds
or to an index that is out of bounds.
- parameter index: The index of the object to be moved.
- parameter toIndex: The index that the object should be moved to.
*/
public func moveObject(at index: Index, to toIndex: Index) {
if ((index < 0 || index >= count) || (toIndex < 0 || toIndex >= count)) {
fatalError("Attempting to move an object at or to an index that does not exist")
}
moveObject(self[index], toIndex: toIndex)
}
/**
Inserts an object at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the object out of bounds.
If the object already exists in the OrderedSet, this operation is a no-op.
- parameter object: The object to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert(_ object: T, at index: Index) {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
if contents[object] != nil {
return
}
// Append our object, then swap them until its at the end.
append(object)
for i in (index..<count-1).reversed() {
swapObject(self[i], with: self[i+1])
}
}
/**
Inserts objects at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the objects out of bounds.
If an object in objects already exists in the OrderedSet it will not be added. Objects that occur twice
in the sequence will only be added once.
- parameter objects: The objects to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert<S: Sequence>(_ objects: S, at index: Index) where S.Iterator.Element == T {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
var addedObjectCount = 0
for object in objects {
if contents[object] == nil {
let seqIdx = index + addedObjectCount
let element = UnsafeMutablePointer<T>.allocate(capacity: 1)
element.initialize(to: object)
sequencedContents.insert(element, at: seqIdx)
contents[object] = seqIdx
addedObjectCount += 1
}
}
// Now we'll remove duplicates and update the shifted objects position in the contents
// dictionary.
for i in index + addedObjectCount..<count {
contents[sequencedContents[i].pointee] = i
}
}
/// Returns the last object in the set, or `nil` if the set is empty.
public var last: T? {
return sequencedContents.last?.pointee
}
}
extension OrderedSet: ExpressibleByArrayLiteral { }
extension OrderedSet where T: Comparable {}
extension OrderedSet {
public var count: Int {
return contents.count
}
public var isEmpty: Bool {
return count == 0
}
public var first: T? {
guard count > 0 else { return nil }
return sequencedContents[0].pointee
}
public func index(after i: Int) -> Int {
return sequencedContents.index(after: i)
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return contents.count
}
public subscript(index: Index) -> T {
get {
return sequencedContents[index].pointee
}
set {
let previousCount = contents.count
contents[sequencedContents[index].pointee] = nil
contents[newValue] = index
// If the count is reduced we used an existing value, and need to sync up sequencedContents
if contents.count == previousCount {
sequencedContents[index].pointee = newValue
} else {
sequencedContents.remove(at: index)
}
}
}
}
extension OrderedSet: Sequence {
public typealias Iterator = OrderedSetGenerator<T>
public func makeIterator() -> Iterator {
return OrderedSetGenerator(set: self)
}
}
public struct OrderedSetGenerator<T: Hashable>: IteratorProtocol {
public typealias Element = T
private var generator: IndexingIterator<Array<UnsafeMutablePointer<T>>>
public init(set: OrderedSet<T>) {
generator = set.sequencedContents.makeIterator()
}
public mutating func next() -> Element? {
return generator.next()?.pointee
}
}
extension OrderedSetGenerator where T: Comparable {}
public func +<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T {
let joinedSet = lhs
joinedSet.append(contentsOf: rhs)
return joinedSet
}
public func +=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T {
lhs.append(contentsOf: rhs)
}
public func -<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T {
let purgedSet = lhs
purgedSet.remove(rhs)
return purgedSet
}
public func -=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T {
lhs.remove(rhs)
}
extension OrderedSet: Equatable { }
public func ==<T> (lhs: OrderedSet<T>, rhs: OrderedSet<T>) -> Bool {
if lhs.count != rhs.count {
return false
}
for object in lhs {
if lhs.contents[object] != rhs.contents[object] {
return false
}
}
return true
}
extension OrderedSet: CustomStringConvertible {
public var description: String {
let children = map({ "\($0)" }).joined(separator: ", ")
return "OrderedSet (\(count) object(s)): [\(children)]"
}
}
+42
View File
@@ -0,0 +1,42 @@
//
// ParseError.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 19/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* A Parse Error records an error in the input HTML that occurs in either the tokenisation or the tree building phase.
*/
open class ParseError {
private let pos: Int
private let errorMsg: String
init(_ pos: Int, _ errorMsg: String) {
self.pos = pos
self.errorMsg = errorMsg
}
/**
* Retrieve the error message.
* @return the error message.
*/
open func getErrorMessage() -> String {
return errorMsg
}
/**
* Retrieves the offset of the error.
* @return error offset within input
*/
open func getPosition() -> Int {
return pos
}
open func toString() -> String {
return "\(pos): " + errorMsg
}
}

Some files were not shown because too many files have changed in this diff Show More