From c23d0ab8102e3fae12953501835a78ca0df36c39 Mon Sep 17 00:00:00 2001 From: felipe Date: Fri, 14 Feb 2020 14:38:39 -0300 Subject: [PATCH 01/25] start project TesteArenaFelipePerius --- .../project.pbxproj | 599 ++++++++++++++++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../UserInterfaceState.xcuserstate | Bin 0 -> 5630 bytes .../xcschemes/xcschememanagement.plist | 14 + .../TesteArenaFelipePerius/AppDelegate.swift | 37 ++ .../AppIcon.appiconset/Contents.json | 98 +++ .../Assets.xcassets/Contents.json | 6 + .../Base.lproj/LaunchScreen.storyboard | 25 + .../TesteArenaFelipePerius/ContentView.swift | 21 + .../TesteArenaFelipePerius/Info.plist | 60 ++ .../Preview Assets.xcassets/Contents.json | 6 + .../SceneDelegate.swift | 64 ++ .../TesteArenaFelipePeriusTests/Info.plist | 22 + .../TesteArenaFelipePeriusTests.swift | 34 + .../TesteArenaFelipePeriusUITests/Info.plist | 22 + .../TesteArenaFelipePeriusUITests.swift | 43 ++ 17 files changed, 1066 insertions(+) create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcuserdata/feperius.xcuserdatad/UserInterfaceState.xcuserstate create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/xcuserdata/feperius.xcuserdatad/xcschemes/xcschememanagement.plist create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/AppDelegate.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/Contents.json create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Base.lproj/LaunchScreen.storyboard create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/ContentView.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Preview Content/Preview Assets.xcassets/Contents.json create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/SceneDelegate.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePeriusTests/Info.plist create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePeriusTests/TesteArenaFelipePeriusTests.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePeriusUITests/Info.plist create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePeriusUITests/TesteArenaFelipePeriusUITests.swift diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj new file mode 100644 index 0000000..2d225a8 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj @@ -0,0 +1,599 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 2F7B7C3423F711C7006D73D2 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3323F711C7006D73D2 /* AppDelegate.swift */; }; + 2F7B7C3623F711C7006D73D2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3523F711C7006D73D2 /* SceneDelegate.swift */; }; + 2F7B7C3823F711C7006D73D2 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3723F711C7006D73D2 /* ContentView.swift */; }; + 2F7B7C3A23F711C9006D73D2 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3923F711C9006D73D2 /* Assets.xcassets */; }; + 2F7B7C3D23F711C9006D73D2 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3C23F711C9006D73D2 /* Preview Assets.xcassets */; }; + 2F7B7C4023F711C9006D73D2 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3E23F711C9006D73D2 /* LaunchScreen.storyboard */; }; + 2F7B7C4B23F711C9006D73D2 /* TesteArenaFelipePeriusTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C4A23F711C9006D73D2 /* TesteArenaFelipePeriusTests.swift */; }; + 2F7B7C5623F711C9006D73D2 /* TesteArenaFelipePeriusUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C5523F711C9006D73D2 /* TesteArenaFelipePeriusUITests.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 2F7B7C4723F711C9006D73D2 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 2F7B7C2823F711C7006D73D2 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 2F7B7C2F23F711C7006D73D2; + remoteInfo = TesteArenaFelipePerius; + }; + 2F7B7C5223F711C9006D73D2 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 2F7B7C2823F711C7006D73D2 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 2F7B7C2F23F711C7006D73D2; + remoteInfo = TesteArenaFelipePerius; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 2F7B7C3023F711C7006D73D2 /* TesteArenaFelipePerius.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TesteArenaFelipePerius.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 2F7B7C3323F711C7006D73D2 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 2F7B7C3523F711C7006D73D2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 2F7B7C3723F711C7006D73D2 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + 2F7B7C3923F711C9006D73D2 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 2F7B7C3C23F711C9006D73D2 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; + 2F7B7C3F23F711C9006D73D2 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 2F7B7C4123F711C9006D73D2 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 2F7B7C4623F711C9006D73D2 /* TesteArenaFelipePeriusTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = TesteArenaFelipePeriusTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 2F7B7C4A23F711C9006D73D2 /* TesteArenaFelipePeriusTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TesteArenaFelipePeriusTests.swift; sourceTree = ""; }; + 2F7B7C4C23F711C9006D73D2 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 2F7B7C5123F711C9006D73D2 /* TesteArenaFelipePeriusUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = TesteArenaFelipePeriusUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 2F7B7C5523F711C9006D73D2 /* TesteArenaFelipePeriusUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TesteArenaFelipePeriusUITests.swift; sourceTree = ""; }; + 2F7B7C5723F711C9006D73D2 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 2F7B7C2D23F711C7006D73D2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2F7B7C4323F711C9006D73D2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2F7B7C4E23F711C9006D73D2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2F7B7C2723F711C7006D73D2 = { + isa = PBXGroup; + children = ( + 2F7B7C3223F711C7006D73D2 /* TesteArenaFelipePerius */, + 2F7B7C4923F711C9006D73D2 /* TesteArenaFelipePeriusTests */, + 2F7B7C5423F711C9006D73D2 /* TesteArenaFelipePeriusUITests */, + 2F7B7C3123F711C7006D73D2 /* Products */, + ); + sourceTree = ""; + }; + 2F7B7C3123F711C7006D73D2 /* Products */ = { + isa = PBXGroup; + children = ( + 2F7B7C3023F711C7006D73D2 /* TesteArenaFelipePerius.app */, + 2F7B7C4623F711C9006D73D2 /* TesteArenaFelipePeriusTests.xctest */, + 2F7B7C5123F711C9006D73D2 /* TesteArenaFelipePeriusUITests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 2F7B7C3223F711C7006D73D2 /* TesteArenaFelipePerius */ = { + isa = PBXGroup; + children = ( + 2F7B7C3323F711C7006D73D2 /* AppDelegate.swift */, + 2F7B7C3523F711C7006D73D2 /* SceneDelegate.swift */, + 2F7B7C3723F711C7006D73D2 /* ContentView.swift */, + 2F7B7C3923F711C9006D73D2 /* Assets.xcassets */, + 2F7B7C3E23F711C9006D73D2 /* LaunchScreen.storyboard */, + 2F7B7C4123F711C9006D73D2 /* Info.plist */, + 2F7B7C3B23F711C9006D73D2 /* Preview Content */, + ); + path = TesteArenaFelipePerius; + sourceTree = ""; + }; + 2F7B7C3B23F711C9006D73D2 /* Preview Content */ = { + isa = PBXGroup; + children = ( + 2F7B7C3C23F711C9006D73D2 /* Preview Assets.xcassets */, + ); + path = "Preview Content"; + sourceTree = ""; + }; + 2F7B7C4923F711C9006D73D2 /* TesteArenaFelipePeriusTests */ = { + isa = PBXGroup; + children = ( + 2F7B7C4A23F711C9006D73D2 /* TesteArenaFelipePeriusTests.swift */, + 2F7B7C4C23F711C9006D73D2 /* Info.plist */, + ); + path = TesteArenaFelipePeriusTests; + sourceTree = ""; + }; + 2F7B7C5423F711C9006D73D2 /* TesteArenaFelipePeriusUITests */ = { + isa = PBXGroup; + children = ( + 2F7B7C5523F711C9006D73D2 /* TesteArenaFelipePeriusUITests.swift */, + 2F7B7C5723F711C9006D73D2 /* Info.plist */, + ); + path = TesteArenaFelipePeriusUITests; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 2F7B7C2F23F711C7006D73D2 /* TesteArenaFelipePerius */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2F7B7C5A23F711C9006D73D2 /* Build configuration list for PBXNativeTarget "TesteArenaFelipePerius" */; + buildPhases = ( + 2F7B7C2C23F711C7006D73D2 /* Sources */, + 2F7B7C2D23F711C7006D73D2 /* Frameworks */, + 2F7B7C2E23F711C7006D73D2 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = TesteArenaFelipePerius; + productName = TesteArenaFelipePerius; + productReference = 2F7B7C3023F711C7006D73D2 /* TesteArenaFelipePerius.app */; + productType = "com.apple.product-type.application"; + }; + 2F7B7C4523F711C9006D73D2 /* TesteArenaFelipePeriusTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2F7B7C5D23F711C9006D73D2 /* Build configuration list for PBXNativeTarget "TesteArenaFelipePeriusTests" */; + buildPhases = ( + 2F7B7C4223F711C9006D73D2 /* Sources */, + 2F7B7C4323F711C9006D73D2 /* Frameworks */, + 2F7B7C4423F711C9006D73D2 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 2F7B7C4823F711C9006D73D2 /* PBXTargetDependency */, + ); + name = TesteArenaFelipePeriusTests; + productName = TesteArenaFelipePeriusTests; + productReference = 2F7B7C4623F711C9006D73D2 /* TesteArenaFelipePeriusTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 2F7B7C5023F711C9006D73D2 /* TesteArenaFelipePeriusUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2F7B7C6023F711C9006D73D2 /* Build configuration list for PBXNativeTarget "TesteArenaFelipePeriusUITests" */; + buildPhases = ( + 2F7B7C4D23F711C9006D73D2 /* Sources */, + 2F7B7C4E23F711C9006D73D2 /* Frameworks */, + 2F7B7C4F23F711C9006D73D2 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 2F7B7C5323F711C9006D73D2 /* PBXTargetDependency */, + ); + name = TesteArenaFelipePeriusUITests; + productName = TesteArenaFelipePeriusUITests; + productReference = 2F7B7C5123F711C9006D73D2 /* TesteArenaFelipePeriusUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 2F7B7C2823F711C7006D73D2 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1120; + LastUpgradeCheck = 1120; + ORGANIZATIONNAME = "Felipe Perius"; + TargetAttributes = { + 2F7B7C2F23F711C7006D73D2 = { + CreatedOnToolsVersion = 11.2.1; + }; + 2F7B7C4523F711C9006D73D2 = { + CreatedOnToolsVersion = 11.2.1; + TestTargetID = 2F7B7C2F23F711C7006D73D2; + }; + 2F7B7C5023F711C9006D73D2 = { + CreatedOnToolsVersion = 11.2.1; + TestTargetID = 2F7B7C2F23F711C7006D73D2; + }; + }; + }; + buildConfigurationList = 2F7B7C2B23F711C7006D73D2 /* Build configuration list for PBXProject "TesteArenaFelipePerius" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 2F7B7C2723F711C7006D73D2; + productRefGroup = 2F7B7C3123F711C7006D73D2 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 2F7B7C2F23F711C7006D73D2 /* TesteArenaFelipePerius */, + 2F7B7C4523F711C9006D73D2 /* TesteArenaFelipePeriusTests */, + 2F7B7C5023F711C9006D73D2 /* TesteArenaFelipePeriusUITests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 2F7B7C2E23F711C7006D73D2 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2F7B7C4023F711C9006D73D2 /* LaunchScreen.storyboard in Resources */, + 2F7B7C3D23F711C9006D73D2 /* Preview Assets.xcassets in Resources */, + 2F7B7C3A23F711C9006D73D2 /* Assets.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2F7B7C4423F711C9006D73D2 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2F7B7C4F23F711C9006D73D2 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 2F7B7C2C23F711C7006D73D2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2F7B7C3423F711C7006D73D2 /* AppDelegate.swift in Sources */, + 2F7B7C3623F711C7006D73D2 /* SceneDelegate.swift in Sources */, + 2F7B7C3823F711C7006D73D2 /* ContentView.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2F7B7C4223F711C9006D73D2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2F7B7C4B23F711C9006D73D2 /* TesteArenaFelipePeriusTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2F7B7C4D23F711C9006D73D2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2F7B7C5623F711C9006D73D2 /* TesteArenaFelipePeriusUITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 2F7B7C4823F711C9006D73D2 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 2F7B7C2F23F711C7006D73D2 /* TesteArenaFelipePerius */; + targetProxy = 2F7B7C4723F711C9006D73D2 /* PBXContainerItemProxy */; + }; + 2F7B7C5323F711C9006D73D2 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 2F7B7C2F23F711C7006D73D2 /* TesteArenaFelipePerius */; + targetProxy = 2F7B7C5223F711C9006D73D2 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 2F7B7C3E23F711C9006D73D2 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 2F7B7C3F23F711C9006D73D2 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 2F7B7C5823F711C9006D73D2 /* 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; + 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 = 13.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; + }; + 2F7B7C5923F711C9006D73D2 /* 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; + 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 = 13.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; + }; + 2F7B7C5B23F711C9006D73D2 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_ASSET_PATHS = "\"TesteArenaFelipePerius/Preview Content\""; + DEVELOPMENT_TEAM = V927RLF8V5; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = TesteArenaFelipePerius/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = br.com.testearena.TesteArenaFelipePerius; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 2F7B7C5C23F711C9006D73D2 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_ASSET_PATHS = "\"TesteArenaFelipePerius/Preview Content\""; + DEVELOPMENT_TEAM = V927RLF8V5; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = TesteArenaFelipePerius/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = br.com.testearena.TesteArenaFelipePerius; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + 2F7B7C5E23F711C9006D73D2 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = V927RLF8V5; + INFOPLIST_FILE = TesteArenaFelipePeriusTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = br.com.testearena.TesteArenaFelipePeriusTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/TesteArenaFelipePerius.app/TesteArenaFelipePerius"; + }; + name = Debug; + }; + 2F7B7C5F23F711C9006D73D2 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = V927RLF8V5; + INFOPLIST_FILE = TesteArenaFelipePeriusTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = br.com.testearena.TesteArenaFelipePeriusTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/TesteArenaFelipePerius.app/TesteArenaFelipePerius"; + }; + name = Release; + }; + 2F7B7C6123F711C9006D73D2 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = V927RLF8V5; + INFOPLIST_FILE = TesteArenaFelipePeriusUITests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = br.com.testearena.TesteArenaFelipePeriusUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = TesteArenaFelipePerius; + }; + name = Debug; + }; + 2F7B7C6223F711C9006D73D2 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = V927RLF8V5; + INFOPLIST_FILE = TesteArenaFelipePeriusUITests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = br.com.testearena.TesteArenaFelipePeriusUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = TesteArenaFelipePerius; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2F7B7C2B23F711C7006D73D2 /* Build configuration list for PBXProject "TesteArenaFelipePerius" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2F7B7C5823F711C9006D73D2 /* Debug */, + 2F7B7C5923F711C9006D73D2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2F7B7C5A23F711C9006D73D2 /* Build configuration list for PBXNativeTarget "TesteArenaFelipePerius" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2F7B7C5B23F711C9006D73D2 /* Debug */, + 2F7B7C5C23F711C9006D73D2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2F7B7C5D23F711C9006D73D2 /* Build configuration list for PBXNativeTarget "TesteArenaFelipePeriusTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2F7B7C5E23F711C9006D73D2 /* Debug */, + 2F7B7C5F23F711C9006D73D2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2F7B7C6023F711C9006D73D2 /* Build configuration list for PBXNativeTarget "TesteArenaFelipePeriusUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2F7B7C6123F711C9006D73D2 /* Debug */, + 2F7B7C6223F711C9006D73D2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 2F7B7C2823F711C7006D73D2 /* Project object */; +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..20eee7a --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcuserdata/feperius.xcuserdatad/UserInterfaceState.xcuserstate b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcuserdata/feperius.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000000000000000000000000000000000000..cff215fea57c99c8e82cdd9348b8850ffbe5674d GIT binary patch literal 5630 zcma)A349ynm4Dxi#u`a8wyZdDoYRR#$R#7ohwM0UZ0krwV#l$3x7P3H zIlk{5-#h;Az3Co^$;p({`5X{nfCU3^kV6iWySnU`OG;8s#JlW??#rY|D!I-cRw8{e zzHYOp5(73Mdk@`bO@R@3m;?nd87_i(a52n>1+WknK^auSQm6+ntb|q23@xx0A`k@$ zdY~8jK!(d;E9``Cz%IBFt^x{I!yWJgxDyV+FpR(`9EQ8#2polDa5vls{|WcQuizng z7#@K~;W2mu{u`c!lW+>2gFnFY@DjWNe}QxG0elD_!N>3^d_e?aB?Y9I%pr4039%C= zDI+dYPAbR}_#>$$4a84c$Xc?2Y$V;Jk0>Nbc9AQ|KJqQHpWH+alAFo*$gSl2eedT#whZkvi;=SU8y+0TFU3L)j6qLOwOn$+R|PEeLph zoe5=Yav&U$yotzQzZ6e}tag{%Q{$;|c^y6v{;Tj+xg9m-6<&wS>vK0YHo86K)xM12 zDKHc4N1za@Z=`e$GG=~}~PfgT(1ZKf(D26#O7fPsw=20unr#4zZb3@i?opL;y z7-~?IaJ*MiWqYOW!QMc;ClRvdW%SWEC2_k~>Io0VQog91N+`ipI3*?h38lStH7@1_ zr5FZ<6wPj*+A2kmrM^4EOy6A4s7T?h0|_~vN;X7N^5w`XnmN#7Cvh}4!~Ig1ek&z6HwT*rQ{nEIq#kR>DDGPVwdfe_v8y?_ zMhjk@$1! z#cF6eL?`L8mcW`3RTWc)t`*jU{U`*X4cegtI-v{J(J8c$PNhY38l6sO9EArivBRZ612Rg-Ey_l8s9kaae0)m$fK z19+lD>%6RbxX>6@I>X5hIVmHXPC3;Vl;gcI30FeaqOpyMM65fk1Tq^#)~RD_8k2EL zQ+DojE-tQc?^;~Ev&>bE_wI7%u3Z`P#vrNYML)zL0RylN6grz0(>Zi5EupxOLX%z& zL->COy$B5&p)vfQpt+k+q#m>l7^NYr6`zBBiJ|83<#KNrEfKOVR<+9H?Sx}{rKH>& zR|$g%q^S;B8qzsrsV6dRPszAVmN0`>{Wx3$d*GX}7p{eU z@GaO6*TDg}9&VuX=*4tCT|gJoMRYNB&{BE{b<(oqa1$Jao8cDtwi-O}UA(^)Zo@Eg z(R$iI8>vSNBOl)TX^R?AA#1({0KJkjPWxir7)_Y@@&Lwwdaf2l?#DD)9o~@`M8I-2 zN<9fhY6@?c`{gSnPojSytjNhkyeSctLhVUONqauc3g50DyA4^3GvJ}W%$hF{k4oEH z!l^#hC#nzhb+ncGkkM7QXmJ{yTGT3)Od;~LN&||N#GA01)yd5n^`crBhpdw?kftLV z0s;z4Gt)%q{OA9lXOxp!?ish;1IJYyyO)*^!@tuC-Mk%bS<41eQh!p%i62762>ciP zh*r|2RLn5=2|NI{Q8)oVg`d$X>ZaAB@N@L#gR}-cw}jSi@^-WZqIf{LN0yY0>eE=} zSn*K}zou|+Tuu!}rFD2L{lq2p@)l74bYxl%kB_Kmmy!D<{Pt^de}@tDG+l;KvRo}( zd76o^R$!>8=HW}~H$J4X3|VdIs8}uaq}md#a&KSC3RbMj{{t@|CjJqt^NSd1&B3g9 zS4;8UR3CbE+`Eo&Y*4Zi>eY388UD0k-0BFNhT8EjGP=JCe;yCUXH>L4OIM5;^$mDi zJ=~j^NPnd(F>L~)@D8TNd-PIFgjKY5gX))62&=249T*F`#a3cOC6pZ)A(5?WvCHfU z>C3toKT(C9r>j-;|2v-aGx!_^vE$uh2ypz15#-+r68tG40=>Gsn+SSDi*R%k841d=5*oy z{0Xb7oDCTbuy!ML=E=7mb4=|A$0Cqo%clLB^{eJOA`%1^wbPkkO7#>YBoESE(AU;< z+I(WeJiU-sbHfOkq!R!0#dJ83$z&SX50fdRkW3{-bS-VALE3hhOeZtQOfrkM)Ae*C z-9&S{)M!=HWt|qV>fL%hjx`9=#AGu!iwYSr7mwSMCKAdjw1q}93Pqq|lthU{dZ9lPV5~DXrD@P?Uo5jT}7_Bkb>+%ioNtQq}Zy0rCQjtbzViwlKO%A2~4gd z*QLTu4K%L#B~udhyw}=};;sn#rxe+(l2fJGh0?u?n{+Qjdgi6!jn`^dg{*C9zj8MdUWUeI<7wB>jNgsZKOeM3^=C21j>h zG$agb;BqP||Gy)l&B&X~7D3D{oH=XuMT-_YoaOrPgmB_4uC6Rr+qdGX8dtFsf7*lF z?Jn-X-gAkotOZL79y!}@rTbE=y|UcvcKcmEN0q;-%u(U2@;j=_Jbs7A?`o(l^LX6V zjWs$zWTua?hWJ#THQ!b+gKJQ>Fi>#3}wL~=)> zPApH&L9DY2$5|@Li9WiWmlUudXQJ0ww&VW}JyFwYz{R`c0Ie1-OO%byEXg*23r^HuPuE|Us#DEp5T~HhRF!JEIpE|y~-%Q8iiVP zg+54L7y-|cBjjki){9eu)+oXXx(L4YnlDb0p>>LAX?!2%$>|I zGs+xiPB0HK&oIw3rLN7=jCd)Wur&kgeoD-GKW*Bg!*9yUB}c**c5 z!z+eA8~$QAYdB~4*l^zPso^uj7lto6;26%zm2j<`#BJxUS#`DI{d7jVX^Z7~qWPS!ei!bKq@^-$8ck}gpJKxE#<9qlk z`0M!_`Gfpz{1N_M{sjLR|2Y2y|7-qP{yF}6{ssOl|2F?F|33dA|9Ad#{vZ5TCSnpz zC8kPKovFd(G5Ji*CfT&r)Ni`MbdTw2)2pU0%{KEa^HOu2x!&Ap_L}|XmF7#$tIh4^ zn0cFdpZTEqZu5VbpD>>?zid8je%1V%`HcA;^LyqG%paLQG5^g17PDot#bH@u@mPG8 z6_$Wym8H$nVd=80w`{a*wtT~KtK}D#KUiL~oVA>@yk&XY@~*%Ld4f$S5DJANVY*-! z76^+3hj59oRPYEsVTBM7T7*`iP3RE1gs>1728AJEhp+S7!~`)E5u#mRpM@OkGNO7O?*)Njre=<8S$j} xocO%>SuUGv$j!;k%Pq96v|VZo+QPOzTf%m=ZLjTso}LV&U&*nFS!=uDe*q1_mf!#Y literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/xcuserdata/feperius.xcuserdatad/xcschemes/xcschememanagement.plist b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/xcuserdata/feperius.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..ccc35ff --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/xcuserdata/feperius.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SchemeUserState + + TesteArenaFelipePerius.xcscheme_^#shared#^_ + + orderHint + 0 + + + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/AppDelegate.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/AppDelegate.swift new file mode 100644 index 0000000..2d54014 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/AppDelegate.swift @@ -0,0 +1,37 @@ +// +// AppDelegate.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 14/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + // MARK: UISceneSession Lifecycle + + func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { + // Called when a new scene session is being created. + // Use this method to select a configuration to create the new scene with. + return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) + } + + func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { + // Called when the user discards a scene session. + // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. + // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + } + + +} + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/AppIcon.appiconset/Contents.json b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d8db8d6 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -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" + } +} \ No newline at end of file diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/Contents.json b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Base.lproj/LaunchScreen.storyboard b/TesteArenaFelipePerius/TesteArenaFelipePerius/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..865e932 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/ContentView.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/ContentView.swift new file mode 100644 index 0000000..6a278c0 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/ContentView.swift @@ -0,0 +1,21 @@ +// +// ContentView.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 14/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import SwiftUI + +struct ContentView: View { + var body: some View { + Text("Hello, World!") + } +} + +struct ContentView_Previews: PreviewProvider { + static var previews: some View { + ContentView() + } +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist b/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist new file mode 100644 index 0000000..9742bf0 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist @@ -0,0 +1,60 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + + + + + UILaunchStoryboardName + LaunchScreen + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Preview Content/Preview Assets.xcassets/Contents.json b/TesteArenaFelipePerius/TesteArenaFelipePerius/Preview Content/Preview Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Preview Content/Preview Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/SceneDelegate.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/SceneDelegate.swift new file mode 100644 index 0000000..e50987d --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/SceneDelegate.swift @@ -0,0 +1,64 @@ +// +// SceneDelegate.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 14/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit +import SwiftUI + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + + var window: UIWindow? + + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. + // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. + // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). + + // Create the SwiftUI view that provides the window contents. + let contentView = ContentView() + + // Use a UIHostingController as window root view controller. + if let windowScene = scene as? UIWindowScene { + let window = UIWindow(windowScene: windowScene) + window.rootViewController = UIHostingController(rootView: contentView) + self.window = window + window.makeKeyAndVisible() + } + } + + func sceneDidDisconnect(_ scene: UIScene) { + // Called as the scene is being released by the system. + // This occurs shortly after the scene enters the background, or when its session is discarded. + // Release any resources associated with this scene that can be re-created the next time the scene connects. + // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). + } + + func sceneDidBecomeActive(_ scene: UIScene) { + // Called when the scene has moved from an inactive state to an active state. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. + } + + func sceneWillResignActive(_ scene: UIScene) { + // Called when the scene will move from an active state to an inactive state. + // This may occur due to temporary interruptions (ex. an incoming phone call). + } + + func sceneWillEnterForeground(_ scene: UIScene) { + // Called as the scene transitions from the background to the foreground. + // Use this method to undo the changes made on entering the background. + } + + func sceneDidEnterBackground(_ scene: UIScene) { + // Called as the scene transitions from the foreground to the background. + // Use this method to save data, release shared resources, and store enough scene-specific state information + // to restore the scene back to its current state. + } + + +} + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePeriusTests/Info.plist b/TesteArenaFelipePerius/TesteArenaFelipePeriusTests/Info.plist new file mode 100644 index 0000000..64d65ca --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePeriusTests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePeriusTests/TesteArenaFelipePeriusTests.swift b/TesteArenaFelipePerius/TesteArenaFelipePeriusTests/TesteArenaFelipePeriusTests.swift new file mode 100644 index 0000000..1d37b03 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePeriusTests/TesteArenaFelipePeriusTests.swift @@ -0,0 +1,34 @@ +// +// TesteArenaFelipePeriusTests.swift +// TesteArenaFelipePeriusTests +// +// Created by Felipe perius on 14/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import XCTest +@testable import TesteArenaFelipePerius + +class TesteArenaFelipePeriusTests: 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. + } + } + +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePeriusUITests/Info.plist b/TesteArenaFelipePerius/TesteArenaFelipePeriusUITests/Info.plist new file mode 100644 index 0000000..64d65ca --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePeriusUITests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePeriusUITests/TesteArenaFelipePeriusUITests.swift b/TesteArenaFelipePerius/TesteArenaFelipePeriusUITests/TesteArenaFelipePeriusUITests.swift new file mode 100644 index 0000000..5bdaebb --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePeriusUITests/TesteArenaFelipePeriusUITests.swift @@ -0,0 +1,43 @@ +// +// TesteArenaFelipePeriusUITests.swift +// TesteArenaFelipePeriusUITests +// +// Created by Felipe perius on 14/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import XCTest + +class TesteArenaFelipePeriusUITests: 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 + + // In UI tests it’s 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() { + // UI tests must launch the application that they test. + let app = XCUIApplication() + app.launch() + + // Use recording to get started writing UI tests. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testLaunchPerformance() { + if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { + // This measures how long it takes to launch your application. + measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { + XCUIApplication().launch() + } + } + } +} From 4780a31844bc6113d2f0c67347e4480375749f5d Mon Sep 17 00:00:00 2001 From: felipe Date: Fri, 14 Feb 2020 14:39:06 -0300 Subject: [PATCH 02/25] create project TesteArenaFelipePerius --- .../UserInterfaceState.xcuserstate | Bin 5630 -> 19884 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcuserdata/feperius.xcuserdatad/UserInterfaceState.xcuserstate b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcuserdata/feperius.xcuserdatad/UserInterfaceState.xcuserstate index cff215fea57c99c8e82cdd9348b8850ffbe5674d..68741089fffaeccc899abfe8833fe80b96470f29 100644 GIT binary patch literal 19884 zcmeHvd3aOB_xH@bN!uiCnzSiPS=v(8(zIEdbWL|Cl(x_XC`$=#+6L03Bx%`o!YZJm zh$xFf3$h4`8>_g0Afm{=s4RlGfFk08sGz=Q?oGM?e!u>n=Y4+fKX3D-nLF#5nKNh3 zob#DGzTReaxmBuD2qOluNPvXMPcTwYKB8x%#p$v->?3+Q#!s+Rx?LlCnw^!kR){X? z>2}nIAUto)Ryoc^{wM&2A_WRV{ZTAZqBsB1dDo3MG z1saDM(PT6QO-0ktbTk9aL=T~d(QLF3Ekci?#pnt2BwCJEpq1!(v>G*|wP-Wif?h(e zp!d;1^Z`1AK13g(!{}pl1RX^u(P!u!I*%@(uh7@%8*~-jL_cDG9Dqewj3qb_2Vp4= z#xktHU2rt+iF;usj>9@^#ECcu=i&i)AkM@2cnB`WCAbt@a5b*Mwb+U$;EC9V>+mG( z#Ep0|o{1mA596otGW-mF7B9yu@JhT2KZl>ktMMA#gq!hNybiyNx8hgut9TcF5AVkZ z@cZ~6{s14sC-EtK8lSBMwp zdN942evFFAWU`oSCWpyo1~3DeJZ2CxmZ@OIF=l2wQ^`~@7N(l9GY+PnnZ?Xz<}h=a zdCYv~5oQ6ika>c6l6i)CmRZNVz^rFBFdLbdnKzi-%)889<{&*Ae&&;39U(DYuVlgXW1KAF2N4682z#3R1o5&`y$!rRn%BHa*e}?x*>BkI*dN%R*f@DFuV31(2pj1#++SA@(vzt<+@a7&0?64Ov=aj<4YkC=$hNLLE^j)ER}NE~qQ&hPtB&A|!sq zp9ByQ5fcdsBte@{6zYMZQBTwh^+tVAU(}CCNib<7Q^^AI5_y@tLS7|$AS=^pF;A>_ zSnY0CMy1=@Xm(qwDrDi=mTGf@&7D(abvvBJZisc|I-I4$@?E33Y?k86T1%Y;D&QZ7 zHQ2K)F1OWgcEjSXkg4*`E_arruHI&W3XABPce$a*e6dWk%TmP^w7RDbv(!7BFciVQ zQ5kNvS2-rTfC@g8;dGkqHPD*fooyN4P?Kk`c0l%Giw)$5rK%-+r(u>#$ivg@tBjH? z@(o}DN<=Zu$bgJQM&!*X2_=&dGMWyAazv%0$`S{&G}!8nYhOoPk)_7$YH$@h8l07u zEXY?OGqlT}XLnni)iAS}4OUx~#d&W9#W0Ff$2-izDBMHwg)Wsy+Qfpl7n za!@WBK*C7^8BFvi(IDWp!6+XMK?RiC#>1eEf?ub_27}yaA&7(#MTN{$ZM9jF;^X5> zT`!b-3cIEG~1k)uE)}5}F}{rsrC0 z)_M!f7p>tRqO%;(Tf4i=YMC78nry9hpFl&=FjS06%J~&wH`iH4@Ii~Kw4fN~pc#@& zM-&tnazejt-$ru%=vX0}{lDFhV&E1_HgHi5us7e6wuFu42+dCtmpo=P zkqUtEs1j8n3#vvns1{k#1k#0cCEZAO5HqyC`xml zy~;Ah;u>4!-7@km_8NCB-}WjrYYpiu$20h*)}W@*1;yD`5aSNJ*$M5fL8UU#VtD3R zhc?i5UO?-Kmgw5FQ(6rjyuSsyre8)|D`cSs#X}n0W|*zky4OMy)b6YMRrDrh%-7KC z=nb?DZAUxMPP7Z{CI(_8i6n_6lN6Fl(uipj+T&%+chO$755oINx|cDtNe&qZ;k^IP zn9evCthE0LV;-Z7d7NbU81ocm%+u%${gOchINy#SkrpTpG4g({5H9x>>5cnwJc0WHPmKEKBEJ0b zSdC(uu!@Xn!WvT1PU*o0ZvP!yAzSjltr$@CG|pD_pN)Qz_|^Qu6FvQ}F` zWvh_M`7{vQMNUVf6%w%v!T-6;IvSsi|Su=gQU4ScVamvt|v^ zN1KkdAFe5Q8VYH`Q_18eJe^D-sxffpC;*Ka<`}dLn9>KU-M*R$UWh_AVGo{#XX80| zE}n-3T{$*u4b{tl3_hA4uRPaqE1WwlE|>#ZOa3ym(`u#@rf8ct z-%;s31cva@8PvYxhO-**Z-vYo$=91}uCv;vR>;EIRxku~E*pQ!x`znhd{~KamXU>8 z>uVi$i_2Qq0H+~`Q>~5Dz?tx#*a}%%RinF#n{wqnX-OH0*@=mn#$08#K3AvIB^oo7 z8QJ;_Wv($xugT5G(Wpd3(w-z_l)q$qQPkphahMsX@h&$a^q_CbcHzakq zFR8@pwpn0l$vlz}xV4yn{SWo+iu5bEKJU_R+f=zfI|V6Ys%qk;UW*^5k0l z4t^K!B}>RtWGSV$_kAt2Bd^G5bvWVJULouMpEG8fD<>9P>dj6%KNYfm|2a3`Mw!{x zV2Mr-;FnA#itNRp$p5+|KEy}v>(o(v3?^Y2d4^6xbUI%l8X8&3ozQ*5aTcGuujF}r z0be95$V#$`mXz^Dhb8@YI=;kL@2l+^{uX~no+qmbCk(v0zqe;6@J%GaKjNS0`M%2R zHW$h}%pdQwonnR+2>m>>{-w=S7UdrhEDP__wRfNX`UHb9Dls)Dcfi2B!s4>>F*SB) zjH&<>p+ zVD)NNgb@J|Hh1gAm^!mOml`gO)$(JT|U4x1hMhGR3XTgmcOXao>J1aBSsU zX)WJ|^iD)X$&FR%)+*!Td6U>$wMI*VI2#z48ae@SC6vn2yiyk&Q(FpihaH+g32hS_ z=_`qYP6RVnnx9!9$PWaEFNE3 zWvPbdhSS{u=%iv0q$)@}?g5ykm>Nf6i-5ESP`2tg4&ov+RVYgpsg|)|>WDa1Yn>pT zXd6&hQc#?i4F;yXtSqRP+c#t)FokqK;SkqPf++8zlGh?6uQk`#+Zf=kI#8bm49gff zVq|%w|9S8-bOeKL911p9y6Q8Eit;G~+JP{h5!?R%^$hqk;P0f8*3~xUUxbBVajS%U z@4|O#m8-H2A)JDc|JBNRryC(rPl%76?5?Nbfe=RAiW-F() zGI9Xe6e0(hVF!uS#AzZyb)85`X@C|fLEFKKMaX|l^Dswgs8zKB! zr8%eA8~(P@T2=tzbcC25_3q4J5FP~K@eLD8Gawub;Vsq9+)@aqLHLu}hJiG!Lx}A# zt+r%1gu6p{kbQhXA%v44TwCeNDu-}i2shVS^5{Iln6V#P-FYPthW6MSPRB5sKL#N| zN|hx$hmRLjPjn2XG{C`E@P@0gn8tH7Ppi$MbV6H#GZV~%iXaRENbrlrHh|`bdW7Ni z?jl+zJPWh!wgTF2I)s;5TwH(QS$M`>TSDhdgOFbjx3h$n1={>ds;#+s5YC10lv?LN z8V~*Td%NDo@fnPX-(6?JFxq$Mqkpc&UP{N1@&z$Fa|S>d#>#&WD#K>5_&LD#X94S< z9Zu|#$OX2)MlMu?%y48jL!1WkYtR75Wrwd5a=5@~7zvg_CwQ@Z>GYYFpk?YI#R0ZN zE0_!iw8Tbo7Dm1tt-}Fd`b6u!%GF!xZ7&Ym%j*6DYJl`wFbde=eKFL5zbfWA6- z&VtwmNUMQx+g3EdM;h?pQCfK#XgY1>nzt1Pl&Ip`;>*!qQtKzJ(+c^fK^mov>$#w# zKqb(^H(8J`NEN6cegM>C29KbUi%;R=e66 z+WoC7+s#{HTfX2prRqMufVPAugvW#zg{M#?{C+7sExZb$bHelR`Lu|J z!>m+urIo-jtyJF2QBd2#8GAaR$TN?=dk95tk?s1RrFW611v^Kd3_Lia+Wtg%ef`+= zGwxXGTT|&gSmqb}T7YK7s$NlDSFKZRQT?pC*qTFiR`tE=w5kbGzGI(aw}Fpw7kC>F zqeyt#4gSVmTxbh;ANR1Ywv=nn;rtl1=Wxnzm0pgfBjon-R9oI}yT<8w`9_Q8_s!IV zf8f`)97AX9-%-?dM)_6eTNC{3aH~!lEmceXr7=>yG((D|QSi}7(;*Zs?IF#Vc7)V{ z(mv8`X_uDq7{JXVrGsCgR_>RsmsTk@5>kDfK>Jq*JT>*N3Z{>z!Y=-$1`y6zQj?@qY1sgCLwpbGbpshW!R*IqIi6tu?joNN_~iERlKk z%DC7_jY8`YU;9)x}#%IQM5!{N#XXCogcpg%(JlLP~9qciNP(Xd-9p;rc!40~n{ z=m3SN1dT*vp&zv{lTH}f8OQ_flSP2dcp8uytI;~N37iYBfeT>|cnIDHJjOAwVV{Hj z=8dJep!4#d|v#sL?Y=SNt6tgSS3XA ztmGBR2a?N@-vdJeV*;}RM+Y_pJ|4Is@ZG>q1Ah(*3hEt{9#kIW4thLjQ_y=s7lVG2 zhDzh4dD1HB!_t+~?a~v{8^NOBUcni`V}qv!FAIJ>_-OETnMl@KmL)UG9+It;?UJ39 z-I9mO)$&4lo%~Vxi}FMAt0Dd&y+d+BszT<3tPOcD7Kiko2}VY;xguqk0H!`=$J)Pe2LyF*?FTZhFRUh8nC!yg^HbA0Zd%Ns=IGlDkxPS=i;ZE}wN}y2f-J)^&Q4 z?r(R$77-ee7GaH88u3oVw~=9y8IiWgXCwDV-i+!RH883nswwJ7)SVuEdX)B<)njXq z3(?|eV{~=&(&&BBH+x3(9MW?}&&@qQ>m}-C>{Z+AnO+Bb-R|9|_we5Hd++FdwNIx$ zd3~n!+1%%R-=MyxzLWYk_dV6mub;8s#D359I~K#l=woVQR>mCd&-72|Z|(nF|KqX3 z*u+?SY;){cWuP)c*{IyCyd2jdEW>#@jc_q1Jc1|6l9;BY7 z-mU&g6Qilrtkj&+25ED(4{LX7f7JEYS#;0qKGBEjhv?_)_v!ykFeEq=UQW1X=xG>d zSYn0z&*Pl_dFUCNcz9;xQk zrqoMmk!j=7)}&oBMVZW|X44nx(dkv`>(jr<=$A1eV@t-3OjV{cb6e)^tfZ`&S?^}E z*#oi{W*^B3$tlfQk#jM(M{Z5-=G>bD^aG|3cz2+1;NXEz4m_LJEw3_fQ{K%%hCwq2 z?H?RCxOni2!C&OZ;*dtQDI);Q-v3b`V>tndUL4X(4wI$ zhkiXwJ#5CXgTrt-V0^s1#**DR@)C6;fhQ>&L$U#&^4d8+1Gt*Lfd z?R9IGb%piE2?Hmro^X3&;lvFS|F#XcZLJHa8&|i>9%7$p-|y(|nBq8I-@krd{iR7s zlb)V*(>d6=-i2LbTsz$gIA9)b=-V*2;c{bIz{bpM3 zv=^oerdLkiHzR6>XU65388e$6!VisqXy3!p56^k{EAR_$^oTtZJs;0f%~~?+m)XN- z@1E0b4w-Xh?trxJb2V*`m9TRzCXS zW9rAAeeCbYs~^r2-MPHy@+X$xT~WK@^vcYYTUT{mwP4ll=c=AN@qGI8FR$*ldeQ1X z)>zkk(lnrHdvovRWo!M`Hm?18UD>*WFBo6gv_5?OqV<1nuy44uaoEQFn+%&az1a1| z#haPU4V$lR8NKD$OW7~&d|CN&)7B1K7rlaBX?W$^SI512=C#4E?R(w$`pa+hdSlhL z&}|F1KNJCE-gv}@n)GGcQE7NJ0GNeu;)kn`HSpV_1BMC>gA2l4^c`WhR?&B%P-#%eFvG-*5$@fp?o%-l>!Rg~?O3!?9 zcJ$dxpHzKv^;6rYKYrHu*`0F)l=y`gWEYlQ?0T{J^M0Riy_9h2t;^Y$4}Veo#knh$ zSHAnw_2u2K=6oIW^|EgwzS(qDb9K+P+-t|a9rf*3-_?J2=lZL|WCg1hH z`|O|n{@nf7;J?oQUHA9jq#KxiT<$R~cBX8wYOZxP6o4^^1|fCwly>Hx=BWkko*~Ed z8DP5MY(LG@sp09NhdG;2i?OYWw_7$7Fg<~-=-znn0~8bwwoCVfX+pGwUSYwwbcSZW(vSJ=A#9mg*=T`fd;Y_^p7_H#;^-;4R4`$Knpp7J_QZr z8fYJXVn4utN7ZbzinKaNn3Yg){Xl5dyEhjTGm?g|IW+fmhUuE_) zhnQo`Nx)Hl&HN1dM;IU`yRzNcNVW&tpH%^RG7Zp@nQS&-C5I~BQoN(suQ;JNqqv~> zLh*y*C&k}kg0R4_;4np4zp&V_jId(Z7f10L8-w{@=zqJvurZ{GLzUoP@U44h6QX`a zrQQkkS<-*Qe^W2uoA?iW2fu~?#D9T%VJ%rlo+K}j_3QCF3}zV6w=jdj)v$qVBrn4M z4bA@^40C38q*|Ax)$@76m=5>aUYRh82azgd=7m^%>epw1EXQIj1D+1fiW;f@;Z5gY$Myr4ziQ%+Q1|+$xI5P1=TzX)sfxg zO%Kk2927kY9^0`nzC7GA*9pdYaIet_AF8#)Jid)G~Z@UrQ0z~|bw0>0{sg5qI-M|3zT;)nx*QNaNSFyG`_{-H(AbH&#Iq=1We zICYD2Ftg!ScWp5k>}?iE0bhJeKS~@9+jz4x&zF(+y|t~RO;U&H(^avNI>XG^$mwd0 z5yA$oYUWJu5}=0%6tj`ZXNJH^E@X?7}OL{Ur`Ec6k~ zNTwXZqhVQvVr^YIy{#CX5J;%Co!bInMzf z6$;LBfSQ77xW1MH%hp(&qp8>5_fR2=rJaA^oPjsRT4Sdb6@w3o19-NQQtGxsoYmr@ z{%Rg7NOSr+U&BlQXf0FASjhqMelufbY~+1%kaot4Zm?9fkY6E-YzLohNr(f<&I28M z^-f}@Ql@n>F2>C?FpVG@r;rcGA@U*lh#V##lOr3LX{e5w0W4d`Jj@Vs6gc%5eEX44 z$wi)Ly<7nJU~pD<1^SD#hEUFGaOGMlN&q+`$4=P|pwASjoinB047j_hJh!FJRRY)# zKo>$Zk1zJ&YVR*fnK^qZpkJ+(UX1Jjr=y`B*bp`|o4Fo9&zVyxN*8u0N`x1{%r`)% zrDYu25s+!Ab~r69&GFe4951RUD{2ht*vJH}zLgUfF^>VpfO(W0Z(<%NCn)}$HpqEb zT^U@DeB-->Sqf5yd5WBDVxA_a=zRTW00Og|c^)t?%nI0?Rx!_!)8q^}OFp3y+y^4~ zkG`lv*6qPqhSEG5Prca>P6yA}gA=%7KGHWan_GIhg?vU-zJ#sJt1W$cjhv&fA`Sw{ zY-4uNgjM8h6SI??Z%ufUd5b3OAs3pM6+l0X0$@n~6ZD7K$Lw!u{Q&vAwe=5}Lp=1u z*Xm&g+|y0W$K-MobCi5RE01abE+}$Zsx3|@Kv-d4s)1FTGX-$f^m0sIwu=|&CpqEn ztLO~#DP3b{nNP@<*RZKV=XfTB;y?roKo@w zAY`D*R`=&<`qV0~W$;KT8)B}pTip#+;6k3nt1@09S%&qyul`~b#fr##Q2&oa6`ekR z99P6wB8ZjWTY?RN5(@G&l=y|NCn|eeL?RW0(dqT+?JDWa_CYZ(vEghNP}aJEx)uQn zTNJ2l(QHq)7u%csN^XQ*1?7^%DONiQo13j3!wEKB*FnyGHa5oRu0!whyK(9)G^lzC95W2kB9s(CTtYFyV zQUK0D5h(fQsg4E^jv8Lr3^7l!)`1J0x@ZC9;{se2fO0CR?D8^$wAs+k@q>_&z2p0VXT+U_T=DV1IyS0cAYVfVykXqNCV~`$~@k zMj7wHBFYhBpU`hRw$bUM-{p7|&Q0DK&$m>&OB} z&*{AJxO14VHgVj3;=xi*#bxVQJ6um`DbUP1P-)u;-#ATToxFTJ%{H)&NWxBLr?6Am zY3y`%2BM0NZ-ey#$;P&>eM$+Jqt0x#w?)~Y8{gH z3%i-!Osk{H*T2foPv}cO;lEGhOi5Y}&aa0L0?gCp0n+hK5adI0+j zBh~{hWl&}rY_(T`fdTr!ug-yRxefMj5GdTH8|=$d!6)-AzD-+v$AhEcw8rj(p?r_s z562Dgp1{Q`@2xd&MYOyJ_w-=RC+z#+PWXU51o=N?KVlEFAG1f;qwF#EIQuai^^Cy! zzNu)}dkUrkJ%b`b=<$gjq5;25S*iW#fo2F(=WcVg19pBpckJ-4jC=FT+ojTW+A;%_ z_R-U-&a_~iJy_+zaULA+!M!{fMiijmMBY{qoMF%Mg20279^BivZuucRPgmgu_9FW^ zd&z_QcrXaM7!U5>x(cuGtlanCEjr(#__qt?CSQB(|6rkbmqdjurqWRtM`1&7$&g~5 z+uRn^!m-D9KQL}YUZzh{{=xo@LjDE19MqA2BV7dkf&lONhP&3;hS{10BD#jSv(LS0 z+?o_f1c9)Fw(Li3IlfsCL<>JS(c2e6us{K)27yc<7la5ve(F3}@4*QkY*;4<6Les( zppyq1JvfzY@L&_skDwb9)$2xbdlLs#4=l?enStLq7(J)=4l_^Yk4u0xY@g~qwG~%7 zs9h?uT_Pp37;dw+;u7g0r(G7VcDfvWw8jhQB?tj5jI<`?1fqZ-Iq2#xhs}HFqdoTJ zP7oM#s@SxPN4qbc3^pA}P z0Bcez4_AfhQAHZ{k<{W6nUJW7RKbUPFc=JxWneB!(!jp{PvD zupKxi=VikJg1figo6fD801?UHayCb(UUi~lr_SLI0&c<@E+}qQc}w$h?DX;>Xt8ie zwAd>x&7HfnfH_Zg>mD2t6-`Z&_gq46iX@Vz9&pt=^klEz!F~GnERsFm49b)quMsL537b8~b$eU3gOGb4AD z*A8Y>sb)gYlyP9>Y+GTovdc-8I#{FC!9E4ZPi~-iGWf99ju_ECt!))t4g%M;NeC>Z z2V3A^o?6WzUdx=pFq4vGOazkJw%cs%0@2AS;B;uc&e)vXWvpt7p?bWwy1LS0sH~zE zlY5*9pUZ;NGcvQXIZ!o)-xd@W4INfoQd~A1P!Xd>j{!4zn@+*paL9aE%)p|20&mx} zIN_xM)Iv$mQjjgr1-b-SkW2IOvSEhv;AmlmEA$j;l~#E^YE{ws3x4Hs9<3XFb;rP>@$OrDb#q8tAnog24ps7a$^x z2*B3@B9;XcAyL4K3_LsT@tqW+QV#dB6!03y02BBF_(uN59dIWc4tK|*abK*3Yf)nW zjbX+0cnV-K=E6;t1%SwS3@?TESnP+lSA2j!1o-=(;2Dqu4x=Cqf{Jt!-u-Zv{gge&$tu+1?HJ2H`~I^RNz?rkeq1n0FuIgGC323V&Hx|nkMsc4 zG%-g34)O)_Ef_8C!iy|eR>+EhI4LV*`@rieMzMByL4^}uQPBuzn`!I}fQJx(hds?c z1FxxA2`{Qx%{H-X*%#Oi?A!2iimUA30u8`@%mSC-alvB2DnXNAt>6X0i-IkJmj$l~ zE(ybheS~pBl~5zp36q7XLX$8G?Z@~@{Nw-@iSUc{i}O?Y zY5aEj9q>EocgXJ}fQO9sclb~8clkH?PxhbcKiz+(|HJ+s|E2!R{Gat-;lIlNdH*&3 z&Hn5B*ZXhuKj8mmKtMoDKv94bU?bZCP6b>DxD@b3z?T8v2mBiFTfiRycLV+sArT`I zh=N36qHs|cQBRRtlprz!ti&YB5M_ySL_WHt5r!b3qq^t_S@PbQhp;tW+o! zO9Q1+sZ1Injg`g&NKPkBkQ${q(g6UM87#dd{a*U3^f&1r(!0{Xg8czBBMA-)4i1(F zD*-%H6HI~^1TPGJGAZp&jo)O{A2K6a7loX31oh<0GU|UQPx@3 zMb=FgA&Zhl%X-OFvJ_dFY^LlP*^9E*Wfx`N$i9_bm)(&4F87oB%LC+M0N+H)qvgHi zedRIoSb37XSUyhfk~hdF%cshx%V)|TmV4y0<#XlF%2&u&$)A_6kvGfN$=Ay_0$68@ ze7k(F{4@FYA%c+3A#owOAr&DFA@f5%2ss*ZCggI+jgVU*w?lppxf9BS3PSxt146~2 zsi7l6CxuQ6of|qobV2B%(8od-hdvqleCP|I8$vgQZVr7d^o`K%p*ur&hh9<06{(6` z#Slfc!ljs|n4x$`K@{^93jp}@m}0TwS;Y#)8h`-3q1dk2so1U9t9VawKygrU2wbA4 z6*m-j!WeLe`h^96LsT9X8WtATF)T8yPnasq*#Eu$2l^lBf4={f{@?b$9V>|Siw%es z#|FkqV`Z`3Vk2UsVxwbw#rBEq7u!F!D7GPXb?l+ok77^7o{#-1_M6z7vA1LIDkVyV zGFlmaY~@_#eB}b=BIRSs z70OKj$$3e+Rr#v&b>%kY4(0pG50oD&KUN-99#@`Jo>rb!ejV2*ZdjZhzSrE;{G|Csi?xiF)e5yC+AwWL zZMe3pw!1b{J6M~qEzpkAj?<3UR%xx;iP}1?Lpxu)NxNOUOZ%qwZSA|-ecDUf@3l9z zKWT4iZ)<P)&^-9X(SUB0eBH(F=a&Ct!&EzvF4 zt<*iITdiBK+o*d{w?+4|ZijBa?jzmDx}&<|x=(bU>CWpe>MrSi*4@>M^gZ>x^?mg* z`dEFOUZvOQb@~LoQJ<_&(`V>M>nrr*^;P;B{RF*DZ`V)KyY!9vsrniEhxA0hRKG)i zU4J_vJfUwwa>Cezx`d|^HYe;&xSsHP!rg?w4A>wr_!)u?3PVRjxS^||pMhRn)fo~D zsfKhzrXj~Lz%bNMZm2QX4fO`6!EKmsc*sBuvkh|%&luJiwi$L9_8UGid}p{}xNT&O z0RY#EGWIY=8+#d(j6;m0jSk}?J)2=Eya;CDdnLQPs;3+c_|xG-bmS=vNPq)ln+uq zOgWr#H06BC=P8#{zD)TuRh$}_8k{OmO-mh|T9R6pIwG|^b#$sFwIhjcAQn#fZPCcFaed-#a zPkS08OxsQGnLacfHXSh?Go3YkW;$>B l+;rLWt?B3NSF>NwK9K!k_A#&O!|=a?F+Qb-|II$}e*hVlcgp|( delta 3480 zcmZ`*30zdw8vnj~=5p`cdoBzEh`1mMt^{rf3doLvC?FuX;|QaS3Mh=CmCl!$nY&J# znknF()$94nm#voO>$R9mW@cul*`nEMr9FFRX2h-c?)-lD%suD)&-s7*w{sm{i(VOG z!cDl@JuIY~%Lxjo5Cp*x0-d1?bcJrv9eO}C^oD+r3~7)BIgkhWPzb}J0xH1{lVCDb zfdi(%RJaH3g}E>fTtILitcNFI18jswXo6?1jCt5B9}4 zOoWdy3Da>97UFOmgJW?bR$(31<6NAFi|`>_j4N>!uExi44L*Sz-3O%<7D7pG3(HAp z4^dkn6k0coZ=q2v_u-}O;UdmIhZpx$GqYN&x) zm<}_bjyg~Tb)-%dNn*h%u(O~+yysA7fvliu;$2Jr<8rgIvnw6W+PZXMkaCMfd>2>M zHssr8IVRhjweB@N#OkLYgdcgg)o{P+sk0XseZ@)Y%Lgr_Nv{L3wYS*0b#(*@g7 zhrJ=!X|JyLnd3Q#Yl6SSF6u|gWVDce0rr5k8Fs@z;YEt41nS=mF9{;A&;W63qKJh2 zxY%){Zs;m9%`pKykI$~Du)oRUD=o(zfOr0K+`B@m_i3OYo=QpOmH=^9mVM&P$&>9~ z&8zOm5+VXDBEmm{;iarh5hgFg{KM??u3 zny&v;-{_u_^o)x{F7*ELeWO=UG*DPD_=dJ`Ik^b~KxprOuKBQmXf3yd+=(rA+A5|t zVUP!W%VM&Rvv>8n_Amt7K-4B|g`wCQ!)Q1aQ8ATl!nW8B+haJ5pwTpz#tHw+NEz4z zJ7W*e_Ab~JyJ2@Kr7{{xqc#a^ul6Rz6roXHLVP-9o)!CHf^b!gr!kGNS}ggyQ&QWy zFd0)?JQ!1H{PjeF8NypJ6SJtCY&Xn@gE8+;_rg{XiTQ$TFioJO$g~FXx@U__MOgY5 zM5sWF62b-3M3)!R>o&+ZEWg2M0#&v!s(`p=tVBCbB0Ehc$4yoatiJOOk%=O4y2wGn zG|6+t4DSuX$GvGDojBWv7;;P4RSU>HB6$T1;s#ME zVk>Pgyhq7LA4O zC26B#f?Ih`m};L>KU$2n-da;%>Z?wTL8LZ@h>~VG(mE`#P1|Q3T9rGT2q)XSpZryvhtr@AZLH-orF3so@9nmqi zrznKJ!h0PQ8+ACMWA8q9_v!_qnF2WDax)`j(Ei7c1px!5pPzzW%LR?JFRDI3W~v$1SEo4_Xe z+)NU=$NQ9AAFmJ0PNEoy1_B$gY23}qFHGJnrkWwCRMdR&C9-sWah`pSy)wP7qRKJL zUUvw$;MNf$T{!LJLeUL|i5QO--CrW4VhZzFZF~pc!-IGdPu-CJEBr=Mq%bL7%8@FhyQK%E#nMt~g|tfO;0bAi)F?GeJEh&y z>(W8#m~=`yFMZGaT+Co?Sfo%$H`aqCu>NcSOJZ3pn+?9Mm9fmmCbC*Kj}e>C7O;hE z5nIfbvUO}d+rS!GGuzCzvhD0CwufCcbus0bW|)?lwwd;t-Zy<>`qcE9>2uQ;rgNtA zrk_ohO~0A0nEo(blR=hbiySGtie$SyTV5hREL)oe9Q4T04l(Wi3 z<+5^BRn-7BPz_Q;)OKpP8liSlqttjcK}}OfsAcLXb&`6wx=dZ6u2R>kThyo2-ReGd zzxtN?FZGamR6V91SI?;z)bG^q)gRU0)vM}%)IZH=Hq4Rce&!T&x;fLFZO%74%u~(P zX4i7_4)gow)8=cMRSVaWwG=H)%h0m4L0XPBL>sD&(57iKv_;w~ZM*i2_Lg=;JE@)0 zPHShhv)V=NlJx1=NJx?#uOZAcZXnm|cUcXmgqra?w zsGrf#>F4!t^b7iTT;c&PZsox|l!x)QJc@Vc(L9Ft#E Date: Fri, 14 Feb 2020 14:55:14 -0300 Subject: [PATCH 03/25] add gitignore swift --- .gitignore | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fce96a3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,78 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData/ + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata/ + +## Other +*.moved-aside +*.xccheckout +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ +# +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ \ No newline at end of file From 1fdaa2565452525bd26fd1b004610c7353216076 Mon Sep 17 00:00:00 2001 From: felipe Date: Sun, 16 Feb 2020 21:00:08 -0300 Subject: [PATCH 04/25] add clean architeture struct and setup navigation controller --- .../project.pbxproj | 62 ++++++++++++++--- .../UserInterfaceState.xcuserstate | Bin 19884 -> 27976 bytes .../TesteArenaFelipePerius/AppDelegate.swift | 26 ++++--- .../ic_menu.imageset/Contents.json | 23 +++++++ .../ic_menu.imageset/menu5.png | Bin 0 -> 1305 bytes .../ic_menu.imageset/menu5@2x.png | Bin 0 -> 1472 bytes .../ic_menu.imageset/menu5@3x.png | Bin 0 -> 1589 bytes .../TesteArenaFelipePerius/ContentView.swift | 21 ------ .../TesteArenaFelipePerius/Info.plist | 19 +----- .../SceneDelegate.swift | 64 ------------------ .../HomeViewController+ExtensionNavBar.swift | 28 ++++++++ .../Scenes/Home/HomeViewController.swift | 17 +++++ .../Base.lproj/LaunchScreen.storyboard | 0 .../View/Storyboard/Home.storyboard | 49 ++++++++++++++ 14 files changed, 188 insertions(+), 121 deletions(-) create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/Contents.json create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/menu5.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/menu5@2x.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/menu5@3x.png delete mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/ContentView.swift delete mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/SceneDelegate.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController+ExtensionNavBar.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController.swift rename TesteArenaFelipePerius/TesteArenaFelipePerius/{ => View/Storyboard}/Base.lproj/LaunchScreen.storyboard (100%) create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Home.storyboard diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj index 2d225a8..67f2c14 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj @@ -8,13 +8,14 @@ /* Begin PBXBuildFile section */ 2F7B7C3423F711C7006D73D2 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3323F711C7006D73D2 /* AppDelegate.swift */; }; - 2F7B7C3623F711C7006D73D2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3523F711C7006D73D2 /* SceneDelegate.swift */; }; - 2F7B7C3823F711C7006D73D2 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3723F711C7006D73D2 /* ContentView.swift */; }; 2F7B7C3A23F711C9006D73D2 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3923F711C9006D73D2 /* Assets.xcassets */; }; 2F7B7C3D23F711C9006D73D2 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3C23F711C9006D73D2 /* Preview Assets.xcassets */; }; 2F7B7C4023F711C9006D73D2 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3E23F711C9006D73D2 /* LaunchScreen.storyboard */; }; 2F7B7C4B23F711C9006D73D2 /* TesteArenaFelipePeriusTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C4A23F711C9006D73D2 /* TesteArenaFelipePeriusTests.swift */; }; 2F7B7C5623F711C9006D73D2 /* TesteArenaFelipePeriusUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C5523F711C9006D73D2 /* TesteArenaFelipePeriusUITests.swift */; }; + 2F7B7C6923FA0220006D73D2 /* HomeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C6723FA0220006D73D2 /* HomeViewController.swift */; }; + 2F7B7C6D23FA0275006D73D2 /* Home.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2F7B7C6C23FA0275006D73D2 /* Home.storyboard */; }; + 2F7B7C6F23FA07B2006D73D2 /* HomeViewController+ExtensionNavBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C6E23FA07B2006D73D2 /* HomeViewController+ExtensionNavBar.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -37,8 +38,6 @@ /* Begin PBXFileReference section */ 2F7B7C3023F711C7006D73D2 /* TesteArenaFelipePerius.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TesteArenaFelipePerius.app; sourceTree = BUILT_PRODUCTS_DIR; }; 2F7B7C3323F711C7006D73D2 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 2F7B7C3523F711C7006D73D2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; - 2F7B7C3723F711C7006D73D2 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; 2F7B7C3923F711C9006D73D2 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 2F7B7C3C23F711C9006D73D2 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; 2F7B7C3F23F711C9006D73D2 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; @@ -49,6 +48,9 @@ 2F7B7C5123F711C9006D73D2 /* TesteArenaFelipePeriusUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = TesteArenaFelipePeriusUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 2F7B7C5523F711C9006D73D2 /* TesteArenaFelipePeriusUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TesteArenaFelipePeriusUITests.swift; sourceTree = ""; }; 2F7B7C5723F711C9006D73D2 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 2F7B7C6723FA0220006D73D2 /* HomeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeViewController.swift; sourceTree = ""; }; + 2F7B7C6C23FA0275006D73D2 /* Home.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = Home.storyboard; sourceTree = ""; }; + 2F7B7C6E23FA07B2006D73D2 /* HomeViewController+ExtensionNavBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "HomeViewController+ExtensionNavBar.swift"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -99,11 +101,10 @@ 2F7B7C3223F711C7006D73D2 /* TesteArenaFelipePerius */ = { isa = PBXGroup; children = ( + 2F7B7C6423FA00FD006D73D2 /* View */, + 2F7B7C6323FA00E9006D73D2 /* Scenes */, 2F7B7C3323F711C7006D73D2 /* AppDelegate.swift */, - 2F7B7C3523F711C7006D73D2 /* SceneDelegate.swift */, - 2F7B7C3723F711C7006D73D2 /* ContentView.swift */, 2F7B7C3923F711C9006D73D2 /* Assets.xcassets */, - 2F7B7C3E23F711C9006D73D2 /* LaunchScreen.storyboard */, 2F7B7C4123F711C9006D73D2 /* Info.plist */, 2F7B7C3B23F711C9006D73D2 /* Preview Content */, ); @@ -136,6 +137,48 @@ path = TesteArenaFelipePeriusUITests; sourceTree = ""; }; + 2F7B7C6323FA00E9006D73D2 /* Scenes */ = { + isa = PBXGroup; + children = ( + 2F7B7C6623FA01CD006D73D2 /* PullRequestList */, + 2F7B7C6523FA01C8006D73D2 /* Home */, + ); + path = Scenes; + sourceTree = ""; + }; + 2F7B7C6423FA00FD006D73D2 /* View */ = { + isa = PBXGroup; + children = ( + 2F7B7C6B23FA0246006D73D2 /* Storyboard */, + ); + path = View; + sourceTree = ""; + }; + 2F7B7C6523FA01C8006D73D2 /* Home */ = { + isa = PBXGroup; + children = ( + 2F7B7C6723FA0220006D73D2 /* HomeViewController.swift */, + 2F7B7C6E23FA07B2006D73D2 /* HomeViewController+ExtensionNavBar.swift */, + ); + path = Home; + sourceTree = ""; + }; + 2F7B7C6623FA01CD006D73D2 /* PullRequestList */ = { + isa = PBXGroup; + children = ( + ); + path = PullRequestList; + sourceTree = ""; + }; + 2F7B7C6B23FA0246006D73D2 /* Storyboard */ = { + isa = PBXGroup; + children = ( + 2F7B7C3E23F711C9006D73D2 /* LaunchScreen.storyboard */, + 2F7B7C6C23FA0275006D73D2 /* Home.storyboard */, + ); + path = Storyboard; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -241,6 +284,7 @@ buildActionMask = 2147483647; files = ( 2F7B7C4023F711C9006D73D2 /* LaunchScreen.storyboard in Resources */, + 2F7B7C6D23FA0275006D73D2 /* Home.storyboard in Resources */, 2F7B7C3D23F711C9006D73D2 /* Preview Assets.xcassets in Resources */, 2F7B7C3A23F711C9006D73D2 /* Assets.xcassets in Resources */, ); @@ -268,8 +312,8 @@ buildActionMask = 2147483647; files = ( 2F7B7C3423F711C7006D73D2 /* AppDelegate.swift in Sources */, - 2F7B7C3623F711C7006D73D2 /* SceneDelegate.swift in Sources */, - 2F7B7C3823F711C7006D73D2 /* ContentView.swift in Sources */, + 2F7B7C6F23FA07B2006D73D2 /* HomeViewController+ExtensionNavBar.swift in Sources */, + 2F7B7C6923FA0220006D73D2 /* HomeViewController.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcuserdata/feperius.xcuserdatad/UserInterfaceState.xcuserstate b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcuserdata/feperius.xcuserdatad/UserInterfaceState.xcuserstate index 68741089fffaeccc899abfe8833fe80b96470f29..fda16150ec8b540c8404e58bebad264173543cca 100644 GIT binary patch delta 14496 zcmbVy2YeGp6YuTa-r2^MC0XuW#g;qng>FkOk}X-5Tx3y}~64K8%hUTC3&CLr`+ zOb-xB2njWigb*Nf2q8e|p@kX(2?=?7l5Ox8zVE%?gWp+qyF0u4pPikVot=$Kz~PHv zwg+ThGJjY#9&$U6Ety0Xkxk?fDnd=<5~V~L(U<5?3?c>-wZu@OfoLQ~5u=IO z#2jKSVI}4f^N9t-hr~i+5wVO|MXV;)5bKEz#K**T;!|P=@j3AYv4_}8d_x=}z9o(j zSBY!Hb>aqblek6PCVnCA5O;}RiQkCl#P7sw;vYa*fFp1MK_D22fdoi_41|DCAO~R} z3M7C;kOaDdZlF8J205S)C#Ip_x}KqWAP{$KzY4C+8VXaHluI4~Ye22;Q?upE2@ zR)8k35;TKVU^Q3+Hh`^Q8`utZgFRp`*ar@QZ^8HA6gUkmm%wFk1^f(dfSceBxDOtJ zr{Ed*1N;qMlP)BWbS3$ufE1E$q=@t){YWV(BcsS@GKTC(#*#^78rhvxkV;ZV7La<< zKo*ilvXrbKD@ilipBzNikhP?RL?lbTM@}Fol9R~E

r`Ig6Z4E+to3$R=_%xrW?8 zeoTHsZXx%Od&w`!L*#k#2l4`WnY=>&Ox_@Gl8?#X$mirM%9(PZc$6FENqJFHDx6BA zI#Hde?oPPA#^%Hf8x=dZ6ex|Nc*Qo2%4eBO! zi@HtyLfxUBQqQR0sOQw*&;dF^C)fcxLl?+{UeFu*Kwl_>AutrmVH}Ky2`~kAhPf~g zYM>V8Lme!HCC~^4eo-w;U0J#o`5IeDR>&5foI`4cphGYm*EX~6Fz{y!iVrB`~&_;lQcy;(=N0d z?M(;LGCG2erQ_%nx-*?lXV5BIOT9uh2i! zSLvJd9r^+NJN<$o8HVY=@E8FjWV{$ZCWw(Tawd|AVxoI7NlY@6!gOJJFiJ+t|%B^dzihj|n~TwF;;yUM%orfe#D9S&+v94GZ#FphI1)YpJIx zU5SV_L<*5gq!FEn&O{d^Ktkk(M93X^tRcD)-H9GVI*~yrkSCgs7NJkjG4wa4-2&q+ za$`kpr8!2W%*?H7h{>$1YN)MK)>bqQG1oN2=&Gyg8|-Cef)sm8+usCTUF{%qMT4Pn z=+N4_f6=vTQznRQH-@UF!CcqByuzH(SXFKP8;U5SD#LmecCwTS!rHa`kJ+Tx*P9y@ z&-p!Z=KoNhjwCokawA2g7r8v)Vi7xWuGR>iGD-{ zQE8G@RF~J+*OU)28||;=`Xa5NNT0V7SDTGmLw-MwBX9R#g$U$>{K^FLxc*WM73Laq zeaD>IA!gg3;wtk9MQu$(U2S!>xh|%DL{JiAD&VEj-f`{x)bA}W)zGeCJ_oV+ZYTpT98 zD-(#c22Eo_dB1A&o1U6+74ECGr=!F>)CNY%>Jha6KM5s$eCsZp-& zi50jC99yUIg80+Uv_CM@G#seEFw?XswUto~dFGk{4FiQh)j|RQfHpn=3iCntHi=c} z>RHeMxMOg@8Mpu*a0PrI07BpfL`aVes1OyQVpM{Rs1%vj1CLg4z?TCD0#MI3aAh`d z{cQ3Q2P_~QV*?SWR|_@}jj@3k(2;vkZ`8;3#0q!WCHOK{dKm)WOALu{<&?7VIj|QNDs0s~2gHbga zvK|!Lp#dW(wL$BJYFeNTLv=Q2jcw2da?q+!Z7Z~D4%!f62KS($xH0#{3f!bUg4>Ba zXapne2uEOq_1ttvV}uR=Mo6_vF=pg@c7!ZOIGiJKXrZw|d>_o^AWj9-z;rMJd;n&G zSztDpgGQoJXfzsw#-ed(JhC9P9#~r-eh3zVMR@g=AhreKL^KJ#kKd=ZL0rp0T!-Fk zh4?WCaU)(m{GbVV^|&Wi5H9T@X%F#Ju+t9lGYoMuH{UNX#3}!V=r}_lZC%Fw;GiAk z0St25O2Vm)iUTP>42}>HP2f8;qX`^EGuv4KaMGsxJ}486=2WRgRnxyVW+-R)T01`j zejp;6!C7z)oJX_JY&54CTmV0Ui)b#IhZb_XF%a9&GF_g^P*|3!R2Amy%M6)$nTkSH zzP2nkv-DjJGL5=)t)Z%^uu!Bvj0*N_#(mI*wIRC(o% zH5CI5*l3UHS6g0Jsm1om-tZRqr3u_d^U;U)@4MjM3beqc_`n13Yo9i)WmB=u-~p#( zPZI;MUIUN7W2_ikw3@-((2Pr-5N2%e@JE@zeax8HsNmRfQNd$U5>ums6JnFbjceuB zZ{T;1*U!=7Ch!6+ZO`k!Y`k7lCK!czU2BOM$vGcGu`kg|{SQfFdrlH0AW4!UAzFr( zqmR%E)U=vpNC(o9bRs*Tm8co5LaWhcj`z{+ybZh0psOx|1G6#EKQDt4#(-Z!A2d4_bp_&yxORfQ1Ys zoXH?E82m*_O6zU2#M3Hms2XCfZzvx!v}cR)Y`|^~T8Gx6C1{g0{lMRFZtwgZtz(3c zVMN4AGL)2~^=QLNGMtP+AES+^Yq1?ou^mU5;9v8kYwNHOTLliD7Mom>ab$d%AfO%4 z|KwRSnLs8I=KotWY?hV9h5t$1I^|?C#m<)20(mF03zk~4GuqNbc17FTNiCUSliICi zg1MZAF#K<4D`sR>zt(OuNi`9%ip(Oj$sAIJwxdtc4)ob7GMCIFRiqZ}L|>rK(3jX1 z7xDuggH#zgqx#iVS@Ze60-;@K@N!@o9$r;xHS>eJlSSMD7NgHmtf?wV6RoR@&Kg|U zI+}^>gY^{Ilk7$IM!V2%w5ORYBm0u&XfN7__Ty1z@O{1T_ElwI#td%nep>hQ{VlCM z4Il@$=g(lW+Fl^-QPoaelS9c7`1C;zBkRa|vVm+Qhob}NAo>b@jlMyL){rB~QRHZH z3^|sVg1$wE(Rb(wI*KhtSCgr>c1Tuv1y)@>75K1WuG3jl1r3%Tp9O#Z*F6usGsdJP z#-t_1rzXe8rp2Zv$6-x_-(r#z@M~IZLR?B>LPGL5yJWxL#+X(NGsq8GrriBx`zg;M z7jUaGm$Z`e$oc4dbON11XI7CPk_*X25^^y*hpwUf=(qMl@R3ajj+Y5O;DjKdNY(L; z*0s6wG4*X)_$^PJTxFv>Stgjp(Is(Q|9_-hZ=*b2CRo8y^4g7P-Rl}6Y&*%2n{7?c zT60~OMvz;{&+Jl{Lw;(Lx*g~|Cv`iq%zZ)bLO)=cyMTVg@{rCC#XAq5qsVkj?d^d;wqNxAHAqrA7#ZV5E zBi;|U(J#ny2i-;YxD6rgeok~g=7(>wsBkPwNWv_Nk4uS5O-jKmipA0&oe-ZKlNgtn z9G{e!l9rm9l$dDe5ar5o=qK_b=Fepm+rkS_R-Tekq3;AtMNo176L370KqXR1R5Awq5IsVV(Npxyj`xE5b%n(vipA&t zF>z^W9NxsV*dz=+J}xOSDmXDYE+#fD4e$5FxVU({=~G+acEL+Sbwy9`(!|E8qpOET z*A{D9QKwTG{{?jxmHRIVu-JD-PfAPW+fYA8zrR7PrwZSV+DMiCPt<*>a;hIyK~-YZ zFVIW$2YQA6vZKB+QS6u@n8<;SPl~bN^-N7kj!nQ$RBB>Ma#S$>iAhR~Zz)d1tKEWn z5Qlm&`tzNrYpJ3C1$6^89Alsw(d#B^1Ph3EYK`hJ)}}iCDHB+*mKkQ@Vl4I8FT<`9 zere^Yg?gWeSVtj>rQV|^P!p+1)MRQ33jhm97EmmJETCDyu)u)@j_atY)HG^3HG}$q znn}%~X0yPF1sz!6!U7%(Tv@uVe9 zD$HCl_LBsa=7#dB>NoL{GJ*HdI&*(>U7fkoU~8F&efE;7%7%fx>np0ODynJ*M3>i@ z%Q3CJr)bWpZz`qf3 zvA`L9h&`E@j#U+9I7HSMQ#GV~fElw2J0z+Mm7*m)m2dCut?-VtNA;IBGt|n`)zljM zg0&W`r#>bkEKSq~76_WCjVusy?BSb74lT!_3_E+2_4b)< z?O4fq=_Wg;I8?1&e@=bTeylyzKEkbu+RFm3CTc$myisazd;rmwTjPac<0zVe`vmk&4fh-7OK`;x%ERd|HP7q>Z3U!(~L!G70 zQRfLo#1#%XI;i6RQM&V0Kq9P$h5u1>RtwDk!I#Cgq8J!xNnI4^z zsZb^*$7Lj?rY9GVOieCJPAsm{4Xmv(o9sVv@lkQD$nH|VVxNb)N8P6$upoj3kt~R6 zrXEs{sK+dbWMrbY?*pY_Y#{k4lGOFzQ{6 zqhSohQ|rcp?kwoRY5kUfSp^XsLK4BJVItuSlVI}pSP!eGg$3z0!GWnTt#{jLPl@BJ z&A6x&VJ^n8G5poS1K0&Bu*$#-0!yOf20%T5&8{3u~!H@EuVAo?}0;Gxib#5f=Xf^cu}T!Dumd8n6!b#)6(K=*5CRaZ7Ai@J2&j`(WOdRMk}0j>xJjAF};cG#?n@ zhj0bf-EbjX1Q)|4a4B2{m&1=((3=H)SWw1-zAV7p>BoW!7F4by#Be2ShO6LexCXzk zLs(s#S@1p!X0c!{3+8bJO;{AWb=)2Zw?ph}u7sb$9W3b2f&nYx4){6#Wx+t)#5uN` z2JVI5Z~*tg{qRe803L*2!LM0R#ezXB7|eod77SrQ4GU`5!b8Lqc$f<^!K3gP3x;ya zV;Ba8f3Ubt#yw7tedZ2-fInjG1uw9mt_fabK|R(ev*Uc+;T3olFF5>}1r1H`8Vhj5 z&8l$^4uZGf9d4Sp;V�&Vmu#>pk1+NYquwwXwiQ@EP7!@G-7>%7Rh0+R@GMH~jrO z3&z;K$Kg}0{rFeNIr6Pr;}v{u@BVLFtFc`7w{5S(QP)B);NQ}chO~pNCC%8X$G5e# z0Nm8{=19>>z@zzXSZM(Z5K3*W64Cf@--4F*WC7dex6nScA6JFZj%cE>wtnwTRS+%a zsxZXSO|*ms6YNzMEcBKja#`+XT?^-9FN~g6mMRXUs8`rT5R=87}=2YMz`a$plFp>F=xi2D zXTb~>e87U4XhE4E*%l;-X?K@YX|Ch$uv9hmLvgsJwhr53^8g$ei%D;2sH^JN*kHzf zMB@J|p@pMV+1!zaQE%?B-oCv0uLByYM&k&Dv}Gv!)!M(Ol~q;UCKp<|0LulPPwQAP zn+0=l2orAuPV_N1Y7^2$w2?M(e8QT*+JsM6_)KLzm=I#2%jj~h9B<4VrSvj- zISW>@pqT}$Sg@J}Ygn+B1?yO_o&_6N@G%QEvS1SnHgBR=&`rb)x|v?ZDN%YYeqT>- zpg-mm>L)DNiPBhr71$S?LS?~j?sE@zX-~1>4!0KDQBpmy(0k~8Z@Yk?J=@PJ6@fke`xC<_RZ?h z7cdB{0(Wq;{S2jIhY|OoH1}&9Fu+{L`GC?M^@MdvN`MP}jlPcUTRyRezG3}3C0w)1 zW?ku9^lg0qX}d1dl{XArN&iA{7ou$itvmNFjnB{AY4RNXEBz2_i%0Zh`U(A%en$UB zKeu*DHSmtHU>^%kvS2R@j#?L`rda5g#L{*2AM~H}EBY_`Z~8U;4@0m3v+Mv14zd6< z>JSUQWx-(>B)XfiW>XnO;n9T;7K% zWBSrjOh2ZAsbtLXDfaL>TL*RCV!>;SxptEUKeFI9wu#uybAL;~nL*58PQVGQkg!96 zcN!<%D9xr$nW4ne)yy!aj;UuFm_`<0iMzyt%PhFUf}gQ(__lntiBoH-O>VOP{{`oL zyWm{42@ZB)d^I*<2_RQ7Gl^aZ&+|IM*Ub1nhnd67{nx_S)@3DQ<(BhZv2v@hYodi& zz$_u$xCnOpSR%939y4RXt(Kr!s+}V%+k$5Hk=HP5xqx%4TFb#FaBNpOi?oti#|{0? zIy>zK#`1BQz~euO4GrZLgI6*eIqG*;wrDJ7GqWAXdzep{EzDMC8w>8T06Ts6S@2*L z^C`0f@A{oA_>~3N7sBg+v3+1pu;3ZCHnM zCAJuA1`Fx)7Q4axgzW}%iNT_Sea)9|cEeTXW}Di7qxG3j2r=^u2E^Ho7o24s(ay3m z_nAlUAWLDkU^>&U5}fh&5&HW1Tc@YT(N3rXa<(2wPwW&dmPp@~VuPXy-+=3&SwOjWd=@|-TW>$8NO0CM%X!CUidV}?O#z|)aLF6FdBN_>Oyc8@K{ z&$zzed-9X`-T3Kz1wWIo<(KeF`91l)`DOfaeg)smuj7y4kK&KvBmR5*iTug@`TT|a z)%*?ojr`60?ff15o%}EOhxzCDclh`C5BLxHmdE_3{NMP$^I!7+#Mw7|flwe4cnG`% zJ_0{MfFMX97IYKz7O;Y5!FPiDLcTCYs1X(mONBj!y@maSwZdV-dSRn*gm9E_jBuQA znsAnIj?gMxC|oRDDqJqyB-|q0D?BLtT6jo!RQSE{gz%K`s_<7g!i{u;Zj76w#jS&z zi<_&Pz|GAq#7*uN?iT45?bgvP&Mm<$$t}e#&8^t2(QT32ZntY9N+cI$iOixJ(J)cH zs8KXtG(|L3G+p$8XqIS>$SPVYS})ox+9KK}+9~=%v|F@SbWC(YbV+ngbVGDYbWij^ z^icFz^pCrXdyu=>UFsg4~a*XhuLGI#|Iv>J?47M^H}Dw#$%nw29J#%n?1I8Z1dRdaoFQ~j}soJ zJkEPu@VMx4$>YAqLyyNEe|wUi(3A0W_T+i;J%ygZp3$DMp7EYZo++Mb7SAlt98a}p zp67R-=RGfb{_J_p^M>a=&j+3lJs*2M^%8j{dX;$f^{VhPdkyeHUQ@khc+K>h?X}2j zvDZ?s)n1=^?e_ZG>y+08uPa{9y-9D{+rhhow~M!{x1V=_caXQ(dztqJ?;YMdy}$6@ z?Y-A~zxNUEW8TNTPkNvBKI?tn$HMp|`BeDK_1W!n&gY)b3!j%hfB3xeg}x5HPQK2* z{=T8UvA$h=yZQF;&G1$FYJ5$;WxnOU6}|&~2l-a}*7!F1j`f}6yTNz6?-}2VzJK}& z`~v&}{et|&eldP=ehGfbeyM(){IdO2ez|@czw3UF{9gL~>Gzl4Yk$Ju$=})H&-3T| z3;jj@9sLXZ&Hm&4r}$6vpW#2#f06$h|4sg%_;2;!?!U`_kN-aZFZ~btU-Ewzzz^^b z2nYxa2o8u2hzaNz5EsxXAUmKipg6!7U<&9J&?lg8z>t92fMEgk0gVA80!9Ul378x( zH(+DHnSfsdi9n~o_`uGA-2!_AW&~RD19gD~frh|dfmMNZfenGf14jmq4xA7;DR4^Q z)WGS19|SHATpGAMa79pTP}iXDLFqw?pmRajgKh@h4!RROJ$Pa8;^3vh%f$)e9%7X^ zSF91|iwndiaW8QnabIyiaiw^g*eaeUULbB3uMw{ke=Oc4{zSY-{GIry_Agl4MGBlHQU&k}^rTWRPTp1WDeL zOq5KPyf2v}u}bDkK9nqyERn2|td*>nd@T7)@|EO}X|KX_a)av_Z;Br%7i>XG&*F z=Sr7Imq|a8Hc6YMtEJndJES|MyQF)h`=m#u7o-=Zm!wyuSEbjbH>FRc&!o?#FQk7+ zUrGO#{v&ggCCIwSy35jK3Yk{cQ`Sq?TUI6;C~K6Bmm%4EvWXViWZ5j)9GO)%U-qGF zk!+1@z3gMzX4w|mHramJG1+n1N!e-HS=o8n1=%gxFS5I``?6nUk7Q3|&t!jv$U|a7 z5<-$fQbIC9@)gd(@!$KNDhKEcDnG`Z5WNN5$sCQ_1XjEv&(D=}# z(A3b*q1{5$L-nDSqEKUK&(J=h<)M|K140LdR)A`DFR~^2PFI`5O6p`9}F>`A+#B`M2`3 z@^kX@@(c1?@;mbT@`v&#@@HWn%r{IP)+wxOSdTD8Se7MB6_yv4AEpm03L6+UIBZB* zZCG7cW7x>BF=6AwP}qB6Gr~R$+Y8h#?U}BkCe75tAdPM$Cwq6|o>< zQN+@Sk0P2Pjzm~qM#>_iBNHPvk*3J<$jZn8k%JpaiToz=aOAbfhmp@CUq-%)d>utcIYv20xkd@1e4>J*!lU9c z_GIkOIGk}l<8sE$j3*hd6+i(M4vG#6oXwsEAV(E5;~RD^4g* zDK09mEAA^EDqbjFD=DR$(p?##3|2~%GG&}HQJJhvQ+82yQ)VmG$~>i3S)w#5P09-8 zNabkdSmk&ntDK;mq@1Fhs+_L;KsigfRJmNaLfM>|kl7 z&m5j<8I?IU(~`+%PRN{;IVE#J<_}q9mMlw?Rh2a{YgyKYtle4rvJPZ@o%Lu%PAtVdZ-vz}+Y$oezuuWWv{Bs(cPH`|y!C3|u9y6hdRsurq6YF~AbI!YaR}As@&?_+T6O_hTMg@O}QI#H|1`zAIP^`MQO=#kys>k96yG+jRSNhjicR zj_FS5&g*{E{iM61yQ+JtdsQGPa4QHZNGQlEP!;G4`V>?Y)E0~_7*{a902RzHSXZ#K z;7Gykg1ZF|3LX_aEqJb%>tprldZj*FuhwhyI=w+(tS{B~)K}_9=q;o5WA&5tv-R`! zEA;F28}*y@JN3Ktd-aF)=k!e?w}@PFmKz5dS>t5mGUFQKKI2!$pNw~mPmI4AUl{*1{$0wHI+ePV@=M)H-Ae;X<)!hZ z>e7Q?;qqRA(Ax8fzMFVoeiFGfaz2D@@I%HKz5ZEvD_J m9j4DsyG&o1j+MEV3CpBqVP!Ebr%KZP%LxB!cd8`HV*d}(SqohN delta 8153 zcma(#2Y6J))^ld=W_#ZxbP_^I+0FKB$rchqFc3lsp+g8{fnZ1=S$f%75D<~(q6i|8 zgkEg42v`u1rqV$L6x4@^f(R-_#D8{^An5zQ@8y0scXnpZnbXgibNEZx@)|6P=D2=b z|In5G?T8Yx7k7vcxRD2WQ4Z>cx})BxKN^4v(GWBqO+XXTBs3XKK~vE*G#v%dO!NYp zhh9Vr(IT`MEkn!EYiK1}g{n~v+KjfKt>`WEF*<|}qa)}jI)*+$pQ6vuadaAei7udv z=o0!5x{AI>*U&BW3-CbzLJ$Q&3=)un4CJ5y4K#%WXbo*Z2dQ8IJ2;>tWJ4!-267-5 zx&dQ~8?YYie7p{QoUC_F0TxscPBt#-4MiLatVY}!%)DW7&%~8cB8^FF5zS1Ip$#@?{G@5D(6~WL+ z{+Q4Xp;CAX^*}vQKI#=3Bxu$$9~Jb?%kMUHly8{-No4&ZfU%*^__Jf4oF5#SZ`^<| zO5C_d5qcISZ$v}UFjS0uXgC^yMxqiliZ-RqXmi?vwxn@1p0=V18&N459eKu}v8aNL z{IoSqiag0Qg&Nt&M6KK66-Edkie^-yAZ2Q8cL<%|``-gb!|^$X|mvUqUY%Df8u& z75gUoDhC&r4;wey7mAb0d@In5)ihBFQ|nGxjj9IbGY5AX@Y=~u?Z^LyPi#m4zpQN z_pqIHPhvfh&=- zA{dHB(=l``t)PB7j;Yfcn$mnu;M?co1(}NH3KfY{%xS3xo2lV3rkT^UaaOxI)n+o8 zjTVE&k!CR1ZPV(QD+}wroL17r{sv=bUFjHIdGD?b994oJC9hshtqI-}4b;{VI}s)$ zRTWI46RKbeok+nDy3;PTCs23+sWw6oX248%4rak@m;=wlTsoOfp;PHJI-Le6r9nDl zBg{kb%qADWLRbWg;UyGLXHpqs=s7xz&Zcwd^X!))G$Zj|>kLPh!;xvv)@508Fd-YaxzrVUsjR7sD@4bjtY9Sn9P1P@OTgY3ftZucmRLEd+;YbVw~2{HFPmuOV_P~ z4=`Yi3HuL>>-BU4-NgQ{XVe-yR0XgUiLngJ!^zZNGTN7rvG0%PZy)6a>Ba~ZScz42 z2l}e95)};YRbE^)DXz#LXS6uY*1A2>IA-u;N+TJm21kc;lHz*AQgLIbtwJ(N9%}|S z$1Rz|p#Yn#!g2IX%22U-0w+A)S@*jg)UKwR>&D3}u7RPxJQ!40Akc=mhK-n&8SAkL zo3RC3aT>N^JKaXN(;ajt-9>BZyX&zNr(+j3v(U=Sm+q!}q(SJ&wj@Q2*Sc*^$L7!( zcfq|-@&=rXyW%|D4R^;qa8I01_tN+1`}70)A>BtmqWd?Xc-$NJ!F_Q*+@FmHG8_l! zW%@0>O0Ti;Z%o1uv$r+DBk(9z|KO3hgdU_HSK|^~N??*cm;l)o~7sL zdHQ*HBJ!|_y2skRP|-ZJI3|W)kkiXo>8}heZqk?(Dw>Ap0+E?|JH#9D=EnqVpzZdr4_reQ%>7^>XoKeD3L2Pc(xUyj* z^M_UVd}XPX{_=`RLqqy_N%}|lz~f^N(y#wM_AowD7XTZM`vfyDufm_wD^>V7{f3Fc z-z6y#pN?2q!=`iii?FiJMnMWjT4Xw$|P~pq?n=pulQCwXqA|gxVVXGrom?p+C}F^!DH8|0}+SR5kcF{5!r&f1)?& z%^KX58POli#$@zoro9DSJ-rAfQUBVOkK&1t?q}P6p@xL^bB08sdp-R`N|gVEASwo- zp?4U>uMBZ=UP6F0Chbu2R?>ttCCx~4(t@-kaU`C!A_=55X+zr5-|1a?kKU&b=pXbU z{gXbTe+2;rfu#q$l_ZiRR6$aRHta`4&&Eb#BFwLXK!PBq#vn+7AY~^e1wkJEsR%;z zAefmfnKHMX%Nq*;l0~u`q((Xgfvb-Jq%+i3lP)AT2)rN&9t(|hBl-X0trz31cMzhe zEC_sR=$Dh#v14%wGY^)epO(x3Quq|Kn#r6DVdM`Df-p>{hzaL%cTLK`4U8iJi{`VDPdm!ze}Wo2qi(#gry%{sA%zD9H_jg zqBt%wlii_`>UdZ{78WX+F&So53>#T8KAd>+{S_r4L%x_-O%|boP_z6vSKWztFZzhg zqnGG241YZpctw~B7D~crHc+-aJQswduchcnN2q>FgVComORKC zK~~u|Q~=~{vV&=zyu*xqdk|XE`$34SAv+mKwLw<+GCEr^wa+SW^dawup+5*h0?Rk# zBSztVa-dMrXxO-l3RZX4S=BQokphi|a~hT;IR&TWR2=g;OAxF#pZ)4o1JaxNAjIXCACLPn5XnHsE}%iuab72{Zl;}j^K zV=ih5N65@@#+dL_T;y`O?*D>OGMN0J0jy!5tO!u|NKlNFs$3tq-A&2u9y+F!xr4!Q z1~B1xQ64YrN+!lc^94eYSR$20$24o5oTAlR(`-(6sM!FW^r<8s${SD|P-}X(9#&dZ zS=o0&Nm+6Egq$p<(lP9U#}G58`#YRbp@L5Zy$kd5omRuC*hY<;^sfUfD;n+VTQ~Go zGONnV@BSFPAg5#5u<~MGaZlfHA9LbizUszJ|L*@ZZ^6l1#wUbMYSqfBI4Z7cMdeg| zx=mYoyTqi>*8_|^31vAf6g|+=JhqW8mDRX)^+#P^sMa+-Z7|ABW=m-1KrfH=wx}v} zXrL)2wvpYz_V$TzRKM5Wlo6fodb*#I-Za#DQ0o@$Gcr45b@stIKb)&#nt0#wO*yGzhUbb|F`e`f83zaR!0 zK@)btPk=-)v-|ZRcIhmEF))!`=w`9Y++3Ik^I-{VogQHQ(!=cD^9%gRE(c213vJ5k z<$ibo9>jW{6Ina+W!B1EkGJ4=@m|)xyo4XI2Bn52elu%JW_D-kc`zA8rjfa171>0# zk&nm$771A#WKl321CO)#cbYXD&yz36g^1}O40T^Lxc*!JAz#s|kg`x6;0AC53z&QQ zeH4%YHAbya3bG<6^5WyHdHM~$&I+c7tXWD3kBAsOGNK^uSW9#ODPuj*3f2W3&vNNx zGL>~hDG9MY=u*}ReU0@(SCJ}GL)Mb@=oET|8Nv?2j=~jC}F9vTsToUOZbBDMd32x zO5ti@wQ#*~qj0lut8km}BjGXO72!4EZz6$6B$9|^B85mL3TQ+zqDG=7BArMtGK$P1 ztH>sDh|)!Fkyn%<8Z4S7suJxN{U8>L_2NA7Xz_UQB=HpSH1TZlLh)j8Nc^&Rsd$b>eN}TJdi2UhzKhe(^!^A@Mo!7vc-zYvLQ?pT)n3e;3~qKM+5Zh$W3ADH5GT zFEL8Y0f|*&lQ<;l61Swgq^G2pq_?E6q`zdKWUyq2WT>QA5|pf#9FSa zMbc%`71EW`)zXd9ccj~;JEgVK-O|0%Bht^LC#0vO=cQjrFGw#*f0F(zeJBGNk?~|A znM5X&DP%2WTA5yElv!kHGP|s!tdlH|BkLl&EW085U3O3QK=x4fNY0lF zxuT^aUXh?^qcA93ir$K8ilvH8ifxLo6yGbZD}GYkRNPlaDfvo)QWQ|Cm2t`hWgBIp zGFhorI+gj#A<9bSIOPQ8B;^$4G-W^;RL)e+QogEOu3Vv9sa&nBR<2R5Q*KahQf^W1 zRPIxLsl1`$RE<@ss%%xEYMg40>agm#>YVC|>Za;9)m_zn)gNlC=G0MYfm)Jn)#ZAnpZW;HLEpSHQO~iHMN@Enthu6nuD4{nj@N1nzNdlnm?j( zG#4EeEr^y!E2GuX(b2KdanbFf4bk?L{V4}iK1;b6NclG9ddgibr;XAIv?8rUE7K~p z&9yDH@!AA!8*Mvnk~T%#T{}*@N_#|mOnXLqQTre5_u5<9yV{33u}-5)&?W1%I;+mE zbLw2W99^z1PuD}2uPe|E))nc7>3q5}UAbgZoY20Zli9qZmTZv zrtWRsHr)>0F5Snv!@8roPj$z2Cv~TFXLaXwS5sMwEY+X-dg{BWXHsvZKG2KxQoUTS z)T{N;`dEEqeN(+wpQ<fsb^)9_f-$P%lpP-+wU#>r*zo@^izpH`7cMx$|vaf0zV;~e8$dT4ky-tud`L zZ7}UH)tYvj-ZOn*+Go08x@P*(bi;JZbldc+8O+#B%sjKo9Bqy@H!(Lew=id#yO?v$ zdFBD;A?BgxVsnZ4S@URfxp|Ixqj{(KUGpCE`{obLADJ(kZSzfceZdqknXW3xc zWZ7bQ!?MeAz;ev;spYukq~&wVmzIl`uPm1>cPtOBLThVlTWg{<*{ZdsS`Ai{)nZMv z+O6qUk2S+O&{}96YAv>ou#U2pTFb0st(DgC*1#m|RO@srwJx#lvi@Yfo7N;PF)cl9 zaN6j!P}=6SeQ7_X-A{X%_Q(b{&K6~p+cdUVTN7I|Taqo@v$fdLY;Ie7Tc)j}t&^>X zt-o!At;{yYR$=qorr4(2sBNZgmTjqRwQYxOm+gS8N$=ah!2naolj+b=-G6bUbqMoz0!CoOWl1 zv(!1(xx%^Dxxu;Fxz)Mb8QAAM;QZKm#CgJb+IiObx${fsRp-NWS$b@Gll124Ez=Xz zJEUi)=cJEHpPjxbeQ)}g={M6KxEi^dx>~s6U9Da1T*)r2E7jG(mF>!L<+{4Ldbs+# zhPj5jN?fI`a@SbbbXU+d(>2?*-nHGe(^c!*<2vj*>iWcW+;!3Qb-;DS^_}Zax5zDV z%iT)1$KA!<%iY`E*WKSe(Cu@NaF@8Bb&qzJyBE2ax!-c{aDU=H>%QT>?GbrmJ#n4{ zPg_rtN9(bA?4ERw+tc2Y>FMGr@C@-x^vv=s@GSN$@htT$_tbdSde(b3dNzBudX9On zdBxt=UZdCIonZ4iy)LiE+tXX<9qKLij_{81mU_o|Cwr%Psdt8Vq4yQ Bool { @@ -18,20 +19,25 @@ class AppDelegate: UIResponder, UIApplicationDelegate { return true } - // MARK: UISceneSession Lifecycle + 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 application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { - // Called when a new scene session is being created. - // Use this method to select a configuration to create the new scene with. - return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) + 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 application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { - // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + 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:. + } } - diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/Contents.json b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/Contents.json new file mode 100644 index 0000000..e69e037 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "menu5.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "menu5@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "menu5@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/menu5.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/menu5.png new file mode 100644 index 0000000000000000000000000000000000000000..78c46f27c0a7e109bbffd41172a632faa6484d22 GIT binary patch literal 1305 zcmeAS@N?(olHy`uVBq!ia0vp^DnKm7!3HGn7yNStQjEnx?oJHr&dIz4aySb-B8wRq zxP?KOkzv*x2?hoh(aeyDk_cZPtK|G#y~LFKq*T3%+ybC#1_ql7D* z7iAWdWaj57fXq!y$}cUkRZ;?31P4%e<`($+!mY|HhWZQWL;Z@x0)0b01O41weQY|5 zOM+4nj>M|7IHa;5RX-@TIKQ+gITff}8Jj`CfWz+qY??|k({NZ0k^#FL9wtC9+W;-` z^|f+IEy^rQO>ryA&jkleL1IyHD#($xN-$R<>jG&6d($d2uec;JFFDoI#SUnaUS?*B zm9eX%tD~EXlYyhTp`oFxg{8ThnX9>(k)ef!iMgwRxs5)CR+R9Enw*lKT$-DjR{}LT z1!1x?A(N4`B22c?$M7mRfkEOO77jQqb;WHd)LevCBugQ3o;X9vg^;mGT2YO)axO|u zEXgkl$O#ORFIyG1i)6kmpCY$c5v1z%=9X9UK^8;i-aQc_;i0R4&Kdv^povG5y_C Yqen}eKIw)R^n=PPPgg&ebxsLQ0HrODKL7v# literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/menu5@2x.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/menu5@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..9c99b9fbb28e11e8e8b03ae403d5800b7afb830d GIT binary patch literal 1472 zcmeAS@N?(olHy`uVBq!ia0vp^HbAV+!3HE%^j`-8DaPU;cPEB*=VV?2Ih+L^k;M!Q z+`=Ht$S`Y;1Oo$$Xl6)6NrbPDRdRl=USdjqQmS4>ZUIm=(6kCGATu|$BvGLvHz%*y zs=`(YtilS&1_|pcDS(xfWZNo5_y#CA=NF|anChA687SFtDJUq|6s4qD1-ZCEwF7y! zN*N_31y=g{<>lpi<;HsXMd|v6mX?IHV#HzD6q_QAYKPa_0zqBYh6{uVpn?b;U!|woWno2U$a99qK0lOO>CO|LS04?$L zwQ@-<$}CGwaVyHt1qVz)Vo`A_$dR^6Fjpe$0%-($(<(EsxFj(zIn~p}4rr2IW@d_& zv73RbrHiSdfup&hp`ojVlc|xTi-n_$sk4)ti>srdjXs7}l<&#az!Jp8)5S3)gZ1q! zN3KH-Jg(6jySVqxpLh6hg-Q9kJ1_jiZ;8qLmzJ1tDOKFmQ^7z?^WXo;XH=5s2JH$9 z-8yyqr>MM(lN{DQJs;Iztt-{7;coEN+g7I`@!%%Gy>|~89Wu<(h&gmK>)*dec?>lZ zgST+xu3q4IeX5Q4+Geqk4RL%4**jwl1W)RQ-deTlkhmBR3-dt-0|A~hvl?%-r|X_) zvFB?o7vA$cKhE)U!Ib6wAHybsgRxjB=7n zW$bwqX03i{O37K{wMHK|*u2wpde(W|`NZ8P28y+lcCWg$?ptE#>(h^P-g>`xkcL=j zpwD*a?cq5~zZZpXZ%=0|E44qP(|tOL|Ju|}_J*~*@7tJ+SYGJ*TedZPP8ZR87;{Wv nalFZ=0@eq+=PY{qXnsZfi=MdnADTIfK*g%3tDnm{r-UW|O1a{P literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/menu5@3x.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_menu.imageset/menu5@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..09c928331d0be8482baa918ab3aadd98fefe16e5 GIT binary patch literal 1589 zcmeAS@N?(olHy`uVBq!ia0vp^Za{3r!3HEB&RrV}q!^2X+?^QKos)S9vL>4nJ za0`PlBg3pY5)2G1qM0EPB@w}FfdWk9dNvV1jxdlMg3=B3ERzPNMYDuC(MQ%=B zu~mhw5?F;5kPQ;nS5g2gDap1~itr6kaLzAERWQ{v(KAr8<5EyiuqjGOvkG!?gK7uz zY?U%fN(!v>^~=l4^~#O)@{7{-4J|D#^$m>ljf`}GDs+o0^GXscbn}XpA%?)raY-#s zF3Kz@$;{7F0GXSZlwVq6tE2?72o9j`%q{TsgucqbT9jFqn&MWJp9>C{g2bZYRFETWm0+$!)&a|1_nLqkJX3r8~pV>ef40~bSAM+*Z(M;m<%ttjCSH8~|eximL5uLNpx z3c_RyLM9_=MVM@(kKt8t0)xamEF5rJ>WJG?sJRHONR~q6JaLASB_U&xw4xeobVo>!q`k;)1l#w906f6qNrgmIFn_yYqj_Y^QD^*|#veVPWF(iZa z?QCDa!v+Galg*YYOo(6zPd+&-xlncMSA{&>^W1M(!O2P}%IO{wAWfGhWzF)BX!a7k*vGTJ_w((`lFNXqOa?KQe zA^nOu`QDU6oAeL4M@a`oMz54L4l7^A9^h#pvprR5gEV6m&s}#lCM5+ZN>*M_dFIBt z8~a{+_b2YTE*AKE-FbmJ`wa;<9!goYN|a5=J;ay)Wd{2Ni{`KZsj?57+J4=BCTX!p z$fxs+p-MN4*q*6pf|E8DX&xM%sEFY2}&Ro!VUpIKIZ?q&9WQN#I+?NR|R zNAE{XM~QW&2aQ!`hfKb!*Z*#!*u+>lDq--fMojbgy3uwRXrWM?j7R%6-RrepEg_FMM(8P{sO z94t)U2L!RXa;aUo=&cZNAzDuH??mlBuZR6H``Om@iyx3Ud=*rdd%F6$taD0e0svNJ B3uyoV literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/ContentView.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/ContentView.swift deleted file mode 100644 index 6a278c0..0000000 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/ContentView.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// ContentView.swift -// TesteArenaFelipePerius -// -// Created by Felipe perius on 14/02/20. -// Copyright © 2020 Felipe Perius. All rights reserved. -// - -import SwiftUI - -struct ContentView: View { - var body: some View { - Text("Hello, World!") - } -} - -struct ContentView_Previews: PreviewProvider { - static var previews: some View { - ContentView() - } -} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist b/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist index 9742bf0..27cda5f 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist @@ -20,25 +20,10 @@ 1 LSRequiresIPhoneOS - UIApplicationSceneManifest - - UIApplicationSupportsMultipleScenes - - UISceneConfigurations - - UIWindowSceneSessionRoleApplication - - - UISceneConfigurationName - Default Configuration - UISceneDelegateClassName - $(PRODUCT_MODULE_NAME).SceneDelegate - - - - UILaunchStoryboardName LaunchScreen + UIMainStoryboardFile + Home UIRequiredDeviceCapabilities armv7 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/SceneDelegate.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/SceneDelegate.swift deleted file mode 100644 index e50987d..0000000 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/SceneDelegate.swift +++ /dev/null @@ -1,64 +0,0 @@ -// -// SceneDelegate.swift -// TesteArenaFelipePerius -// -// Created by Felipe perius on 14/02/20. -// Copyright © 2020 Felipe Perius. All rights reserved. -// - -import UIKit -import SwiftUI - -class SceneDelegate: UIResponder, UIWindowSceneDelegate { - - var window: UIWindow? - - - func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). - - // Create the SwiftUI view that provides the window contents. - let contentView = ContentView() - - // Use a UIHostingController as window root view controller. - if let windowScene = scene as? UIWindowScene { - let window = UIWindow(windowScene: windowScene) - window.rootViewController = UIHostingController(rootView: contentView) - self.window = window - window.makeKeyAndVisible() - } - } - - func sceneDidDisconnect(_ scene: UIScene) { - // Called as the scene is being released by the system. - // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). - } - - func sceneDidBecomeActive(_ scene: UIScene) { - // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. - } - - func sceneWillResignActive(_ scene: UIScene) { - // Called when the scene will move from an active state to an inactive state. - // This may occur due to temporary interruptions (ex. an incoming phone call). - } - - func sceneWillEnterForeground(_ scene: UIScene) { - // Called as the scene transitions from the background to the foreground. - // Use this method to undo the changes made on entering the background. - } - - func sceneDidEnterBackground(_ scene: UIScene) { - // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information - // to restore the scene back to its current state. - } - - -} - diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController+ExtensionNavBar.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController+ExtensionNavBar.swift new file mode 100644 index 0000000..1e0fbd6 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController+ExtensionNavBar.swift @@ -0,0 +1,28 @@ +// +// HomeViewController+ExtensionNavBar.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 16/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +extension HomeViewController { + + func setupNavigationBarItems() { + setupLeftNavItem() + setupTitle() + } + private func setupTitle() { + self.title = "GitHub JavaPop" + } + + + private func setupLeftNavItem() { + let menuButton = UIButton(type: .system) + menuButton.setImage(#imageLiteral(resourceName: "ic_menu").withRenderingMode(.alwaysOriginal), for: .normal) + menuButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34) + navigationItem.leftBarButtonItem = UIBarButtonItem(customView: menuButton) + } +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController.swift new file mode 100644 index 0000000..cdc811f --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController.swift @@ -0,0 +1,17 @@ +// +// HomeViewController.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 16/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +class HomeViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + setupNavigationBarItems() + } +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Base.lproj/LaunchScreen.storyboard b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Base.lproj/LaunchScreen.storyboard similarity index 100% rename from TesteArenaFelipePerius/TesteArenaFelipePerius/Base.lproj/LaunchScreen.storyboard rename to TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Base.lproj/LaunchScreen.storyboard diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Home.storyboard b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Home.storyboard new file mode 100644 index 0000000..03851b4 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Home.storyboard @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 0f4fc1bafe3d1927c5ae66996ced01d1d24bac83 Mon Sep 17 00:00:00 2001 From: felipe Date: Sun, 16 Feb 2020 23:02:50 -0300 Subject: [PATCH 05/25] implementation auto layout in cell --- .../project.pbxproj | 16 +++ .../UserInterfaceState.xcuserstate | Bin 27976 -> 30479 bytes .../ic_fork.imageset/Contents.json | 23 ++++ .../ic_fork.imageset/ic_fork.png | Bin 0 -> 1131 bytes .../ic_fork.imageset/ic_fork@2x.png | Bin 0 -> 3051 bytes .../ic_fork.imageset/ic_fork@3x.png | Bin 0 -> 5699 bytes .../ic_start_yellow.imageset/Contents.json | 23 ++++ .../ic_start_yellow.imageset/Star@2x.png | Bin 0 -> 3318 bytes .../ic_star_yellow@3x.png | Bin 0 -> 5286 bytes .../ic_start_yellow.png | Bin 0 -> 1558 bytes .../photo_user.imageset/Contents.json | 23 ++++ .../photo_user.imageset/photo_user.png | Bin 0 -> 1995 bytes .../photo_user.imageset/photo_user@2x.png | Bin 0 -> 3224 bytes .../photo_user.imageset/photo_user@3x.png | Bin 0 -> 3969 bytes .../View/Cells/RepositoryTableViewCell.swift | 24 ++++ .../View/Cells/RepositoryTableViewCell.xib | 116 ++++++++++++++++++ .../View/Storyboard/Home.storyboard | 12 ++ 17 files changed, 237 insertions(+) create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/Contents.json create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/ic_fork.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/ic_fork@2x.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/ic_fork@3x.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/Contents.json create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/Star@2x.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/ic_star_yellow@3x.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/ic_start_yellow.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/photo_user.imageset/Contents.json create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/photo_user.imageset/photo_user.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/photo_user.imageset/photo_user@2x.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/photo_user.imageset/photo_user@3x.png create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj index 67f2c14..28d0308 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + 2F5C380A23FA179C000985E2 /* RepositoryTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F5C380823FA179C000985E2 /* RepositoryTableViewCell.swift */; }; + 2F5C380B23FA179C000985E2 /* RepositoryTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2F5C380923FA179C000985E2 /* RepositoryTableViewCell.xib */; }; 2F7B7C3423F711C7006D73D2 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3323F711C7006D73D2 /* AppDelegate.swift */; }; 2F7B7C3A23F711C9006D73D2 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3923F711C9006D73D2 /* Assets.xcassets */; }; 2F7B7C3D23F711C9006D73D2 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2F7B7C3C23F711C9006D73D2 /* Preview Assets.xcassets */; }; @@ -36,6 +38,8 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 2F5C380823FA179C000985E2 /* RepositoryTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RepositoryTableViewCell.swift; sourceTree = ""; }; + 2F5C380923FA179C000985E2 /* RepositoryTableViewCell.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = RepositoryTableViewCell.xib; sourceTree = ""; }; 2F7B7C3023F711C7006D73D2 /* TesteArenaFelipePerius.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TesteArenaFelipePerius.app; sourceTree = BUILT_PRODUCTS_DIR; }; 2F7B7C3323F711C7006D73D2 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 2F7B7C3923F711C9006D73D2 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; @@ -149,6 +153,7 @@ 2F7B7C6423FA00FD006D73D2 /* View */ = { isa = PBXGroup; children = ( + 2F7B7C7023FA0F60006D73D2 /* Cells */, 2F7B7C6B23FA0246006D73D2 /* Storyboard */, ); path = View; @@ -179,6 +184,15 @@ path = Storyboard; sourceTree = ""; }; + 2F7B7C7023FA0F60006D73D2 /* Cells */ = { + isa = PBXGroup; + children = ( + 2F5C380823FA179C000985E2 /* RepositoryTableViewCell.swift */, + 2F5C380923FA179C000985E2 /* RepositoryTableViewCell.xib */, + ); + path = Cells; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -283,6 +297,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 2F5C380B23FA179C000985E2 /* RepositoryTableViewCell.xib in Resources */, 2F7B7C4023F711C9006D73D2 /* LaunchScreen.storyboard in Resources */, 2F7B7C6D23FA0275006D73D2 /* Home.storyboard in Resources */, 2F7B7C3D23F711C9006D73D2 /* Preview Assets.xcassets in Resources */, @@ -314,6 +329,7 @@ 2F7B7C3423F711C7006D73D2 /* AppDelegate.swift in Sources */, 2F7B7C6F23FA07B2006D73D2 /* HomeViewController+ExtensionNavBar.swift in Sources */, 2F7B7C6923FA0220006D73D2 /* HomeViewController.swift in Sources */, + 2F5C380A23FA179C000985E2 /* RepositoryTableViewCell.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcuserdata/feperius.xcuserdatad/UserInterfaceState.xcuserstate b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.xcworkspace/xcuserdata/feperius.xcuserdatad/UserInterfaceState.xcuserstate index fda16150ec8b540c8404e58bebad264173543cca..d4d7012495df589ad73a549a200c5aa4f858a474 100644 GIT binary patch delta 13754 zcmbVy2V7Iv+y6OtvI&78WPlI|F+d>T-diCu6A}m`Bp4AFinvG4(N?Y2s*QUCZtEUx zt##H~XWdoXYTZ>^M{U(wt^acqas1x)_r9M$e3IOI#&gg2S?4*=eZIK}r`?0oB@922 zpX9n?iKBxk-Hc92&KzI{`Je<;fx(~}3;{#IFfbg903*Rz-~{8rL@)__049Tvz{g-N zm49JmO+2e-i;a2Naneg*fy zeeeMM4xT~)A*7%W^o4%V9|kyKFl+!Lp%TVGHEaZ%z^1SnYz|w%Hn1)14%1*d)Wa-j zfJWF8I$$qY4tv82*a!B7{op`Y4Tr#?a2y;D--GYN3Gf5xf-~VPI2+D~i{W~>0d9nw z;AXf5ZiU<6cDMt60e8ba@F+Y1Pr|d%c@AEL-^0uBC-@8e6+WV9ilJD_hw`QTC=nGz zDX0i4hH6YTp_)>ysMb^)ssq)L%A|}`Ps%~{qWVyMsY+@fHJTbneN4Hinbcfr9<_*C zOs%IjQ(LG{sn4jL)R)v=Y9IAAb&xtj9i^^P*Qo2%4eBO!%SruA-KOqPcd7f-W9kX@ zl=_o~G)2=iLvu7w2ht)sh>oMxbR$|r$I}UPBCVy9=w!Mv-HL8ax1rn8UFmLgcRG#E zp>yfpbOqgq?o0Qh`_lvHN_rqYh#o?ZrpM6l(-Y{4^fY=py@FmzucBAeYv{GK^Ama< zy`J7cZ=rY4U(h@0ujm8xH}oO;Fnx+XP2Z;P(0A!y=wIo3^nLmP{gD2ReoVh$ScYSG zCXf*^DkhFmGmRJx6VD_tiHw#>Vp5rwOe>}})0yeQbY(J`EGCaJF=nPeGk~dN1~P+~ zDrPWK%?x3NI+-H}31{U>IU8r^%DA4KgX_hWbN#si++c1DHZ~@HFqs2lByus|LJ` zkK`NjF?=kq<5T#id`rG7-;M9ir}62$i8u54d;xFaOL+%h$q(cQ@uT?B{1|>b|DLM_ z(~h2uuDV7sA4s}kn2w@0IbA3Dfv)GVf!?P;0kD8VP~>BOKOEhmkh2PQdQ>YQ8Bo>LzTl;Pq`M#m%wH46S#u9psuJJ z>W{&ygP@qO>7ukv2N(h+uY~K7EewM)flfG-q5@P{3*}IOiqY_Q z(8FjqdW%)`F_G~Qm&jY{x-4TuUfVW|a}Ox8ie?K+U^Z1ah9z|(_A@vs*D-V3AAAOz;>`D zVH<3P%1~=dMU#xg?5f1BeU0_B+QCjl^I&_}0d_M7>IBA{6TP0$SUVF9$jLevlSM*~nL8i)q1fW@!`T45=) zK|88KgHbgaf`+1D($m190aRgJ*wRa&!fERyN1Eh0w;#U5pX0Ng+`!} zXcQW~432?g;V9yU$DpxjG{*Ih*H4}dKN6r%fgi%D$cYfbb#NM-PN0uN zWOJNPHg>`TlT#nvH6VOC734MSjuYfDzD!3Z1folok zDd38eBi-UII4N$goe5n&9qI%xQ!8hDsbX6^bwJpzFXhKie`!FeTLO9 zekc6$KbTVAvlo6X@MIs{55Iy3(8p*dnvLczg9qU^@DMzV=A-3kBl^5vVg22k4gA)v zkS^EKh>zb=(=+bYSys_Bx34NOMuxt%LqU&`&#{V@y1NS-rUboF@k{Qx^IVG?F4Vv) z@TNy)6XA8Y%9f%9g368|3VR#gA%e1@g=i5GRL>}tr5?&X_<(pAqL}41L@GoX>pOmj zfBjb-dk$Z~zu`*?fGD&WEkR3B9a@G02>Az5tphl)rQNqfnBK+>ksaPuEzv&8< zNNK4gDw)!em9Iu?&|0(}Z4g$jZ1>Zl=Mf|9Usy$&QHiO^Ews&2nl@?NRM#xEd2&ih z(}aeJjhn_c*6MVrsk)}ko9mi4OKqC!Q6;LGfVer;0)2wkc@R6>Qtkc)aVM(#zsRaR zrKfrj#16CxZGJ5cDvKh%;2*?9--HkP9{u3{v=)g(t(Ci9x$Al@ zd`7(h;#%r2>N&cMeyW9IsFy^)u8^aFzrUH$&%v&fL7};{n3fa3bTA!4OXyI#0Ubt%(^6W7enz*^9dsA{f__E! z(0%k^HLdUfrlaU+S_$oREPD6~@E_>!v#sz)uO_A0#pIoC^f!8mA;1t~NMT50$Y98>rc3JONS6t6q_LRkWek0UHIGN+ zAm>XkEe;Bo)05~a9!!(b4GjI?89-23=@~S!m>IH_O9K(hJvZzyd30 zkZq&43m*)n7|J}~1Y4j;T#xQcdXER)ZULR5mflP6!!QEFNOZNNXJy%t{*D3FJsbnd zt9!eZpZ?k%Bn81AL`*%6BlPib4+oA39Eg60h@hz@^cnh+z=E^%Ir=;LJbi(_NPkcN zKob$gU>J*`3d1-I)fhIyP=jGSh6$_b%dcg7-7VW&7$&}vZIVZ}T@pS7KDy@qdL7}>e>2dHodE*&WU_3A=oP`PBclB>I9$PaF&-;qh!tX( z`tAq;7!$;hcz-n`W`dazM#6+L4VW+{oFVLPf?-n(iBdJkumy%KF>HllYYf}0X5{t2 zm?!}lLwL~k4X}ECj1EMfAl8A;VcOHf&49ytkV^~0%t`?9)Lb;>b&{=P(7~G{_MR^4| z0+Hjbr+Ld#bp%v1V;D^0c4jQ&WDtgh7#3kzT*r)K#xw6>Sc2gw3@b=HcC%5xEM_t| zx}2H9e8@~?K4PX}XvL6tkUkg=z_1FnuV>1~%xrn-k#@=jt`I9z-;-av0IsK46)h181}=kKcTxb zKC$UeX3sy2g)5nT%ziWl!%7SXqWCh zFc-=9c{dA)z=mTu5<_x9j%!v?bXw;w9Y~&KXoagyr`gWyWI;EWn?lyAx}v{BIDvcF zRhPcUaD-=dKQp&I3vtvkKa+Hdv9hOaL_=G3!xUZ16=!*Q=p=q>*bfsXrx{)U3sL*YH)NF{mG z+`!X3;Z6R>@2y_Br*~3)@I@js$LqP^Z=n}uy%Hmj`j?arpL>8zgZL9R1V0EP=O z+>7Bi7!vLt6B>RX`u)7?mI$_hCC7nU*1{5-U4-G{TDF)a=DGw!lE`x%>(>}Qd(Cr%s)uxw{aJVl2_*K_u(vVXPXt=6*GP#| zS;pRD@3RlshZuf^;Q?up~3bpK?>@y4xVR)FtW#nKd z92(+X%X)MO<|vLK^f?+s;-sR8>BPI9_J|GPyg6T?-3P6CbvE+f1%Cjv+7 zxFAl<1!H&uLjwQ8Ysbcga#A3!;~H>b9Pu?LF(fQIUB}5l6sN%Oj9@%xiK>2-p>j2q5o zXMjUt$W7&5c{fttTdPjycb5vZVDSQGZ3R3P)9*dp*P|-TV4; z&q}v&TU~NPBwNdEBZ+XiAu881c^wf9adg`S0X(m#IM36#`JKj(JdGRPZshj68!6~+ zBu-Q&6H@rkU>tV{7*P?XXaqb9ILaM!?KOwd$I0XOnnOJ=xwsSDN!MLtB7KUq%JOvC zXGj3Roy8RQMx^Jt9|SR7;4X6CV~QtAf+_Dhj^qHi%b4;ZPo~JZu26X6qpujyQ|}mI z@fbr!Wlx7|MxNGmQy_W^Q-0({2zQ5Y|1S57RTNe>q^gSW%rm$U$)1B!?zu~1+UVScsRoz|!&CsKq=eZ#f$zwi=R0F63R5b<#3(I_&+p;rRV~B=9@2(^{VLqIogMZe<$_nX^stSn z98xXlWI=94d2e@bJ;(HXw(z(fe1?+GT4j%_QT%UM))dz=$rXnU+-=FFhXDirV<1KiR8fd8XcjK{q{!0kL3|rGVjDx67hNj zPP|KG35jqYeE9d7Ls>!0E<54e;OgY$GmxSgmTTLN)c2@ECA^onkFTG9fFx8Nqlr&Q zYSOe>%Qh}~VWRxM1stw|!UAV-h$*J5pKb8q{9(jBR1Qn)Omt_UqiQgD4l(~XeiM0% zXyj$GW*S;HZE~tXSh&>UnK*#Fc+K}*ItE)s5t)YU*VFUTx(pC>xM!}TmxH*IGDmH= z?9KanMFbNV8KrccOb8CDX^4DlqER3UJ{_wHj8ivqT`ttIe#jpMxFki56%E1?wdDP* zp{&Z`7~oNt+C7-rmr2T3(BJHqzVYrQ|UTV z(Z}f%^hr|SbCx8kE|4VEkMw1?-T?}Feo0B#JAX6@S_YA7flLG0EgU^NRF(Cva5c0t zPW}Uaavt#$)eZy+{%{Zt;z1M860~EMlfs?Pm_6k5eTw;xoT9%c#X48X>G&4&H#x1P zuwB@0BkOW2eH+p_GTohxk04r=6!Y{`#JkH`y(eJUFRu`_ZIJ+-n+f`dhhrC$@{kV zWA7I}w2z-ppihubuurm2woidiFQ0Os-adVN2K#*AGu>yA&l;a~J{x>C`)u{u?(>b$ zNuM)5=X}olT=co-^Rv$rU&fd9<$S$-CB9+4QeTB{q;Hh3);HNV#kaBVCf{AY2Ye6u z9`Zfnd&>8Wuk)PmdEbk^fB8lDwe#!lr}xY7%kt~(H^^^<-&ns{evAET{ObIc`>pre z;J3+dhuHZ)4&-9<|Ki7Z0|8oD8 z{;U1h`mgif;J?ZLN`NS!Z9xBk*#R2^4g{PEI2~{%;9S7vfU5!5odGuko&>@`-@pce z;eoP1MPOv$g1}{gn*z57eipbRaChL|!2N*-0*?ls4*XdJMLr^pNGHk>m5ZuHLqtPG z!$t3lCW}54eI#;;W{KvA=80B_R*BY#J_+g&lo^yAlpACW`Zeg8m=?2QUhFOQ6^DpJ z#bIKpST2qbw-h^z!~?}2h(8w363-FO6E72Q5`QM%A>Jw8B|acNC_W@UB0eU*CH^~D z8XOm_4sH}2AKW~+MR3dD*1=tZbAzqHw&1d0M{s#?MR4EX;lU$=M+c7$M#1BP-wU1) zJR^8f@Tb9-f}e)?hJ=K)3F#V=7NQTy2(g3|h7^UAgp`N$c7_ZI85@E^#)Z5WG9hGI z$czwI$gGe#A@f4Eg?txsSHejAB>@tVL?MZhs3dBMMxv9XN}5QTNm@t@l0K3N5|?DA zWR_%(WSL~SWQAmvWSeB4>U(6ynTgsuzS5c*l@fzacjCqhq!o(Vk{dO7q;=(W%r zp|?VBhdvH{8u~2sd4mrd%xkcq!J-CB!gOJ6!`g>+4C@?rEA02M$6-&yo`p{fUl_hT zd}a9R@U`LV!ncQi7QQ2VXZWu0J>fUQAB8^-e;WQ*_>1tDQa@?9Q!0}xq><7nsZts% zO_4U1HkCG)wv@J(ww1P*rb&lNoznND6Qq-*lclqyOQq|i>!ll{o1{CW2c;*Zr=(}3 z=cMPQSESdZH>9_ux21PwL9z&0luRj8$<#89teLE{tgEcMEM3+^mMP1Y70awLo2*Rc zkd@0SWPN4MYFUkJjckK#lWdD@n{1Eli0r)Vg6yK~2iXnTZ?eB+FJv#}P)^JJg#3d1ru@GAq5P3k{)haD0w^d2qu>-?3LixSg;XI|L@J^b zN=34wjiQ~RgQAn7i=vw%O<_{xD=dm4MTw$RVOR82^jFMP)F_rIRwz~}wkY-}_A2%% zzET`hTvXgr+*aIG{HnOGc&K<30V1dfCW4Fbj_`{Jj0lQ|h-erQ9T5|;Cc^n?#OD!T zM0^?9Au=;EJ2E%Y7}bZT^y=w{I^qFY6`iEbC&A-Yp^X|yxCF8V<9U8TQL zr_5GXDu*jaDaR3IANemO?9pfA0A0v(li3yDfi;0LyjA`4`y%$G3aU7jm&!-wr;@26R1H;$suWdYRZ~?fRU1`1 zRR>kJs#rBpRi&y{4ONX$jaE5T<5cgfCaD&v7OR%3YE{crD^#mhYgOx18&#WC->UA# ziQ^i_S>i^=Esfh9cPZ|cGwx2@uW|R|o~lVwUd^e!)xK(fb)Z_Vj#4YtDs{X%QJt(# zQFl;xR_CZq>U?#fx>RjfJJjXsq3ZGK+3I=fh3X~hTJ>`ED)n0Rdi5stSL%c6L+T^y zW9o0!r_^WF->EOEe^CF~D6CQIMkS5jYqX-#;YPPLUYa0Hh{oAK6RwHY#A~z~ou;v- znWlxNm8Oj*U6ZBB(HJ!anj(!=W77=OjL?kKjMg|cSo4v_rJ1Fft68L3s;Sc~*KF17 z)tu3Mr@5&4QS+1Ln&zhFw&oYj{dg*#jpyUN<9*}(<3;h}_>lMp@!|1Jxbs7k0#zzGu)CM8Tsn4aKDn4K^;VP(Ra zgijN8ChSVsoA7nQp@gFe#}j@`xRdZA5hT)yT%vcPUt(aQI8l-qmKdL?O-xQqNo<_h zG_gfutHd^m?GrmDS`)`6)+TA$^cDHt)_JH=F_MG;D_NMl(_E+r#?H}5w+P}0flKhgwljKQ}NzqBM zNpVR{k}{JDlLjOWN~%s8mNYVHOcF{OpEM!qgQSH?OOk4m>XKF@txozRX+zTHq^(KY zllCMXNxJS#dXgNFtW0j6oSj^e>`b1Kd@A`u@=wWklb-D%xf-QOt*Dfub3l-?;g z<)f5YDRWa6q%2NZp0X-sZOZzTjVYg}e37y@<#>woY|8nR?^7^k=iP?ZEAEW-kY1RM(wC=yoBn6|UwTIGrD0KR%TXZ4#^yzIVy8<=G4sTnNC;c?992D^D`G_F3wz+c`qwGt5sId zER?k%YirittW#NMv(9IIpLHqgO4jwPTUmFq{>plh4YKKMF55fXFFPPRC_6Y?mE9t{ zN47n?GJA3MrtIC>N3&06pUM6%`-kky*;li#XFtu6<+RPw=U8%zb4qi{a(d-dJ34U~Z~u!aajydlNV#L(Q(%Fxl!#n9cL zH)N1gM}eW2p|4?pVUS^{VT56{VXR@iVY*?CVZOn+$gtF~(y+#`&alz2+3=ZRzu|=8 zwBelLg5d|lCBt3AJ;Ou8?}jIaKaHHx+vsNuG>VNO#wcTqG0vzlCK{8Bt&Q!B9gSU# z-Hqu+v(aKKHkKO8j1J>?<8-6TINLbSxX`%RxYqcIah-94ai?*&ai8&k@f+h|<2~aO zXCBC-^SC_kJiokvybgII^ETyumv=qycHS>}_w#TK#}N;mZ| zWt#e#MwmvMoThQ6_e~Q`3rx#QYfbA-n@n3x+fDmThfT*!CrqbJ7fnB!E}O2JuA6={ zy)=u>v1YBgmARw2i@Cd5Z_YL6nayUW#av|WV;*cq=85LX=BeiC<~ip1=7r`Z<{I-> z^Oxqs<{Rdp&3DcB%n!}Ko1d7UnP23Cd^(@Y_s;jrkIUEOC*~*Rr{p)uZzgj*U~l$KbF+M=;EwzRRNTXHN$i`ina*epFQy(|@$ zzLqhT36=$xMV2*|U6zxUGnOAMw=MT9&kFfMuR`xa-@=B4sf8U2^9lzQRu>K{99cM~ z&{?>ta7W>R!fy(X6do@;S$L+F0?MO)>xNWH(9q@w_88Ap0ZxH zUa?-c-Yg9+ZCKiEAZq=411>iEP0(xh>KbZHu+3Z5msuO>Z;VN^SjZLv15$qis&xINKE4RNFM$44ca~ z%eKXK!uH7SXAif_?UD9qd#pXqo@{SoZ*Fg8Z(~ol=h%&Qv)xi^x7mBzd)X`OeeKou zG4{#!8TOg>IrjPX8v8Q)3j1pNTKhKpF8dMtar;U88T&c=dHXN+KgvHX-%)ljbr+9wrzsoQDKM8&rFaQ7m delta 12577 zcmbVycU)6R_xGJUb1z^BNeI2CK&T4#ULceN5<)^qhy@X%q6kXSwPxE!@jlm zZKQxA@P2Ai16wYYM|GvTQ@yC(R4LV$s-P;Vfz%*s3N@9QM%k(9)C_7S^&K^fnoZ54 z7E?>8rPK;)CG`Wfp4vcdq<*HhP}`{;)IMrIb$~iVU8Sy3*Qp!SP3jhPo4P~YrS4IG zQ7@>M)GO)(^)H}+D{up$APh)=6v%8q4#GhMP=H7f3mSpOpb2OL+Jbf<6{LYKAP;l} z`Jfvp0ENH`x`Q5|Hz)(;paKj5L%}dG3XBHxz!4j|(tORSpIX|1^<8#v^&kGJ!koki0G*iE~Kq=ce)o{LYLAu z8q*y8Ej^qbL64+I(WB|{^kjMpJ(pfcSJ6x8rSwYr2l^*^jg8(;@1S?n`{{G^dHMo< znZ82*N#CGv(og6Y^h^3Zz@F%z)Zh)JhZ8O{k_rSgI z7x+882>*bW;AMCP{t2(bYw$X}0dK-v@HV^y@4{#BIeYa9^xT)#7Dl! z5BZ}2BuC*W0x3`eYKR)4W~dcPM;SZNfHXo3X9g_N?++-ChqCIonl$FuQI_z3<7x5*R6+1Ii`_TOAYFi)s(zQ18N*w?U8 zDW@qnsvgCoGAKP2y@b+GS}K#$QCZj*2jCzag2R?j1}d8}QaO|fOL1GAg$wZj+~zc8 zA>BGsov6-Kmuap+V7Q&j=xYxZG4{D39;v6Oe5xB&Kowf#1;zR0uOV)PTadSwL>iYO6M&7HL(Q$C zzQ=Jm{*;s7^QpOusRh(R$AjzR2F@p5C=|A?;oLH6xk+p2P*#>da1phPvbxH4J)xZc z>Lj*``ib&fMEyvu#*J~4MbsK!dX(iwY`=N=x#~$Xr_~tB|UjV<)x8F~=@yH*SSne>R7) zduefD-RLD18P<{>6+LT)JV^bPClqT9n#zj&ZpGG5V^>oLJ3EH28~iYJ*1_r{)KTgf zb(}guoup2Yna|*MxIONG6LAt&;$)nHQ&&*uKC=1`C#$dEw2!RLaI!k{BdhN_Sp5L2 z>RA2A!Rp7<6UT$qINkZg3q6Fcb(FlO-qo=3En%g`0rPLdN-b_)%f32*BA}}60sufx z&HzX_qx-Cjy+eeL9@GO~1RLN1cfbc8Kmde51U!Kl>#+f6Vj1`r9DWh!Ins{6@1pE2Ac{P9N5$#9b^Cv(1J{$16e?it++exfqUX2 z+za={#kkK3kX?ffm_e=+TPIvni>)6nb7HIfh^?msTM;g;!&dCT)`yzlcyM3R*zv>* zJ!S2~zE}yM5`0qwaR7l>?x1%Nfmre15MiBS0~`3Z1|mlw_IGq~sqIsPaSWK|z&I9+ z1LMI2FcC}wlfe`)6@P;V;z4*Y9)gGBVc3T83Sh6r_#K!9W)t~+kGWcmBk)K(hP;oh z#b^M_92l45Z|gAr;J~~nqfZxGIJPl9Bvv3>xMV`za<{oN)&yxwACJkJ5V7rFxINqM= z9@vR^6>tmOsRFn04E$Y9lY8L)LOj!HC%{ASSC@}g!fEKL!9$0stEqkro)F7aYeWpz zifZr}Jf*C}b&wDHFn8bBI(2;kUOB+M#B-{^YdrT$aDO|&eQysH3~5o<;a{2|zK*77 zK+`m&5uS(V;{|vju3AE~vTT35NC~ zcxivU6vv;TgXmy7gyPYmbQt)XmfBx?ND`LgW%zsiqpZW8f6%nfnHy`Tr^D$;DtZwe zK`ZbIymAp8MMvWw@G8R7eS)?w#BI_EbVGZBFwCWzZbUbxtmM5-3%V)YtY-GQaaz)? z32wR-UQkovz)9FQ=PI&vYo&|rx(-T(X;5;^c;K^U&9aZi!WKbz{%QU z_F);*L?1&Ada<+ggnfbU^iOdHy~0^~Do?nOh+&w0pP&4*%GJ)wGj%fR;~y1GucbHD zh$oHS;1thBe9j@B%|tj`=&krX5zYntI|01gKcah$BJOnh^g6VA=wBRa(HU>AB7z`7 zsH-?YANxOfdz?N&pQKOGrzr`(i2uNs@Spf9_8?QW4`}W2J2iI^eUbhHU&dF+3Lh5` zV!KLT`yYJ0Mc@A_iU$P6U-Tn21b)X8k<;o!p`^hJEdMpzMF zOC=OT;_w}|LG~Xy2K`|0S9!6S?g+!6gh+HNeu)42C?_a~5nlxiqhZ45c%%Pwb-;$O z5o`>bz@`N7Bm5XY!O!q>=j!Mi)WQZ^6E?#(_$gs?e1bZzxNlr(j;0Pk2blOj0Hnb5 z{|P_~Go1il;#Z#l=wbF(0JNrf&`&-{mH0yy9KZqUi{%W5I9K7nc|x1hQciRgk3`VEQ-^7>dyD(#AT zL~u*s(i&)Wgsp%-I1sJmfUpX#;(*Ap$rD(=>6=f&{z6rSwU0_!UZbyT;JPZfmIIy~ z5NFk|@vTqc#zhWiYALi<Vjp(D`z0bWRSktklv6{DbrCXB)-Ktlh4}-+ z@+-m`#Ppc^sR`S55Yu9v+xHz0f*r^#Otqd*z%9=91U_<1rF#P zUS98XL}(}?sexr^7_uRZIP@(Vjz(}Gn*&A;1p0nv62 zbmTxM4!k2Ri7g|_P9nEF|jFD4vgWzWDZQ@z;s7J6;Uj)ZhZ(^k4Px72yH+c zInbR0Jr<#j=x6fFfu5wvO>c<%_CNJ5QgjR5 zb)dM7?r@+#2L?D^?>k?=!EJP(HMOC~=s8(R=m}}@i~|FmjRsYt7v%dD2L?O8hvGIl zh5~DewLCkg$U2~IMZ8BJYG(Pz*=mSmmfOzP{jkPSsGcE*PT+(#eE_%nfyDgt^y6+?p$^cfCl z^~?W@=!Q(=Pec<7N;aBxL^o$zeBmLO)=XQ+!0yDvj;&(aabO%#ghScU0ZHKgVn)d% zGbv0e2gY+?0tY5?U=p5b?_eym3yqEJ>y5F2S|*Edl*wdt9GJp^sf!#M=FloK%sXQT zF=J*djtR)pvR9GV)De+tbHZ&*9+U4VCu?Lz6+_m@Oa~&7GAG;6x45XnAzp_ktnq_P zcW}R&>B015h-QDsfw>%*|IxZI#Y|tyvzqC{lrW_nn8ktF9GFv$W>XTToGeAhvicr3 z?@WeP6?832Uc<5M-Ht1ky*%8Q4^SIX0gLcG0VvN3T7qq zgTrF|#DUGY1qX<|*y6BQ9N6ag+)l!rlN`9~G-2uHa$sh*Gdn*CVHXG1)LLd{FSx&m z`Gq02WGx3aeB$*1=J3~`9wAVVabTST>Ush-+7h5(PBZ7f*7gD+m)Mn!4!Smxw!JNl z+?i|4bz<@}sqM@S`$|icW~zPfX@rr$eO}K&ca%2og{>3+4^)a+rXJKdB!GCo!CZfV|`I!p3q;F z*r9?jq+4Z$)nLspE9jX~T9EHZPvaXLI7Slk;3x-QZeYpxf%$~*%o<1 zKUJdAne#5GsNrv2_iDB!+lsP&rG;H33~{R&q7B>D&hH!t+YuhL>70<p=U?&h@?Yj*$!; zI8X9lY!1-_6KkHIIFww$eC zD>*>4=Mo1lbKnXG{v@%_=eqJyHR?*8NagIi9X@Wr z7e0=Cz&`$3zcr*EVb*;|x3|u2I;U%N?r_*wsA;AMwe3bcdU-{B{24$)#ITK{{iG-LderpT8&|Fvvc&FoAKy^)SzVps;bvFo{(5wS!EOz%~?+V78=2po^sP zPv@Bt3Q=TKwB66zj^Pv82<)A#4P(M2^&5~*CSn*$2h?_|FFzF~Noe@xIb4F=zQrmJ zY1*uLi zQ~)KT;;4pHGv~o>Uupm~mYPp)a9k$0HXc&1sSo6q1`QBk$z2Trh$fdYI)EgQ42r=w z%npGl-!+o30{*M6OrVOL~C+4LP_pLWYYyCJv)=OEv8qI+YN{5 z(`m@5l)`?n+$m*}gs=G}XUt#x zgZ(+sfovPJ24X?2g&l|^DC%!5JITId-y01T`4v_S2vmRjSp=mf6_3 z>^T=Vmn4@Gm%%QhT*kPJbD7{W$z_Vm_b&5X7PwToRJ$y3S?03AWxLBkmqRW`T#mVB zyLNW%>DteAfa?&~k*?ERr@PK{o#ocRt+iWQxAty{Zu{L%yPb7A@Ai8=TyJ8%$@Qkz zv-5m;a$YlD3tlT;8(uqJ2VN2{nU~5_@ob%VU3gu2-FSt(?!2D7Uc6#n39m12B5xJ% z1n-%b~Fop!*^BBkpJ2FS}oNzv2GS z{jK{4KE zgh#SRk;izCwH~KEUJHB#O$2QP9Rx{&WPw&-666Xx3OWn&1o?sjfmKi@7$6uZ7%aeo zZv`U+qXaVqvjj^7D+Q|rs|B|8f{lXBf-QoBg0q6Vg8PDpf=7ZUf@gvkf>(k!f_LOR zR3H=y#X@hPuh3r@C=3>c3MIm}!p=fYSS|cb_&_8O)fZ_*Iig%qM^R@{cTuURpQv0^ zDHkspDjFx6ESf5^i)M-Dh~|psi+&WX5$zD|75ysOFFI@!9TgoHofKUa{pCq{ z(w@kZ^>p>D=jrb0;VJa=^bGe@ct&}~c*c1)@J#S**ekh>Lu}#d4+o^yrR5fyyCnXcqMo#y;8i=ywqM9URp1m zm)u0Zv-jui0JH^}TJ;HmU_Z07G-qXG3c`x-|?!D4`mG^4zHQwvI zw|O7*KI(nk`=s|d?+e}+y)St`@P6d|#QPr~+6VctK0KQb-$&ph@(J^a^NIIq=+nff znNJI!6rVI7wNHl6Z$9UIF8loHbIs?5&wZbVK978!_&oC!`!@D9`F8a!@U{B(@WsAk zeJA)%@}1&4+joxdT;C8Txzs-JI{A}C&cKGe`JLGr7@0i~Szf*o^{LcBa{!RP~{HOVE^FQl<-~YA$8~?Zd z?*mYPOMqJdFCZu&A|O7XbwJyI_5q0j$^cD(B_J;#KcFC>XF#uj;((HX%77sOQv+58 ztPeOHa53OrpfE5vFeETEP!d=_Fd?u}VAH_nfh_}5166_Pwm?nb^}xr0Zvx*1{vG%s zhzfEG;sx=81VN%8aZrPxtRQR9u%OXFrcM9$j+%>pQaA|PA;PT+g z-~qt{g9itX3Z52hTNQjd_^%Ku#4V&@NUM;xA?-sFLo!2jAz2}YkWL{*A!Q*IA^k(X z2^kbJJY;0Z=#a4?<3lEf%n6wrGCyQtXnbg!&~~96LX$$zhF%Z78G1YPZrJ#+Sz&X+ z=7!CeG?KKJs3hqUjU-c&C9z04NxDe7O1eo3CF3M^$#ls~NwrO~RI*(1gXBlaPm=AD z-z0}6MDqHzl_vcO~~F4<(NzPb6=p5z+?I#?q$J=F*nZWT{TtS=vRK zC(W1kk`9n!>9^7m(oxbe(y3CrbcXah>1^ru(#6tc(iPGlq?@F_NcT$*N)JnqN{>q~ zN$*J?NdJ;PmfD_5pG#lLXc>~RGFMqWnY+wGCY1ThQe>I3Y*~)XEVIaZ$a>0(WW8k- zGEO#5HbFK?Hbpi~_PuPLY=NvwRxMj1TPNEn+br8E+b-KFJ1n~(yC}OPyCS4{&%<{JU+Zpc$4sE;fdjy;kxjwa6@>f@S^bI@RIO;;T7Ti!-t2D3?CgnHi8%7 z7h#Kvh>d6v(J-P(MDvJN5p5$nMCc=o5$1@F5nUqkBMKvWMD&U%ju;g&En-Q;?ucU% z*CL)PfTEs)r{F7m6#j}JMTnx2!l3A+C{pxN^j7py3{nhLV8w97D8(4X97VNasbYm< zm14DGvtqmAfZ~ketm2&Fg5s9quHu2>kxlVb@jMbl21F_%TSm5tY#*5vnG&gr%!tg4 z)JGa4dq(z->=RiUSr%Ct`Ay{D$YGH<^4rJ>k>5qGiTow|Clesp1UkLX^}eWLqDmqpv6 zZKI;cMo);I96d97cJ$on1<_T}hoaxa$YbJS8pmj2EHU{pg)u#1dd2jMsfZa6GbmDk(Op zK~h3ePSW6{B}vDVP9|MUx}NkP=~2?_qz_7{^i+B&gOy=QsZy>?P&QUJRkl#JR<>29 zD%HvirB-QDnw1u1f$|&WAmtF{FeRrPt{kZxtsJWyubilytemTyuUx3CPHvRkKG~L; ztWP#3o0B^xcS+7qE=(>@?w>p`c}TJ?nM)p?JTiH7^33G(DRhcFMUzsLG9qPO%F2{& zDLYg4r2Lw4AmvcX(UcP@r&DgG+)lZd@-XFb%CnT0DX&xBrTm>LNR_5GNli~Rr;bjY zle#>0W9rt_9jUuh_oW_8J)C+p^;#NA6WP+j(qw57X;EphX${gErZq`ZrjbB3Eh9~v zrb{!V<)oR@dZdj?o0qmH?P1ynRh&wx%2H*kOe%}2vno&3Pc=-%sYa+qtH!A&sFtYK zsWz*&s&=UMs`jZ4st&0Rt8S{Es@|yHt3IfK+EvX{d#FWfu{uBc z?bL~CrCO!VQFl~#QRl0>tBcgd>Js%p^(ggN^#t`~^)&T#b(MOtdYO8q`bYIo>h0=X z>b>fH>VxV->htQ0>dWe@>Kp1?>SyYg>No25>JRBuIzL^QE>8DJ_fHQ@k4tZv-X^_$ zdQy5ydRn?MJty6io}1p?mR^)zoL-tksW4omJQ*&K&PxDao zNb^+lT=TcqO)J!jwLV&ZZJ1W34cA6$qqS|cDO!WJMB7hWp&g(dq#dfo+Tq$!+OgUR z+R55!+8Nq4+V$E^+Ml)Cv^%xCwR^Suv4xb>>c;5C>n7=D=w|8W=;rAb z=vL^~>2~S%>weQ6(H+;F)BUddLw7}YRrgHyK1-P8nH8GVC@UpPm8H+>l2wpZnl&VA zXx6YSoHZkBdDiBvLs_@8?qxm9dYttv>!n_ykJoq5EA_Tiy;`r)>+}YFjy_l4QD3MZ zpdX|kq93WBqMxB(s9&L9rC+Vztlz5Np+BfUtG}wht-q&#sDG?~WAHTu8Cn_A4Cw}q zL1*Y}=xXR@uo}t?m4*R^L59(WafS(o$%f^Im4;o0y@o4>tA-nfTZX%a2iZfjM`cgW zUYWhtmVG4qdiDdOk1^1gV$3w^jYgx%SZM5REHU;oRu~5xhZ(VPxN)R$s&Scdi*c`U zpYfpaknyzfk@2bVMUHn)LXI(~N6yHc**Qyce#zON^IOi5oZ~sCa?a+Q&-p#)QO?tx z7dfwU-sSvlVoXAl*yLmKHwBqOO%hXmQ-aCX*woCVG^LtUrVLZAsgtRTDc@9L>Sro9 z^*0SSjWUffjW;betu?JTZ8H6A+G9Fzx@3B04mHP`o0yxKTbNs!+n7_#Ds#G7W6m^Z znJwnd<~(!0xtEzUk223QFE#Hp|6=~beAoQc{KEX&{LcJOE}QF?>z*sf_009M} zavSEVb4|Hja|?32=N9D_=T_zp$Q_tFICp5SEq7k-*4)dvuPo5QTHGw|77vTiBDW-1 z8e5uKT3Xsz+F8;p8jH?iuox}fEJc=LOR1&IGSD)_GR(qRhFd0BW?L3osx3<`D=cd) p>n$5CKU=n1ez6?M^T-qBh0F3H^Xk{`C+V7B_U|vYlT=>({{!2CfRX?J diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/Contents.json b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/Contents.json new file mode 100644 index 0000000..93f78d6 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "ic_fork.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "ic_fork@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "ic_fork@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/ic_fork.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/ic_fork.png new file mode 100644 index 0000000000000000000000000000000000000000..ec86425cc193c2e7727004ab7578cb07ece42b6f GIT binary patch literal 1131 zcmV-x1eE)UP)X1^@s6JPCf300001b5ch_0Itp) z=>Px(B}qg+0&#(!KSpGEsEG?yzo@ zD+X$+$`9yt+Jk@oJ-nx2YjM}@;bC??kc_6)ao+HLbIXj^9}uK*ZE#3<-PZIe3dnjv z)I!2@+_K$d(Cf6>J*HA4Y$-LCRaYOOv&o#m;czf79Xnnm2o6e0%j%x3Cp^zTw`ccG z6)l%%^8UrU;B;LZ==%BF%a{-(F;-0cQMQI<>9>rA!dJU4rz>jr?u*nPyb_Q(`+KKr zcI{y$5HGL;y6UOD{y3;UjUbVo(G`KkGN zU%fYQ>0+j|6K}lM{m;#@}sc+I9w-h7ZoqakXQa#dQRE`ZG%WkND5Apj4A z5Rl0zh{a+-U+AmV>vM;;n2KR`-VdQr=(|F7(ZWhaZfqEmc{{k`(>Rt?A5G{XC6F{B3b2!z=2Krh7K}t2&z%3^ z5iGPCpN1Z?0hFI@Z+9%`gEorQh_&Eu8OAT$>>t;^-E^u1y;Bl_=r|rDv<~Mb;HlF^ zYWPEfh^ti5!{`j793B?JMBq|L8D!*gyGF&2;fK5Ge|g=Gx2y_`aud4 zlQV+-!_Uq+_V1UDeqROo33-?h+NduChGDYzGzA4vSg1{&?C*a-hi9ePfWogX=)OI- z;J>q&O}eM1Vcb3K#>BcoVnajY2hA0mRGNXR3bPJ9;z!0NexDn^`(j7OSMea~iGY&P2iU-eqd{{UQ3&va?5>vI4A002ovPDHLkV1i^6F%$p* literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/ic_fork@2x.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_fork.imageset/ic_fork@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..72e889faf65aa57cbe9ad7acce126b16ef3fb29e GIT binary patch literal 3051 zcmV>^600001b5ch_0Itp) z=>Px=rAb6VR9FeMS!--u#TB0WzWem<+Uxic+az^LiZK#t)KU?IqN)-Csj5_&KUGz! z{Sl!8h0xHdyc{U15E4{{R;pT3@uNRzR8@iiLTZ(ysHH$cNE(|sj!A6CyY{~K?%mz{ zo_@2N-CRGD2zR8rckbMoGv7V)oik_7a%4sM{abGZ)1S>nt6Jr|w(BUi?RY#VpS*Q= z^kh1H(ik5f_f`zq)JLHuZES2z*t2JkSkbv5&vyD{LAX~GgsnWs^~wTQ&lQWMC97l% z_w~7xlasVHZnN)POW^qUONlZu6Si)=Cd*R)_M5hL@f^>ynREG~p3N1~g24Ym41`Wb zh+g=AX-cG&a)%Ee=HLJLzoUYv3=VAV+pfq`vcI=i0e}YHKrn!!Dw?M6s#J6@RZ9H} zFY359T~p#Kue>WO3Q?)Y{}jt}$G7(0nTW?a_@3@=!t+f9mbHqQ$>rj2zjy4BV!1pc zN4vjw^yty~y?ggM4aA%HBhD>O?BF;$n(Rv46bLBsWM?Pe(Gel4Dz~SJM#4}9p(nS?4t#7%dJSJjkU|y+W~==Hl^Q+Sm7GIzGO)HMadxqA1BGWRyYR z>ry{uLtWRgt6odk8W5H@9Xj-8IFcNUDb>r{d&49o1T#*Jl(a*K{xTB|6aD`C?`M2$ z6p<51l_z}0@m#~Q9oKOj!F63C2yKr*JkKKz+E}~e*wiGvWeKi5GBQG;p_Z&wcUU5i zB@WDIX0~u19SEq>&D5h&Rh2A`lJZ6JEN9!iBtlMw@n!QRTz6Qpd15f=jYMajPL_E4P6bknD zba%m6ltwSZFo`5fq^ehME^3vsz;TPv&}s3CgYyo)@ao&dbtc~V`>_#G5Y>ULy=_3n zVwn_*C8mw6EQ@J}660DXkEN6h!`((bZ~yT2A?X`m-$l9-38KP4STRhC_-@fOr(&@=* zd17MHbzwloQhC{2(3&^0bI0uMx7~U{6si5gWp9^1OiWC0J=;dYeOtQW;S~~#MG5m| z{=xvUHuesln0V9^HNB*?0byjVS~qkLi|-%Us>4^gwqwnQLV?c%0eM6IurX?oII7CK ziY&La(vs!BGhnO_0NH9KUvILu*#nv}*hFgrVy+q;bb!&&XG7~^?tqezN3l0!7!0g= z`GK%{qupyvM>&sp21w@z=J}aRl?$_%b;zx?my7|1<6B!hc*)*dR)frp&>Qt@^zH5KbxRjB zwqrYbtzMVGNm)YlpkOCwg}D{R(^{=&KyC>h&v@qfgVYbm)pUK`?E?y;T197H!Pvgx zlCcT*?b~NR^5k<%vM9cJ=Im#qXD82(4h{4ZaFD$waDUL;0`Xk$L_ksg0SEap9Pu(h zjgA}rU|V5J#ja~ON z6RtZEqh&>}8kp(21G9(s{Q%*K^w;10@%653zHnE1G1CC*|G^T@JpAYb?-5At?cT5H%10&*B2rlspDpnz1E zpYN7LVR^)d(V##o5DNSW5hB~=+vSD;AueK?xi0On89tqv!QL(o!25T!XKYq1>XA|~ zET4pK6QHXiF)0<%O}nP zQKxZD8F^YW~6S_M=i%0fMPLk zyI7RtCp?ZnZ<-l%Z0vz$GW~#fS(2bJ7ACG(6^`hXa9LiUtE{Cp4g4ni82*C~P7czF z-Cr}SFTx1AY|H6|g4w%P(E_6I2a$*u;IEC92I2=K1XR`k+!BC0ha(ToBCu|lCX08_ zDE8iROJIKLQdiZmI)C!`bGPAB6XBpT001$|bcVp40O~DTIQY&p_}ppBC9~mBG&er} z;}u^Hp}tuKNs`v)5TSLPsSAV?8i24*2~IpN+nOEoJboC1cG#Z#eM-Ecitcnl=2~(b z!qHDC&wXl?_00H-PqA%iRq+FoL&2bmFW^@0_wYKM7&(fg{*wMg6R?fZr*%3uy4!Ws$p0fmAeTJE)5GTy?lrM^IBA-k~t>>S7jAchyxh^2h zu0BA9UGFh%YY1!H2HEQ5zr)hX@s7xAvLc-gOZ2^m9(u^S7BBqcuT^hP{?5Bc2jS+2 z;aw$mgzkt&mK_vXgx4sP+DMs9MZ)2WTjC*SGr=(VZ9r!xCx@Wiok(;_A_DQAEnUlw z(kugl&6QY#(YO{$jt493w>V5C81oRz;Gw-}BA8rD!xvdV7*> zK&@oM`~UukWU_fKmn}q&961sKp>=5Jiy>GsT0~|`7#bR4CLe}hjIbm_Jl;Y4>6j>% zFBl4vPfnjDVzI<%CRH4Xjb&(Vh_ox_U-c+18Ac>EIg=RPx>Z)ORNdX3jWf6Z%bQ68 zp7i&2V}Esc3l^D~O$DZ=CN@_+fX7!Wa9^&-Hdao?85<_O>MYJk4sH=il!z)Rl&G9z zD4fHN%&R`}3pR*}q~fYXu@pt33X&o4vg?TC2nz-jMf4&xQmh%gHvZIs%?A`iB#87+ zxlkyVa7F@u^$2F+k&$f!Gm%`vsg;(>dMQ^ZXLycQlEYirNnz6g@d&m|RW-}$#aw!6 zDZh}-<=uR-2$U8QcXs0f7?$nwGPz=UaWOlW%H*|2$HuNWrZ(*QS}+SA9)9`db}DyMkX#Ycc8p3WI3+l4 z4(X9u{Q2TavK+_G-S9H_^QE?w%`GaNbT$z0m>98K^YCV(@X2axi2Xfg%s3ilsXKrmFr38d8xm t5@d-#-oLH?xQ+kJSeoUAX1Kx5{{y>3g=TDN&dUG*002ovPDHLkV1fqBPx~{YgYYRA>dwTS<%@*Li;L)!J3PPS3&_(&9*>D1!_lDVC^2ju6Q zMfO1gV!($4SpXlzToU9GAB-4ra>zk9(ucq>0@yx?0s>2xC@*w4k|M4lIcx7--L=1$ z@2_F^bkD{aQsVfLHQiP9mj8eM{=dID+rIICK6}cmg!^fwc*U`;Ioq;6Cpgc`G-Yur8RM!G zhv^$(oGh|5ZPoJf{fM!EUAmN>J9jP}o%5i+>mv*Eg@v_TWRzVeGG^l>`b#d^lZqK; zrBWyxx~@@QB2FA9>C(#T^Jx%8jPqYi_~IY)rSf8Y^i-d*bGQzkEi+&V;4^2=hmStK%&N2+$(uA=3LEuQKiiWOrnbO`)!#E1HH2LBe zo)6BSKY!r7sX;z?wfd~pXh=6%3N`>9wL?SMOW@L?KQxC$3EiSDb{^-h$Kao;4xln;oO@28$ zJ0GJPQSHDeC!j2hMx$QthQWlPiwbzHWLZYuwr$;Y9hS@Gm}Q&HG>zd!_w=0J+qR{f zhF&lYqi6`j0nb`M$N+1PDJDF7piS?_`i$V-S2SJBOqR+|S*GchN(FPWTILg#5_AJ+ zkf|}C=)O>Jp-2?#`+YGzRn1wp0Yb{juGc^E!BWHNF}8?7q(}~==}d~85^NryvxaU| z9Ve%Q8XR)QfaH!qfkN3k+q5_oi*AROk)(+o8@ihWaaay>L&db?B%k05UDM!6a4q42 zC0Iv-Lia2e3RXPkDV&r@dJaDBy>Zx7qu1++8#ns;vbW|4&V*qY*_={w`S8>+&vl#0 z@#DwUi!Z)Nu#Yt%bUn2VyK5PC2Ux;2x<`0uLnMrlJ{e1up zZQamPQ|GB-Jcwmnt92VZg5kx)5ymDbPMk|`iN-BTPjgayfn{;Q6 zOf_Or(w92V!+D#vOv5ghic`8SG%mmu*lsumakJr_s)ZdNe(RdBvlPj8mW2sicHfssD_E54Sg0xF%To9 zI;_*_Dj|fQD;Ar-|J3o;JMX-+h3|L6k|X$D3hN zkU}2P3_eq^@@0ToAnjZ(<+1*TTblr}D2N!GJTf_zNXFA7K9Iva`=CwQnA0|>SCvX$ z{^1Y(!@0t*6jwTEe(3FYfALkYAq=&}rY9%2Ahueou^D(7!lS3=F8#+}yrI^&0mzxJypp=dKhpqlu7b^irIj@w3uW>}EJv&` zXfbwdb+ra|3>er?0;xa<4k1=CY{$M#2FWXAg4^}F*7c%EVn1m15+U`_r{*$SN{#}_ z`k;|)JMer$1Q%#I&iFi(SVc%x6;kSv=ZPV-U{o^=>VrTF+Y<=n4wGA>rCgjD7SGpj;@~_{2U#~aTLLxa>4diYx>`FEf{ZaTw z)T9Pa#e4qup856E<*Wnd*X)q2p-TxY0hleLqyM^E6l0^n@&nCNwaSt{WNakFww9IR@`Y zM5w>6o1{p%#!{~3^K5i0kgI8?rYWHeAeH1t?4iLpN8pSaEd83}nBM&S{GP@Qre3aA z6|4umBuhfoE7&V23J3xw-Aki>)St#_FyNRd?(|lYF^W|x6%r&Un<#`Z?g_v&l~5S6 z<~Y_WCY9=2CbC0dGm8E8g&6unfsy4-gT5czVHl4gb_XbM z9t4O4X>Sc1u0pT|U9>TK9hc2ssVu@No0pnyq;VuwDkSAp7-?QoQq%@)m)+d?Gk6y# zG5V)6%CbyKIu4iR@~j*ph8+TnVht$5D2kxkAY6NBuwhZZ?>Er3hHKvxgEmf!#bfDpO+-dSL~4~nUlmU=SL zyIlkoE6^p;TCGmH-XuRY2m>gH4Nwu#vb8nxJVJON4d?@P3+kq!m}vF;LADDUz1LTy zhp8U~l*b<5rtKiYGi*ZI^}rX5!8vE-3hZed`VCqZD86#$Opw>~>rftV!`M##?7}af zfp|>0j>8Tgo&ig)N9;6+jPdQ;D~xOys8>s5{1eO8R{+b0jk_C{a!yw7C|wh z6kU5};mzy0?V{4$z-O9jf@O5i>m$aHjHr|E~&%x?u!Ij~xp{skBZ;bl$A)XCw@*-@e(D{!mlcirUAv?UUkqsSd z9|K}z^WF2!!qgNmbdk4Bc|k^L9y_!ZHu9xdmU@6JiPq#qaSd$gAAa=FEu`H%n3RS< zUVgJu*#_XDs>%-B(SbD8Jy8tsYOlZky7jBo_T!M&&qBpdt5i;mElQpchj+tOmr`wM z5Z8GWH4$jWZ@&3vW|T+!Z$^yXK`Uy2am;Xxj=A%F9SPEkaB=PjDSr7f(|uphH9P)s zWK%v5zj^|8Y8){#C!BY&+zLQj_LI1dlw6a5f!(?*Vwt)}h;UbR4}?-6j}M;SwevRH z^2Qr)=!HUofA`!u%U_MFeXm=_lv7AemSBCivLYo*6=aKR%b0Ezlns#P+k((wsUgL{ z4jEE-fm00~m;vk^T85NhEqqd1pcRJ379QVWC>dP--h1!qQKU~J?8~uc|B=fs#5h3yfhO$z2Ws@G5`~T4KHY1{-?&Znu;V`sGV7Vh}a!KGUV(iEdiO3Ti;iC=4f5%BB#q zmnBcR_EY6l!3>(9Bs4rKot3Zpv`y>a#_O})hgl#xXJ&QeCMUV-W4f=Z!=$4GE)Geq0I3UbpJ0r|?d9d=T^y2)2}cnl3K1)!ynzzt>y+E*y74Vz z8;zCm>0nn2@B;81cal$Gk}2dKG(^4v3=3|N7NNyppEC=+uFNGn0%#y>5)>n8V16YrH9w`27eKOa>GF z+cxX&X0x`NeiSjM zuzSRM@FX&`5g<`g$Ci4a_*E3rw6vV&`9-9s?xT$&MthyZRYAt53^5yXY4)=QCNv{6VQVzGMb zaOF_Xb<4@QbKmt5Xbv3OeY4#t7=!O)h_(BD2L-+pr~;@64&?UHfJ}mT=NgJku3}g( zjp8dfJLv$$E+}@DrOHou++tE|@+69r&Ptb6Y)~bZcaZv65E_6yMC>y5yVMI|msFKY zRe>GZ7h=$ki3y~NCFf0uYKWf*66%phbq14%6m2z=Qin-b9 zWCbjP$>Dgwf8)2R)75v2`BKwnLHi&O8o)C|>{_qKog~h|ds=QuDl~v|c zvvc7AJX8~m&?GyYqw1Una_iU#VpidGI{Jqnewc;*gZ>BcNr-XeAG9C8^_Bt8yb9Rn z3zl7a_L--QxkJ;apFqh^xx59jdaISO;_ams_QsoU;po)kI4`v7Ywi38;SGcw0hP@j z7}appo|XK7uku3EBJ#dX#2jWGh0G|Y%L<&Spag!_aO3Ih9ff4W>Nmt)C?rFS0!@>k z%pwc}&G(xd+GaTN!F|zRef3qH73PX=!7All*G3kIqu4n+(5C7acpx~~9*2?csg{XK zg6QD8gbg6Ih!6|me{41TsTpALz1PYOCSig0C6%n8H*Y!Ox3gR&mT z-56MOPxVXGs9y>;S$_>DcKEJPq>fX=Sl&-f@L-Mm`P5Nlucl%>a-4i*n`R1)2q8lNy@~yH zT7>#he?;91a_FNS^pY8TF(7 zBzGwBN)59ZN>Pl$-?9cy?QX+Av3GiJ9&Rb}bkg8qKY}`oarCJhrXL0-3PiwhpvXum z!T^#8B?+WaQEMS_g(%9*Dr3@q99vNu&n+!Ia5riI8+~dEa7Je*P~Y6^%P{Fbj$_y3 zbf|sg@GLkCMcy#HWXs5B95gDz>~uV;2S%l7J^1;>OG~IYT}4IrTRIazJ8|N0_Z#2% z#$8ingZVy*PcqQzH}kpqktu#JNWp z)0h^x(eI~5y4zvFCxOIvb7n3TGC%6&mtPJ|F@Fgj`VT;*nafwMedX5eCD%cr*7VHe z7GH671vSAzKyKAq%+eo2z?R_$FZlkg;Q{w{3qGi417A_i&(BBo(7c3{-g1xzNB(Ew zqt60}dDqQ>Ee~y}jJb7tIjf98pBn0Weq=h<%_vmO$*Oi>Zq(?eWib~$IDh^;d*Mre zC~~^1WFQS3AbbYLIxb4SgPfg1<+GHi=fLk)k~9jFsL^gWK`qqi%m3At@uO0yTtm*+ z|A%jV>o)?i0mTS6<)GH5UcVJ3t{b?P`)!;POyY-f4|!hq%g~NUgiHZgnl->?0FNY(KT0>n pO|^tB8iW+wjhOlm2mgkA`G1CzL1(%FrdR*~002ovPDHLkV1h1{`O5$R literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/Contents.json b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/Contents.json new file mode 100644 index 0000000..ee165f6 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "ic_start_yellow.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "Star@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "ic_star_yellow@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/Star@2x.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/Star@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..e5e813e21e9be8e5fa79c65df14890e2e5f2ca90 GIT binary patch literal 3318 zcmVjzP)Px>ut`KgRCodHU3+XCM;V{l$31MPPSPf69`>CbpF@+T6;x0`p`@Xul>tRi8lnDC z(Ev(fI}%b06@;d=DEt8eA;oqQKv4CM3Pltt2nDsgQmGUbR3Jnt#Ao8Ookx>~yzTSd zK8EkRcuyDSZtwPPXZCjQRyytOJif>8x8LmS-0UnN0pG^=L^j|r;BFEn=nhh9?3(lO zaFBhKg6!PHaP*^$kq7XH$3gZr&_ps*f6gMW@YqTV(w+v%nL=MuL(va2roUO3Myc|V z_+a`kg=s-K4sb-~?~Mgq6-z6~_VHmLBXV-M<%5Q){k0e`vZQ{fb71Cg#q#`|7RZP+ z3+|2c$+63uU)E3Ofs4r0kop1WrM_)P0;S}h_@MT8yE1;u3tU7pLi0VMr#5lDpP!XwXbXPeN5g;ssWu1am&*g2e z+AzHL)`LhB96j#NS<*2Sol8NIt>NA~D^S$;eZOhg)lJX5h(VnPe?;ysYc%h}3nqvsMxje3XH*yd;iIGS*GmPWV zG`ccf1%S}0EU$_6&z`6iR4?lLHX@n9zUdZ;2t3L{nO>0KhE88b4_YhNB%>Qy&AYL!9u=h9sqD zeHW1$(=lRrk%%CN=5%lYoR?5vMdZ}p=t^DJ{|jJ*c>yvfH=`)Z>W=N{ zQ=IjcF4utOEyy!L_RP*E4^tQBBU^?ebMXMfVVEIpeYhllp4C}2Q%YAj>wZk3vSiPYzjIaZC(L{dZ7n}%MPUPwR3vSD5dV&(Y7aRn_kSLNM6eG>sCbAqD zZs%i@Ocq zEOgVrpvnT^FXbYbP>5nO%1n}!BqeFIgpyrPUb^Je?~+8G8(z{jBV9^R<9bx(nm`~6 z6!Zddw>eeREMGYSKrBY-7IR^8>A-u}ib;ZKXEe1pyh$?28oX~Y zYC>eep0MS`Dm2r)MSv1|hQWQ9GAVaIHYIXAzCCkL!5-JdklGGW_FW)P!UreVduwe| zdr1Ux0mjI3M$G$xCKCd13v!rmT2p&Mk3)y#B_On>Iie*kXlA&I05rD-bflh$@5sK4 zg7ZY;$;5Ez^Cn|21JmwKYC_@7%{>HQl9)v4Q9(+wuxDvqJvFEi|ZkTp9srPG{j&l}F=)nM3nS z6(tf2O$>z}f}yg5ejRa{@2KC;fv7YL4Q`4JW`0-9my-W}UH`Gtkr^#&mPBGVL_({oh;~7va?gnL=+5TeH$RJ?q`)1v)?CaXAxs3 zB%)uABGLjPw*Z65{s;r^E3CBUzIFs)%=EM>(T&wCOyMXZEmKhuj4pf}CbRhJjU~(e zy4(Ynh-oz>qCZs;i4{8rGGj!R?uV-=h3Cz!dIWM90+u;Us}xgJ(^{wt-&fR_fz51B zVS4kpG6aCcF_p?2YkeQH>WH+=L<1zIU^DCM1&1tugzf<|#I9Bn(dL>X(sDfaenv+7 z14QOJE3LUNjQ~XAv1nNRgj?^G)EtqPsc2A04R3&JBQT5ETE4lzr$-Pgw@5_$Tq6>N z;S@h58rcXBv=xm;V4X(W5F5m(E~Z141OLMQMeUchYdAK0Z@ID!l~2iA?P}Y@i??39 z?6%*oMxR&d<@lu?%moxkjXAJUS9vn)oaX8r(4R%gPVr9(+ZgMUaU22_X^{ z(ap!QadrJ;aFyogVq$s_H}o;*EBGwRKOs$Pp)#AIaSuJmH}F@OCiGa)XqFHnp@k9Byc7}yGui$LOMZPSKB#>R ze|U^(g=It>i}GE_NDDqs!TmzaM(LKg9*~Vof-*mHW+yUK10zf z!XQ!4lH5BW6C>@5Ok?H(Z_r>#latUhem=JDz8C2OhjlxB>`xn%iDQ5MA}n0{9IQyZ z%C4*%d6L|+IM#ppq8qYG$>83!Qj+1?(Sa-eJT#k6v9=WnXhMHljzk0k%V1fogLP3x zDS+Ha=Zyi{$el>T+ z-T>}IQf9gukq|wz@cV&EBi*nR^z&}Ks)jO97Rp4~s3VV%3kPmvP|PImM8fj-t`G?~ za~*~hek{vM4>XHU^Z4Kx%0$_y19jze7DLTpnp+syspa0;Ne!vzp~rfwoe_3<5FOAT zp}&wNx~rB2h3s^c%9|Pv_dv7w0(7FjfTJ{}%9Tq8AMgU<`q7)JjVot7=Ho}rh?%YW zW7F{X@EchoJ3IQb|EfeEuQF33p}P!|?1smePgku&3N7dP(KD`1t3-`zo7LB;q}&%D z%znme5|KEx0c}B>;Pmxs$gBa2iqvr>(sbBkg(m22nMjXx?a(&F2hwj=tf|b7f{fPH+B{%35c!DzmW-nj- zDtsF7Ye49YUu96_uCDE~DIVrFX3SBQz*WO5@CW|gmlM`#V2l)WURuI}2AeWv5fSGfNR;x<6l%0pk#XY@UX0br5C zq*{Sq)x%F1;tC#K>904vhy`L&Z+129sWSxr57&rFuN1OI*Z=?k07*qoM6N<$f~Q?6 AsQ>@~ literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/ic_star_yellow@3x.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/ic_star_yellow@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..5e7c090c53474dac4d18fcf94d895650d6d1cf61 GIT binary patch literal 5286 zcmV;X6j|$uP)Px}U`a$lRCodHU2BjW)pfqN=efIjAxm1J$Ii@3D-4oioY)D8Qy2qf6H;Jef{IE7 zTs(v#&2B=NkY;vQUa?vs zB(b~m?wjw-?x<#mdG$L$zwh+1fr3vNNrFrVyI07oN8po_+jq$;b-^z*HE9IG9 z?!97TfAZDxbaibU0To$|V^*<7zDggpT6#qxDzPR4Dzesur?JejgPkAAv+Vy=EA3&v zkM<1AzE&+?r8kCvimZ*{RI`-Mb2Uf)_3~>9SD6}EvR&LRTWuVaDQHB4>m$nQbFaYd<*JaU$t&Ta6Lj*02m$gZxu}ZtWmO( z7>cf(@$I4h%o|n2s^l67sK{CaoLX5rYdoqJ+$4XSF(;5h<$XWxO@+^^UJ*pOE65&Z+@ml@X zM?gi^`WO{TBn}57ER`R@0Lj~6mAb_MevSn_Tf#e2@w$ao0pn9IuEi`Z_L@ml!m%I^ za$Sq5!G^2I+5lh^gTYXm<>7g3S54g*dc?%0q`m(JaX zB32TWEb!0ksbh`1vsGlR;eUKvwGQ7_9Y>KsjbdhHrSYv+FTT~9FiYTKlcOSQ4Ugt| z_HU4F2T{q2z`VX17P&i1Mb;|*j}LXN<$C5grk6UZ6fr#+&PWQ)-y4a}yluMhMIcZ` z)+$Z}Q9oxVQOOL_M|!K6p%DRb;K;v{XLxSM4AwnL>I=e+9E#pQIvd83iT|EnSt#q!PF#ca>$?b_u7<`2E4~ zx?S&`woR!66sgEs=A>*U{g>?|Dw#w2$&ND9Tz{z|YY7F$A6vFEmr5qUmZc@h?K$P_ zJ#Vlhyz%byXWCnLefcTRuR~ei%olc(bmzk(U0u_~sJvFp? z$*ee=z$4BN$m}Gt4etz`?&K>XYob%rvfFBveXfqINp^0J6NpOAhn=g)UaN@U1i7w_ ztP_XUb*3{@2{>uB6C5>f<5a-E8t)8D%sR+s(@b@3WX*$ot(L{xJ6>Uq0OBY=|x zxiYejAKB26o1BcpQQb~**1WBg-tO+m#vLb;4z#@`lU*5E^~tGwfSMDDO3v<{x4$LF zJF&9sB5VA~aFEYT91}vUbE3n@X3qJ9=vucaaz`TN)HXC@x9cJ+pFMfElZi@BCi|%! z%{bi2bzDVOab&9>djZhr)y_ZAjzW8!-;#z~;EHa5IP@F7UuBO*a$MXlba8*f=ty3W zYy4ra;QzSZw=K?hy`Gia+?LH-G-MS=Zt;wrelEoGq7RQJw+OEHp?BAZXO(@7i!dhD zo8AMUWt1%zK&xnDhphx&B8Z`r5aU9N!LcL4!(%TcHKw>n@5}4?KJXKy1R3Wd) z33Pa37vDKOWsemLwOC5l(c$G6X*@F*A$8UVWn0jHq&_8)bNND3)Rkip;OrcH2_o|t zd^y53R*1;D@W(=X&b@0@J6a}d;pOGzxjyuR(2r!eZ4)U4NLe_S{?$9HfOV@}bS>VY zXpC)YM{th*F^ge*5$oz$9&7dG@rKAsZz$z6r#E3pxkYFoV}X=3z~LaLSnF2DsCFAe z0DO5Hd_mtB5g8=LuFEk@(TsTftBy7DCfNnDisv^6M&o0>nvMuLKlOu5+^*4|Dm0vY0EfuB&g;MSfP4*b5z z>)%GYim*0$L#e5XK$?5Bo5Oq3|5_}ufUJ}_HWc`zuIt}J-@&%!$&1FQUxff608%D3 zO}nWln*R4vMBYbM%1jIeKf(0;b0DmmoG(R7om-9o2sy(v&kf;d>ZNjJ70F74Mu$3n zR~NbGF-~j$@{i?KtLw#y0G9dGxcB-{H2I&E8d#OAR5(7|aRt+JKTuDbDnX~xOho`s z#hB*3F0v>2N;SDP$x4;*Qprbjmi;$$38Y}3D0QE_bI$Q^I9#7>yni! zpZEvghjKagA|4E^swGV2DFlonfCmDnyQ^Dq2m*+x2^P?< z4)09G8!2B}#!zG}RwP9}?zs~Ejbp_$^{Wu5hXC<~c+(6~Np@3YrHbpL$#IQ&uSA#N zmvpTTg+NUNz!TyN@up_E8ktRX14`vh9`5Q+rn5BY+FF{f&J_Yh1aRwrqa)zErhDg1 zOS4H$N7kYtWI&+P{|R(|>&}xE>!@EhA;5o1{AiV^gjmaDB_Z^+qqie?H70mpr)za6 z1PB4*1M$MFuVGCgD;Y+6jEb(VYcap@DqX9?AQvRc*D}Kqb-Z9MK@3b!oKZ) zh>78+i)re2@gP8cE%?`Bq7q`3la-Xvs?4D^pS~5hihrSNbu119$e#tj+O+Dn<=uc% zw+OLcOALMS33LfQTbi!U9f$zu-v~$d-pToXtTtuOVJlgwNqC2Vj}8SN6+(C2ZX@=% z)OszPYmbGZse8}`z;wEOhb`TJ(&kVD3k_v#xHMgzI|Bhkx8ZgWmC&(0vX;7JbkO%z ztm%4hX_`8h7Xhrb`n6Dh_Rrg8q3w~iw4sHDbN=_GY3f{31mLH35|vPCD_O~aNPp%& zj4B_Zb9Kmx0Qraf)NbqA+6^deeBz-0eyk{apfpXLw;urzbzgWO^KknuX>*^o9Du}N z;IA=D@a6J!b=@8WFzWwYxIg`s_Go{vD&6z%=_A#jJG%Hi_iXULtqLKdeBUb8ZMz)k>rG_Mie0MROJ&IZ9 zwhscE0oI9iKn5LX-xH2zAD7X7X~{}pVIKB2ko8IY)jcwTx0q}~M9qT?cVK$zo3ge` zYO)e&@j?HsT!?Riv|d?3bh=$2K~8Xf8>XkeC39P(Co6%M81jDx?-YCsiyEt4ugzu? zcFo2k@LR*t%y-NdZMHl|kd+!eIuy788*@B`Q?-+fc`Qg{qlsHW(e!iXiL_3VV+Jn- zC?=?%wGImRNhUmA1#EQ^u8tuqMy_hHVhhOXBwQUqR`LAi0A2>#Y=N&_FOqO2e4PMPIuHP3(a|*tWAgivXtrn2W>j<(sX~b$a zk?fG?6nq^)R*YCxH^4&HIt5?p$$DyN^%9I&do1*o>qQg3gtP2GNKe+ZnBIyJt7G1~ zmEGZ$>?3>$=Sq1prAbfLJkO~vfDMds0?yKt)hV5S8~9|Y3Mb$!Jy~&!QjyhCn$8J# z0?yKt6?-Zwvf4maC*UkKS;rq+wh~{puC>EgZr4FL6W%i8AT?Q8CbL~;@D`nIlH)Bk zS@XJ3T>u;Z5whbgHCeIrlJs+bHgd@ZRdVAkHCdf7LbZWGwyBUEZ>hC;tW3+R!BrCuZMllXxJye`?2o0$ z+A{Nu3y>LiX~~L}trS^}bIpVr^5QNnS+UKKgUQOrOkho0MBqu5w1X@u$qK-*YB+Pm z7nh}sg3+&gn08%cAQPfrx-QLk!Z~cdjPRGyRw<2291ccADt}x?z$)2CBW>71%nzTJ7U;x8px(KnHEaK+g`AMTN*wCEm}RpMfFyTIvVBrI+=k+a3wR*%M<8xn z?|NM0mtk+LpWA_VqdM9ONF^gdl=e_Qwh&h!pE+( zw)>$%L!~2YyA}z9bAIUM-Yc*raCraIoOAH5Ug2SL1Q0|M6*9>)mF3WOBGqISS}oW zuXi!B-s|_R+7#|j4=o0wlJlt@)E;UVwXe`lvsf`N#|nS6Vxm-JHFE@tTgD8){*vhG z>cz!~#)NX1&;Xrs4aB03xP5YyHmDOwF&m+e{%Y@I0v*$6#YS<=>jK712llx?Q zJSYRQ^!OTsR+{emj8S_)bkWIIEL#(uqIWggen=Bpn_7;Yvll$f_fb5eyjc;oGM5M! z!iR7|7NJ7ZI(LWs+b>1m>z_E^kM~T~VHN^}C*ex?63%mYmr1YSm$DMJT^b&F zTVWY351vaV-zmz5QD+#}{?4;z_29-GC-6y$I_yAT{K$rm{HdvaCiMHzCA+XFp0}gp z0~_x?f5r|QYUz+7vWiru5LGc%GL2i(LrX7O8o{H)uPCC{a-I2kgg4<%_>&*VAEc$| zAM-UDlPE=GO$_<&qK>@3Gw{WW@0^}8)&y1BDg;hGv1D~-HoX_?vm6aavyWS)$5C>H s*e^wdcNAzg8ms(cBiKsS;y~d40njrhRX6&F{{R3007*qoM6N<$g0ieLQ~&?~ literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/ic_start_yellow.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/ic_start_yellow.imageset/ic_start_yellow.png new file mode 100644 index 0000000000000000000000000000000000000000..b2cd068e4956f4390849a1feeb1ed5bfdc33bc68 GIT binary patch literal 1558 zcmV+x2I={UP)Px)&`Cr=RA>d=nO$fcMI69qX7~1TZ4zl>2||*)2#M9C)%t;w;#(Ekhk&956%m5k zB$o&UA4E(I_~L`0n6Ji9M5s_jQ6CEGt6K59Z9sEKb4e_OkhGe_^!8)M|3ArIFPFW$ zoxR;n+CrI`|NOsx`=6Pe+!7MyYG3p3!=hkW!?KUh> z8djjm;aI!i=C^h{%G3ji#fmhO^X3@P@ zYTggXKr1;p8rd&Q@=K{isY>olbQ`~x((^hWY$Yw)?YiDi_3F#Ea}7B&R8?y*vzc+T8MaRgfHXrw&=<{6f-2jg?=2;Za3G~1UJBx+;C!0k zOie|&nyT+zoOcs%1LVTkt{ay0OtXbB00GMfV8j}XAiLZ+3{wZ7FRj5-fF~0i9)be! zm0C1abM(?bb}n>kRBPj=IDtSQ+-*->2kjh!GnIC+#%}#QVeBM4l^d@Euq?tV4{#x0 zcDYUtMVi{4uO!91^*LVk0-vE>ziaZ67@8MB?jd5ku1t1QPo$+4d z16#NO5``Crwa4I<{2_EbzXojQThLnYrhT$0sehCkdlMv1!VkcYa3M}Y(IdIa+qzGQ z!6;hPe0C892OZt|+@yrZGTMWVf zl#Jt>dW5oD>U%R2G7hCHX_j&5z%}rDNUn3emB}-!YZB3#9k}dBLxNxFAn@_=EL_Vv z;3vZNrat3+Y;lZomw8@Qqw?p0G^ET42j4LMg8xq>k}vL$Co^AO&6E%vqa5c^FL$n3 zUnaioM;em4I9VyB7ok#J@wWCoi9Q{Eogd(Kz}yz)IFEX$k9N89PJK7=^X;S#9&xHw zOV3U$!#z^XcZ6fuYx6{~SCzWm!wpAfR-AN-$)-=$$E?}8Bz$vz0V-DOqzeg~@w%3s z^vJmGH18ynf}9@I_QJ;Bw2$Cp{}L1Q^(s;MTJ3WS|2hSdk8)NwhJJP)Px+g-Jv~RCoc^npun$MHGew1=&Fs5rqV!!l=!+|gnurT=iw{0% z5Ltqe7h@2OQ65Y{+?T`{FhJN>MI$K7j8SA91Q$?n|Ncvzq3-1_-PLvHj(_ssTDs1u zbE>OPo$i@7$5bD^m|{2_0_)&l*avoX{Fm}q$0o|Ha0}cFm%@GUe+M}`9d3aCKsgyg z$*zM>!!u!Yw27#(1G;X9cfw&M^!`BqS8zAfUEdD{?S?M!WH<=+hQ+X!&KKc4c&ONb zTJ&{h(ud&p(7(&Nd&}WeI1=`NNzs#mqv15T5*F^FZ|Qpgc7!#9cF%a&0DZ?lr~N2A z1;)Yv6g>vNg#KJRXkQIm9DSMbUFaLLjP_M9=3|ArJhY`X7OsN++;7lUU~LhMU>1M7 zZ=>DPcR`Ch4%S0k2t5{;!>Zz8wEqn?smdu(!LL^6#Kbe8#fZPC-(L-5wDo2|TkY?t zUs;Wb0(Fi;PA7}mr{J0BQA{#O&d-Gtp`fGa8mJ>JEsjOtY^Xe;KkN>re-BjfR2=yY zhM*rpAHtzdcn;+xs71*H|IUAeCY{%5QHOxe?saUDpK#!FcDg@mSS`1CM5~xhj zGjGb|eEXEz+A&@WXmP`IRVrUWW*`iKVv@fI!7*V3ip=oU)YIO1E!GFHlC$NmZ$kcB zm=@Xz8=-V7FkS{zLFc?3bqaVVrjkB9cs4~j=h9qzB4B>SghpqBj>uB!^--!77%j=s z4j6vah{_!bbhdlaI9hJ35}>pgjes4I3zG^f!7xJFpp-hv|w{-h=KC=%vkU zxVMx7t&9aeB_yF3gP=_oyL=|lDDBEM&aQ7Ln~!s4VTK7*PI8Uu))`PHjv1q>uG7AQc|s0C?+Bp`_7xbmqLv~PB(k2vu%axu^ljkj$y9zRX51S zq%D6>E0ALRFDb?r4%Klu&vjlxsaTa;6_q#X2WX{V%hkevehe3_D7mZRi1Gt`-^}Nn z#0Gxl{PObhiLTZ;UAApwmda7GVjT)((@Im+i;87SQ>`;Y*&f+HU`)qN*T4*RndmHM zo8A$+DF!IjwV?M2^{kNd`gj=|yHQvlL8sqo~~ys2K4bkfiN~Ypit*`44ALIwE$h6MtzTqfh@^NrTJs&Heb8?3$VY^ z>#-el+FLRcECpUI$U6tNTrUOX&H3QK-P||3~KU3FZ5cQRPPIIMY0&{ z>CLO^t!t4ths{-~RBGNXPg9)6vz{%@JN`4*+5C|p&Roq}6kjSiTzLJwX6d*U?Rd?# zR%-PK2$r~9L|tD^V?$Y7TEve0n*TI7)ES~b+%_+O}uv-SNWfw`QL8hywYdH%ZO03my-P;t_hy zka0yvr0?v2h|XKno3z}5OsrjSgE#+u)JsCUpaIIrde{kOK~ID~hDn_+9Jd77K3NPv zR+*%}QA)RBK*_t$wH&VJ*9=i676K(d+QRmxY5GFS-RQXkN@ocC#Aj?01$tiIhB8)X z@hF%S-597X_B9M~ww%m%bWVodVN#4?py|vz_9`h*dfe!QbqDPAv6P%XR=y1PLz}Q# z#gyfsgl-R%9omV#U@DAcv@$p;Pz2T8^`Sg{0t^Xou@*;Z?QKxD_)w0&8ET$C z;cys)2az&k7g1M4*CV3myB^xLT9-SqVl(vDQ8Rd>z}9Jg0*n8*qrmRCG|O9%DJTdddBpMSr3aD z)e?Qm?GvT9jH?=S?kZnsge~E;=FlsxQtpZ`HjHU8C`q~tu7}lHh&AZei&3j`9D9z! zIrKaQl|pA-jJ4=^5}pO4qbg@*ft3nQm%^b?PMiw$vZZeY+BI6BgK#g@W3&@~0rift d0`7xV!+)g(s)o^{v!eh2002ovPDHLkV1mTny9NLN literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/photo_user.imageset/photo_user@2x.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/photo_user.imageset/photo_user@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..a6251aacde1fa9346af920e11698207e6f8a0698 GIT binary patch literal 3224 zcmV;J3}^F+P)Px>Qb|NXRCodHoqOQRKJ-``3e4fcJqxLyQ1HcaMMPihgSH zv}g#0J`H{boSdg}Lz#ba{UG=#sCWJ5hO)_}#s)i*z6ZD$I10=QD=4@CTm-(5S3wcw zVgx9H<$!I35CMk4&*#7|gRjrvP4C`Y$-mj)O5`Uq>UWwvf{IhXsRj>3&f@eD^3MYm z8JC5Vyfv zu1*Gjvn{8e4Bs)Y?dK!!HZ8wbQ-S?pkqsvI23;qt&yFa5^aLIbOrs3JwL5&rx z!&j3q8`MgqE$390lTMXJWz}JzhzKwhI`rFQHWPUfpb4NdGRVcm4A|oCsLwYw_)y;OU_HDo_veRue*3S1Y7}X)+Aoegb)Mjj$UB4b|6j=WfPVm=1&e~+ zF{Ig$&O6BdrCgi{b`=TKcqxxqGX`8lfcbD{-}yI?{!wtVXKuCTuGz;-?2YQsuKc}# z`e%b0op-1DA5T47s+$O)C++)&9X;I3*cO`Cz zB0ULTMD}%4FGT-Y;5yJZ48efL1U3?A1+}Af0$*hLCMD{3#6TwzKzHDc_@JBU&&Y>? zdWSl4b(@;)xmp5#U|UYH7k|N=R`P!3*}TRCw_r!J1C2=zCH;>B@k52&1 z2%wdzRkUBbdRpO|M7r;JzDDJz2G$Q};m_Hg{n9#t`e8Kow2P?7pmmM5?!*YtmY&|v z%o71r=33~`=w7>eQ%UdhOqW*l?!r!}H?Q{lmwM*oedyO0N$RIxl73Vk`=OGU$M;yq z0Ry^g+NqjB<~63!w~;jpHrdX_%g}g&bIooQ-h;XcZq;UL)9&l(ri5lkzcuMiVvGPy zbkt917XgMr$GzZKP-pnGyXN~Ok9^#S{gGhkFcAkeX7S~3RzE$AL5-bS_EU@izPhC% zdSBDVPkpPWCtpRi_T2K0QXz-_?y0X;x6~?cf>U0C(#HWTS8)vfeQ!+q?Lj zcMEa`z|v`fea^d0*w!kBR`=BS^n9h+_a>v{yuL z5&;guSDn0(>$-C!mxbEBx(^5TFUygfb|0nOx}4>G7gImZ!O&pv-~?j?fQ`CB5&^UV zXgSd6(WaLr--hAPBfw2%5tL!~_Kftj-(v*GV5ct0Nd(X@YpBiow(m(L1cHAL#E<^m z&{(Cvaz*9qH1)qRxHFjcdyD`@bwi+bl99jO5t=71!`F0_7=YjURj)PpvV8zPwR1tI zrN>c7vx0VYipbL#>Kzzco?wgsMNl8Gjbse4tMM&zWg1+h4$ZdHc$Cw zq3zf7tYwSHa_G{YjF#>ek%@wcTDgtZ{tW8>x z)LFOCZ`zmO?~cHDv=Jcg1_starMQzsfY6^PtxR4AL(@xPD!BWjEQhLyUBNd#C+qxDsAReqD_O8hQ6 z0{kNIn@02hy^Wt~zsCq*SgD(s+#To8=rc{@M<8pKV6saWHL6{YC%Y8vkANaPp+3@ddLlQF=Z8I67$>A%m&FFRRJ+*}-)U$8^p!=C&o*nDnt z`WDbuSd}Ei2w-WcnVdub&0}rTr;-qA1dzWMaPfZdy~^-}%g}qiC;hI~svoW1wBKU{ zu(Z@nP9lKT*zcz86TqxHCp3z50%takrN4gV(aDq1t=}u~Xv&Fd+mE-SHJ#nX2;hX{ z>MBVhfc|viMiJmZGBnTqn+gVsiUhvh3w_OB?bolB+h2b9wF)E{BS0e?HN0+&09Voe zuY!ZXW59V}sPJ;Aj+NxstPHz9Z%mI7pplIlUh64Ony%|~g=nk1KYZK|jt4`12fhXW z9s+%Vc1^QZP<`3Wt5*-TWoEoz#{hbVUP2o$1@{4`flI;A zU|2y86=kQ>=6r;Tdh(@5{V6%c7y+8-sGp$seq+mrBK#E`1>OegyLUwll1m4j%3b2w zlTV?4k!L#tRjYu7+wxe z^z6t3=$`^U#A`+UH6CaVteJ0<>bKMrrLLfW`t^2N(-4>%o0NeHl|U zZ921fC58_#*nvLm9R+SI*uKmS=R&_v_y*)P;CQg<-A`KF3lI@?#dZ-uoahd}N(taR z@GBb5XfeXQ+b|-&;z0*L!bS~Pi+r%+|=&C8^i2y32`SlFA z(mKEq$TvFXa3}PA5 zCs9v#o)+&$p}WA*px%LY!VIUYIz(CmQ!Lr>%0M%6l(7RkTrQe=y z6}FJ@Ze>Kw#em-BJ5XBRX{hpfT%4hVPB2D*PFU-qI(mw`X_9UtojKDyz8jsfZZ-oK zlcjxrt;lBAXp^JPYf~g<^)dr4B7peO&2&Bqc1)mh5j$f*?|kjPcJ<`T1$CO_h&5xt zWdyL)Y4=XEgm|-AhT6+o;S-M?&GXxvh+hZy$4}4a`-}i0Pixd#+0w3}@*_4gpk2LB zklfdt?N*9m*)5-y(^fjz8wbG?ALz%w0w5_jn=c050 zsPhsoZROS#BS3Dddb3~%5x_F56EHeKq{uMY77Scofq&X1)jCM2PrT(UMgYr5&Eyax zKvow_AmeCIXAUQ2RVXN3zrCwp;M9En-h%9RWhO>|uIQ_NTv;N7-fPdFdp>S}Jig4X)15|ZuP6L3F#eUm8?y*v{g%^5NJk;Bblo7amrbOp0 z&P`o;$-~?~_|Ehen7i<5=BbmIvg_WJzaRG@?2MPo%Z$6ACwY0g81JC$?69k9C3iMo zOd{(B-^m-Rriz*-zA;8-i~ebfoBK8#(LFy=yu7QYXgI!T?!$ah>hP0*<^G@5MzEC9 z7G;4nw~V`-6eFb+F4m}N76_bbtPu&&7416tM)hqxeerciFFOO;0jVg!t?MD}3F2ob zCiB|O*F3VQJ+VEB@-`!=KVH0MCXN#H)7&bRIqngJ!M`A10WUjuvvRUNVeJ4MC0ZPJ|!K9*%b>D^{_0`DdCUz3*I1iLl^yrR^|Gd z6?i7orv{TKSpe7crlz5*R1|Y_f8V1-x00L3dvBCX&6toDC}LllYE?_hl7LM^{wBgN z=_qs41-aY;J~TqfC-vP;!DnU?ISbfhl3TFN0bJqn)&B4#Dl>?E2|0(Th@BkOscE3g znek-SkUR@(;w{Q5t{`!$87b7-k{2h)((i&snD6BE>qu9RXq?lAng7K!C#S;r(<`o= zc66Zema#&0e(PV)D%b4j^q4Jz2BVIdllX$M!rG?edOw_p^d7P98Swf`?3uxld@m~( zvKA*dB}b!QpM$HyD6Pf}7=0Nph-g8+P>gyhFVrgXq^Vx7;C!S{g(db#&kvo~T8!XW z%XlU>a`53~y=xE;dwaO0zuFFn!H0qkD#}B(Z=l2q?m~_gX~p(x`|Ick_XQx z@(uT}l!nb0nO9V|Fq98SX@I9N7#LtTO)c4IfU@}TO#B5+ylfPBK}|z4wu|RWyAZow zh8LB(m>jQ1Tv*Z*DY4do1Ub=;Z^%gr^~%h)(gU->XlMA1e54Dbz)c?(s$YVnl@+R# zQ&`S-$PwXZ_`^jXT_(Q>{-j}Z!W_Pj4o8x9YWkpEQwj9m3=U%u`b4!(r?F1XQr&U9 z)oDcQM4`=L9Wu`Nt9B`v7Am;&&72Kdp8z{?UTl?G;TR`L;Wuk7SOopS%nc{4ZV>HW z`JShA!4O&vUrv!8Ma?1W-{G9YjTql@l(J;4l3h!lfGI{E3M=f|0lVnPA|(&ANFUy; zDlEIuMkbi`Wp!HJ&t(~!B=m~B=0xPgvDRS?#8i8+t511x(_9%+9J5 z?wkv%cQxUMjA@l#CQa=Z6eqg%$>tou)l`D9zdGc}ySKh|#ocG;Tkz-zC#zQp9w)-K zdrsfzE<7kz75-GF;Tv2?*9{Lh@Y?ciDUUI@)OGh4K z#VX8XQMK^t>B1qBqsydIx;a7)VXi zu!(%(SBxbrNlsxCw47@omU0Y*!v?4}6y^}wAZPTo=hQQAE7(}Z=*kqZP@lo(+zjam zwc94m8OZsJmbZ%bec;HF3>^M-+Bgd+-C4U5wobn1ZCqd&GL?yo+V1vpif#kd5!nf zj$R~%>phgz8zSu@__fO?NZljRmTy{6g{o54?ufqj-VRh2_39OK=Nv?zTL})?bBsPn z*_m3WK>Lv2em{K%fIK&`(wa+ebyjxNZOexj#tq`iWiUF})TX0D$klY+Z>`ahS# zFM9a)=SP99NIRBNH!T~n1e}uI{83%B|uQUfkgkJ}cu1@`ZjSZE;s zqsR75_?&gR8Qy-;QN>@Uqn=j$-IdgSn3lb1$u8D2hmfoIKV&+2am%7;&QERI9kOg~ zGz@`-TmVGUhOCV@k{;r!Jv>Fzrq#+E-OHk_VAB%c@(}OJ$yTrf6)Dm4NtL8cpLjKi zUtMrFPzC871I&2Nj?uP5HKvhAA9Uhue-SRO<=k(RLXO{O2E-8!EYS;~^Ih)2yta!3vU@s3HgJqm)hp&DY zQudE1d#7yFRB*lw-=76BpxJ@_OZf94NduqLB;VGc>3RIp1JEbBaWc4%#%PzM=RedM z`z@;>|9%P=Vyce}xefe_osBcOn9s?3h$||Vnhc|Lqq9A-1j_9V# zgBdSF&vdk6q<&PEzjzBm2X!W2U;nDSqI51?_|ffIIT;GV&bBuVQ5v=Gpr&Axp>#v|%%^k+mO)3%?5~X29vfEE zi-ireUX$lo!{-$nKGLi;9WABV4>)Yl<=Xi5?XmG7Yiajg&;88SryfGIeKCfOX=%vh zB-A&2tW(q&fp1EAKvwnn{0A?rhwIazz@F!_%j}sgy8TiVS8(Q?fh*N)0>`~voYZ`d z9Bo`R&{=POs_;m=;$9YE6whBA?K|&oAagE!Q-rOS9Rhj>EC4x6*E7R&-Pbnxr#5J6 z_{5}A?bJ#kjUQWIZ9L!+$3eIK|4**%l-+ns4ta{*x(%_8j0 z0r zmzx_;7sa9$i{*qry+@pERE}d2mg%!kxbqyJb~zytoTE0o#mE5+zGTbss6iq+4F@}G z(4{M>Yuo((PI^^g)`uH7Uqc^G{oy?o=4sXNVCWPs6)~{xUk1i5)}}(XSCFkBQRvq# z36Q)89tW9Lwm!&;Fj&M$cWccpn=IgN{t>Rf3Kiagzx~(%_E!bD%f!t3{gSVU_y+@s zMdyV*Qe+p#RMyFK6DsGoE43Kjujxdx7S(6&8 X&Wvax%JzY8YGA*evu%|PE%E;VI%p}I literal 0 HcmV?d00001 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.swift new file mode 100644 index 0000000..5195faa --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.swift @@ -0,0 +1,24 @@ +// +// RepositoryTableViewCell.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 16/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +class RepositoryTableViewCell: UITableViewCell { + + static let identifier: String = "RepositoryTableViewCell" + + static var cellHeight: CGFloat { + return 140 + } + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib new file mode 100644 index 0000000..310b8ff --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Home.storyboard b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Home.storyboard index 03851b4..c2d8c90 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Home.storyboard +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Storyboard/Home.storyboard @@ -14,7 +14,19 @@ + + + + + + + + + + + + From 223a5b77554def97c9160ef9f515e68ba66c857b Mon Sep 17 00:00:00 2001 From: felipe Date: Mon, 17 Feb 2020 13:32:13 -0300 Subject: [PATCH 06/25] install cocoapods --- TesteArenaFelipePerius/Podfile | 22 + TesteArenaFelipePerius/Podfile.lock | 24 + TesteArenaFelipePerius/Pods/Alamofire/LICENSE | 19 + .../Pods/Alamofire/README.md | 200 ++ .../Pods/Alamofire/Source/AFError.swift | 840 +++++++ .../Pods/Alamofire/Source/Alamofire.swift | 29 + .../Alamofire/Source/AlamofireExtended.swift | 58 + .../Source/CachedResponseHandler.swift | 91 + .../Source/DispatchQueue+Alamofire.swift | 37 + .../Pods/Alamofire/Source/EventMonitor.swift | 844 +++++++ .../Pods/Alamofire/Source/HTTPHeaders.swift | 445 ++++ .../Pods/Alamofire/Source/HTTPMethod.swift | 54 + .../Alamofire/Source/MultipartFormData.swift | 544 ++++ .../Alamofire/Source/MultipartUpload.swift | 87 + .../Source/NetworkReachabilityManager.swift | 266 ++ .../Pods/Alamofire/Source/Notifications.swift | 115 + .../Source/OperationQueue+Alamofire.swift | 49 + .../Alamofire/Source/ParameterEncoder.swift | 184 ++ .../Alamofire/Source/ParameterEncoding.swift | 314 +++ .../Pods/Alamofire/Source/Protector.swift | 167 ++ .../Alamofire/Source/RedirectHandler.swift | 95 + .../Pods/Alamofire/Source/Request.swift | 1460 +++++++++++ .../Alamofire/Source/RequestInterceptor.swift | 243 ++ .../Alamofire/Source/RequestTaskMap.swift | 136 + .../Pods/Alamofire/Source/Response.swift | 399 +++ .../Source/ResponseSerialization.swift | 800 ++++++ .../Alamofire/Source/Result+Alamofire.swift | 109 + .../Pods/Alamofire/Source/RetryPolicy.swift | 363 +++ .../Source/ServerTrustEvaluation.swift | 606 +++++ .../Pods/Alamofire/Source/Session.swift | 1039 ++++++++ .../Alamofire/Source/SessionDelegate.swift | 326 +++ ...URLConvertible+URLRequestConvertible.swift | 105 + .../Source/URLEncodedFormEncoder.swift | 973 ++++++++ .../Source/URLRequest+Alamofire.swift | 39 + .../URLSessionConfiguration+Alamofire.swift | 37 + .../Pods/Alamofire/Source/Validation.swift | 247 ++ TesteArenaFelipePerius/Pods/Manifest.lock | 24 + .../Pods/ObjectMapper/LICENSE | 8 + .../Pods/ObjectMapper/README-CN.md | 500 ++++ .../Sources/CodableTransform.swift | 73 + .../Sources/CustomDateFormatTransform.swift | 40 + .../ObjectMapper/Sources/DataTransform.swift | 50 + .../Sources/DateFormatterTransform.swift | 54 + .../ObjectMapper/Sources/DateTransform.swift | 75 + .../Sources/DictionaryTransform.swift | 76 + .../ObjectMapper/Sources/EnumOperators.swift | 120 + .../ObjectMapper/Sources/EnumTransform.swift | 50 + .../Pods/ObjectMapper/Sources/FromJSON.swift | 202 ++ .../Sources/HexColorTransform.swift | 144 ++ .../Sources/ISO8601DateTransform.swift | 47 + .../Sources/ImmutableMappable.swift | 376 +++ .../Sources/IntegerOperators.swift | 171 ++ .../Pods/ObjectMapper/Sources/Map.swift | 204 ++ .../Pods/ObjectMapper/Sources/MapError.swift | 68 + .../Pods/ObjectMapper/Sources/Mappable.swift | 136 + .../Pods/ObjectMapper/Sources/Mapper.swift | 491 ++++ .../Sources/NSDecimalNumberTransform.swift | 52 + .../Pods/ObjectMapper/Sources/Operators.swift | 398 +++ .../Pods/ObjectMapper/Sources/ToJSON.swift | 177 ++ .../ObjectMapper/Sources/TransformOf.swift | 48 + .../Sources/TransformOperators.swift | 709 ++++++ .../ObjectMapper/Sources/TransformType.swift | 35 + .../ObjectMapper/Sources/URLTransform.swift | 67 + .../Pods/Pods.xcodeproj/project.pbxproj | 2178 +++++++++++++++++ .../Pods/RxSwift/LICENSE.md | 9 + .../Pods/RxSwift/Platform/AtomicInt.swift | 71 + .../RxSwift/Platform/DataStructures/Bag.swift | 187 ++ .../DataStructures/InfiniteSequence.swift | 26 + .../DataStructures/PriorityQueue.swift | 111 + .../Platform/DataStructures/Queue.swift | 152 ++ .../RxSwift/Platform/DeprecationWarner.swift | 43 + .../Platform/DispatchQueue+Extensions.swift | 21 + .../RxSwift/Platform/Platform.Darwin.swift | 36 + .../RxSwift/Platform/Platform.Linux.swift | 37 + .../Pods/RxSwift/Platform/RecursiveLock.swift | 34 + TesteArenaFelipePerius/Pods/RxSwift/README.md | 217 ++ .../Pods/RxSwift/RxSwift/AnyObserver.swift | 72 + .../Pods/RxSwift/RxSwift/Cancelable.swift | 13 + .../RxSwift/Concurrency/AsyncLock.swift | 102 + .../RxSwift/RxSwift/Concurrency/Lock.swift | 36 + .../RxSwift/Concurrency/LockOwnerType.swift | 21 + .../Concurrency/SynchronizedDisposeType.swift | 18 + .../Concurrency/SynchronizedOnType.swift | 18 + .../SynchronizedUnsubscribeType.swift | 13 + .../RxSwift/ConnectableObservableType.swift | 19 + .../Pods/RxSwift/RxSwift/Deprecated.swift | 228 ++ .../Pods/RxSwift/RxSwift/Disposable.swift | 13 + .../Disposables/AnonymousDisposable.swift | 59 + .../Disposables/BinaryDisposable.swift | 53 + .../Disposables/BooleanDisposable.swift | 33 + .../Disposables/CompositeDisposable.swift | 151 ++ .../RxSwift/Disposables/Disposables.swift | 13 + .../RxSwift/Disposables/DisposeBag.swift | 114 + .../RxSwift/Disposables/DisposeBase.swift | 22 + .../RxSwift/Disposables/NopDisposable.swift | 32 + .../Disposables/RefCountDisposable.swift | 113 + .../Disposables/ScheduledDisposable.swift | 50 + .../Disposables/SerialDisposable.swift | 75 + .../SingleAssignmentDisposable.swift | 70 + .../Disposables/SubscriptionDisposable.swift | 21 + .../Pods/RxSwift/RxSwift/Errors.swift | 52 + .../Pods/RxSwift/RxSwift/Event.swift | 106 + .../RxSwift/RxSwift/Extensions/Bag+Rx.swift | 50 + .../RxSwift/Extensions/String+Rx.swift | 22 + .../RxSwift/RxSwift/GroupedObservable.swift | 37 + .../RxSwift/ImmediateSchedulerType.swift | 36 + .../Pods/RxSwift/RxSwift/Observable.swift | 44 + .../RxSwift/ObservableConvertibleType.swift | 18 + .../RxSwift/ObservableType+Extensions.swift | 131 + .../Pods/RxSwift/RxSwift/ObservableType.swift | 47 + .../RxSwift/RxSwift/Observables/AddRef.swift | 44 + .../RxSwift/RxSwift/Observables/Amb.swift | 157 ++ .../RxSwift/RxSwift/Observables/AsMaybe.swift | 49 + .../RxSwift/Observables/AsSingle.swift | 52 + .../RxSwift/RxSwift/Observables/Buffer.swift | 139 ++ .../RxSwift/RxSwift/Observables/Catch.swift | 235 ++ .../CombineLatest+Collection.swift | 157 ++ .../Observables/CombineLatest+arity.swift | 843 +++++++ .../RxSwift/Observables/CombineLatest.swift | 132 + .../RxSwift/RxSwift/Observables/Concat.swift | 131 + .../RxSwift/RxSwift/Observables/Create.swift | 78 + .../RxSwift/Observables/Debounce.swift | 118 + .../RxSwift/RxSwift/Observables/Debug.swift | 103 + .../RxSwift/Observables/DefaultIfEmpty.swift | 66 + .../RxSwift/Observables/Deferred.swift | 74 + .../RxSwift/RxSwift/Observables/Delay.swift | 179 ++ .../Observables/DelaySubscription.swift | 58 + .../RxSwift/Observables/Dematerialize.swift | 51 + .../Observables/DistinctUntilChanged.swift | 125 + .../Pods/RxSwift/RxSwift/Observables/Do.swift | 93 + .../RxSwift/Observables/ElementAt.swift | 92 + .../RxSwift/RxSwift/Observables/Empty.swift | 27 + .../RxSwift/Observables/Enumerated.swift | 62 + .../RxSwift/RxSwift/Observables/Error.swift | 33 + .../RxSwift/RxSwift/Observables/Filter.swift | 90 + .../RxSwift/RxSwift/Observables/First.swift | 42 + .../RxSwift/Observables/Generate.swift | 87 + .../RxSwift/RxSwift/Observables/GroupBy.swift | 134 + .../RxSwift/RxSwift/Observables/Just.swift | 87 + .../RxSwift/RxSwift/Observables/Map.swift | 108 + .../RxSwift/Observables/Materialize.swift | 44 + .../RxSwift/RxSwift/Observables/Merge.swift | 598 +++++ .../RxSwift/Observables/Multicast.swift | 408 +++ .../RxSwift/RxSwift/Observables/Never.swift | 27 + .../RxSwift/Observables/ObserveOn.swift | 231 ++ .../RxSwift/Observables/Optional.swift | 95 + .../RxSwift/Observables/Producer.swift | 92 + .../RxSwift/RxSwift/Observables/Range.swift | 73 + .../RxSwift/RxSwift/Observables/Reduce.swift | 109 + .../RxSwift/RxSwift/Observables/Repeat.swift | 57 + .../RxSwift/Observables/RetryWhen.swift | 182 ++ .../RxSwift/RxSwift/Observables/Sample.swift | 133 + .../RxSwift/RxSwift/Observables/Scan.swift | 101 + .../RxSwift/Observables/Sequence.swift | 89 + .../Observables/ShareReplayScope.swift | 458 ++++ .../RxSwift/Observables/SingleAsync.swift | 105 + .../RxSwift/RxSwift/Observables/Sink.swift | 75 + .../RxSwift/RxSwift/Observables/Skip.swift | 159 ++ .../RxSwift/Observables/SkipUntil.swift | 139 ++ .../RxSwift/Observables/SkipWhile.swift | 75 + .../RxSwift/Observables/StartWith.swift | 42 + .../RxSwift/Observables/SubscribeOn.swift | 83 + .../RxSwift/RxSwift/Observables/Switch.swift | 233 ++ .../RxSwift/Observables/SwitchIfEmpty.swift | 104 + .../RxSwift/RxSwift/Observables/Take.swift | 180 ++ .../RxSwift/Observables/TakeLast.swift | 78 + .../RxSwift/Observables/TakeUntil.swift | 227 ++ .../RxSwift/Observables/TakeWhile.swift | 85 + .../RxSwift/Observables/Throttle.swift | 162 ++ .../RxSwift/RxSwift/Observables/Timeout.swift | 151 ++ .../RxSwift/RxSwift/Observables/Timer.swift | 116 + .../RxSwift/RxSwift/Observables/ToArray.swift | 66 + .../RxSwift/RxSwift/Observables/Using.swift | 90 + .../RxSwift/RxSwift/Observables/Window.swift | 169 ++ .../RxSwift/Observables/WithLatestFrom.swift | 149 ++ .../RxSwift/Observables/Zip+Collection.swift | 169 ++ .../RxSwift/Observables/Zip+arity.swift | 990 ++++++++ .../RxSwift/RxSwift/Observables/Zip.swift | 153 ++ .../Pods/RxSwift/RxSwift/ObserverType.swift | 40 + .../RxSwift/Observers/AnonymousObserver.swift | 32 + .../RxSwift/Observers/ObserverBase.swift | 34 + .../RxSwift/Observers/TailRecursiveSink.swift | 151 ++ .../Pods/RxSwift/RxSwift/Reactive.swift | 74 + .../Pods/RxSwift/RxSwift/Rx.swift | 141 ++ .../Pods/RxSwift/RxSwift/RxMutableBox.swift | 27 + .../Pods/RxSwift/RxSwift/SchedulerType.swift | 71 + .../ConcurrentDispatchQueueScheduler.swift | 84 + .../Schedulers/ConcurrentMainScheduler.swift | 88 + .../Schedulers/CurrentThreadScheduler.swift | 144 ++ .../Schedulers/HistoricalScheduler.swift | 22 + .../HistoricalSchedulerTimeConverter.swift | 67 + .../Internal/DispatchQueueConfiguration.swift | 104 + .../Internal/InvocableScheduledItem.swift | 22 + .../Schedulers/Internal/InvocableType.swift | 17 + .../Schedulers/Internal/ScheduledItem.swift | 35 + .../Internal/ScheduledItemType.swift | 13 + .../RxSwift/Schedulers/MainScheduler.swift | 80 + .../Schedulers/OperationQueueScheduler.swift | 56 + .../Schedulers/RecursiveScheduler.swift | 220 ++ .../SchedulerServices+Emulation.swift | 61 + .../SerialDispatchQueueScheduler.swift | 132 + .../Schedulers/VirtualTimeConverterType.swift | 95 + .../Schedulers/VirtualTimeScheduler.swift | 269 ++ .../RxSwift/Subjects/AsyncSubject.swift | 155 ++ .../RxSwift/Subjects/BehaviorSubject.swift | 166 ++ .../RxSwift/Subjects/PublishSubject.swift | 150 ++ .../RxSwift/Subjects/ReplaySubject.swift | 281 +++ .../RxSwift/Subjects/SubjectType.swift | 21 + .../RxSwift/SwiftSupport/SwiftSupport.swift | 18 + .../RxSwift/Traits/Completable+AndThen.swift | 132 + .../RxSwift/RxSwift/Traits/Completable.swift | 259 ++ .../Pods/RxSwift/RxSwift/Traits/Maybe.swift | 293 +++ .../ObservableType+PrimitiveSequence.swift | 55 + .../Traits/PrimitiveSequence+Zip+arity.swift | 521 ++++ .../RxSwift/Traits/PrimitiveSequence.swift | 267 ++ .../Pods/RxSwift/RxSwift/Traits/Single.swift | 337 +++ .../Alamofire/Alamofire-Info.plist | 26 + .../Alamofire/Alamofire-dummy.m | 5 + .../Alamofire/Alamofire-prefix.pch | 12 + .../Alamofire/Alamofire-umbrella.h | 16 + .../Alamofire/Alamofire.modulemap | 6 + .../Alamofire/Alamofire.xcconfig | 11 + .../ObjectMapper/ObjectMapper-Info.plist | 26 + .../ObjectMapper/ObjectMapper-dummy.m | 5 + .../ObjectMapper/ObjectMapper-prefix.pch | 12 + .../ObjectMapper/ObjectMapper-umbrella.h | 16 + .../ObjectMapper/ObjectMapper.modulemap | 6 + .../ObjectMapper/ObjectMapper.xcconfig | 10 + ...s-TesteArenaFelipePeriusUITests-Info.plist | 26 + ...ipePeriusUITests-acknowledgements.markdown | 50 + ...FelipePeriusUITests-acknowledgements.plist | 94 + ...rius-TesteArenaFelipePeriusUITests-dummy.m | 5 + ...ts-frameworks-Debug-input-files.xcfilelist | 4 + ...s-frameworks-Debug-output-files.xcfilelist | 3 + ...-frameworks-Release-input-files.xcfilelist | 4 + ...frameworks-Release-output-files.xcfilelist | 3 + ...esteArenaFelipePeriusUITests-frameworks.sh | 175 ++ ...s-TesteArenaFelipePeriusUITests-umbrella.h | 16 + ...steArenaFelipePeriusUITests.debug.xcconfig | 12 + ...us-TesteArenaFelipePeriusUITests.modulemap | 6 + ...eArenaFelipePeriusUITests.release.xcconfig | 12 + .../Pods-TesteArenaFelipePerius-Info.plist | 26 + ...renaFelipePerius-acknowledgements.markdown | 50 + ...teArenaFelipePerius-acknowledgements.plist | 94 + .../Pods-TesteArenaFelipePerius-dummy.m | 5 + ...us-frameworks-Debug-input-files.xcfilelist | 4 + ...s-frameworks-Debug-output-files.xcfilelist | 3 + ...-frameworks-Release-input-files.xcfilelist | 4 + ...frameworks-Release-output-files.xcfilelist | 3 + .../Pods-TesteArenaFelipePerius-frameworks.sh | 175 ++ .../Pods-TesteArenaFelipePerius-umbrella.h | 16 + ...Pods-TesteArenaFelipePerius.debug.xcconfig | 12 + .../Pods-TesteArenaFelipePerius.modulemap | 6 + ...ds-TesteArenaFelipePerius.release.xcconfig | 12 + ...ods-TesteArenaFelipePeriusTests-Info.plist | 26 + ...elipePeriusTests-acknowledgements.markdown | 3 + ...naFelipePeriusTests-acknowledgements.plist | 29 + .../Pods-TesteArenaFelipePeriusTests-dummy.m | 5 + ...ods-TesteArenaFelipePeriusTests-umbrella.h | 16 + ...TesteArenaFelipePeriusTests.debug.xcconfig | 9 + ...Pods-TesteArenaFelipePeriusTests.modulemap | 6 + ...steArenaFelipePeriusTests.release.xcconfig | 9 + .../RxSwift/RxSwift-Info.plist | 26 + .../RxSwift/RxSwift-dummy.m | 5 + .../RxSwift/RxSwift-prefix.pch | 12 + .../RxSwift/RxSwift-umbrella.h | 16 + .../RxSwift/RxSwift.modulemap | 6 + .../RxSwift/RxSwift.xcconfig | 10 + .../project.pbxproj | 159 ++ .../UserInterfaceState.xcuserstate | Bin 30479 -> 34160 bytes .../xcschemes/xcschememanagement.plist | 2 +- .../contents.xcworkspacedata | 10 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../Scenes/Home/HomeDataScource.swift | 13 + .../Scenes/Home/HomeViewController.swift | 4 +- .../View/Storyboard/Home.storyboard | 3 + 276 files changed, 37008 insertions(+), 2 deletions(-) create mode 100644 TesteArenaFelipePerius/Podfile create mode 100644 TesteArenaFelipePerius/Podfile.lock create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/LICENSE create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/README.md create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/AFError.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/Alamofire.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/AlamofireExtended.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/CachedResponseHandler.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/EventMonitor.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/HTTPHeaders.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/HTTPMethod.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/MultipartFormData.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/MultipartUpload.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/NetworkReachabilityManager.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/Notifications.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/OperationQueue+Alamofire.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/ParameterEncoder.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/ParameterEncoding.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/Protector.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/RedirectHandler.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/Request.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/RequestInterceptor.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/RequestTaskMap.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/Response.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/ResponseSerialization.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/Result+Alamofire.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/RetryPolicy.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/ServerTrustEvaluation.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/Session.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/SessionDelegate.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/URLEncodedFormEncoder.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/URLRequest+Alamofire.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift create mode 100644 TesteArenaFelipePerius/Pods/Alamofire/Source/Validation.swift create mode 100644 TesteArenaFelipePerius/Pods/Manifest.lock create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/LICENSE create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/README-CN.md create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/CodableTransform.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DataTransform.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DateFormatterTransform.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DateTransform.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DictionaryTransform.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/EnumOperators.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/EnumTransform.swift create mode 100755 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/FromJSON.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/HexColorTransform.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ImmutableMappable.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/IntegerOperators.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Map.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/MapError.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Mappable.swift create mode 100755 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Mapper.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift create mode 100755 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Operators.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ToJSON.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformOf.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformOperators.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformType.swift create mode 100644 TesteArenaFelipePerius/Pods/ObjectMapper/Sources/URLTransform.swift create mode 100644 TesteArenaFelipePerius/Pods/Pods.xcodeproj/project.pbxproj create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/LICENSE.md create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/AtomicInt.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/Bag.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/Queue.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/DeprecationWarner.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/Platform.Darwin.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/Platform.Linux.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/Platform/RecursiveLock.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/README.md create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/AnyObserver.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Cancelable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/Lock.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ConnectableObservableType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Deprecated.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/Disposables.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Errors.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Event.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/GroupedObservable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AddRef.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Amb.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AsSingle.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Buffer.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Catch.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Concat.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Create.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Debounce.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Debug.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Deferred.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Delay.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Do.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ElementAt.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Empty.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Enumerated.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Error.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Filter.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/First.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Generate.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/GroupBy.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Just.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Map.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Materialize.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Merge.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Multicast.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Never.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Optional.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Producer.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Range.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Reduce.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Repeat.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sample.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Scan.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sequence.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sink.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Skip.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/StartWith.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Switch.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Take.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeLast.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Throttle.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Timeout.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Timer.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ToArray.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Using.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Window.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObserverType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Reactive.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Rx.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/RxMutableBox.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/SchedulerType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Traits/Completable.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Traits/Maybe.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift create mode 100644 TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Traits/Single.swift create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Alamofire/Alamofire-Info.plist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Alamofire/Alamofire-dummy.m create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Alamofire/Alamofire.modulemap create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Alamofire/Alamofire.xcconfig create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/ObjectMapper/ObjectMapper-Info.plist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/ObjectMapper/ObjectMapper-dummy.m create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/ObjectMapper/ObjectMapper-prefix.pch create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/ObjectMapper/ObjectMapper-umbrella.h create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/ObjectMapper/ObjectMapper.modulemap create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/ObjectMapper/ObjectMapper.xcconfig create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-Info.plist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.markdown create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.plist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-dummy.m create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-input-files.xcfilelist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-output-files.xcfilelist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-input-files.xcfilelist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-output-files.xcfilelist create mode 100755 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-umbrella.h create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.modulemap create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.release.xcconfig create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-Info.plist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.markdown create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.plist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-dummy.m create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-input-files.xcfilelist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-output-files.xcfilelist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-input-files.xcfilelist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-output-files.xcfilelist create mode 100755 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks.sh create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-umbrella.h create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.debug.xcconfig create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.modulemap create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.release.xcconfig create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests-Info.plist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests-acknowledgements.markdown create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests-acknowledgements.plist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests-dummy.m create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests-umbrella.h create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.debug.xcconfig create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.modulemap create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.release.xcconfig create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/RxSwift/RxSwift-Info.plist create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/RxSwift/RxSwift-dummy.m create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/RxSwift/RxSwift-prefix.pch create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/RxSwift/RxSwift-umbrella.h create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/RxSwift/RxSwift.modulemap create mode 100644 TesteArenaFelipePerius/Pods/Target Support Files/RxSwift/RxSwift.xcconfig create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius.xcworkspace/contents.xcworkspacedata create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeDataScource.swift diff --git a/TesteArenaFelipePerius/Podfile b/TesteArenaFelipePerius/Podfile new file mode 100644 index 0000000..7ecea8e --- /dev/null +++ b/TesteArenaFelipePerius/Podfile @@ -0,0 +1,22 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'TesteArenaFelipePerius' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! + + # Pods for TesteArenaFelipePerius + pod 'Alamofire', '~> 5.0' + pod 'RxSwift', '~> 4.0' + pod 'ObjectMapper', '~> 3.4' + + target 'TesteArenaFelipePeriusTests' do + inherit! :search_paths + # Pods for testing + end + + target 'TesteArenaFelipePeriusUITests' do + # Pods for testing + end + +end diff --git a/TesteArenaFelipePerius/Podfile.lock b/TesteArenaFelipePerius/Podfile.lock new file mode 100644 index 0000000..81647ea --- /dev/null +++ b/TesteArenaFelipePerius/Podfile.lock @@ -0,0 +1,24 @@ +PODS: + - Alamofire (5.0.0) + - ObjectMapper (3.5.1) + - RxSwift (4.5.0) + +DEPENDENCIES: + - Alamofire (~> 5.0) + - ObjectMapper (~> 3.4) + - RxSwift (~> 4.0) + +SPEC REPOS: + trunk: + - Alamofire + - ObjectMapper + - RxSwift + +SPEC CHECKSUMS: + Alamofire: 58ff2bfb8daaacaa233d5c36e37b10a5248f59b1 + ObjectMapper: 70187b8941977c62ccfb423caf6b50be405cabf0 + RxSwift: f172070dfd1a93d70a9ab97a5a01166206e1c575 + +PODFILE CHECKSUM: 8aff128e776311a1989b50e8a54660c9cb8a4c53 + +COCOAPODS: 1.8.4 diff --git a/TesteArenaFelipePerius/Pods/Alamofire/LICENSE b/TesteArenaFelipePerius/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..ccafad5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/TesteArenaFelipePerius/Pods/Alamofire/README.md b/TesteArenaFelipePerius/Pods/Alamofire/README.md new file mode 100644 index 0000000..5d8112f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/README.md @@ -0,0 +1,200 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/alamofire.png) + +[![Build Status](https://github.com/Alamofire/Alamofire/workflows/Alamofire%20CI/badge.svg?branch=master)](https://github.com/Alamofire/Alamofire/actions) +[![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) +[![Open Source Helpers](https://www.codetriage.com/alamofire/alamofire/badges/users.svg)](https://www.codetriage.com/alamofire/alamofire) + +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#using-alamofire) + - [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) + - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) + - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) +- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) + - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#sessiondelegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) + - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests) + - **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 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 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ +- Xcode 10.2+ +- Swift 5+ + +## Migration Guides + +- [Alamofire 5.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md) +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication +- If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. +- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. +- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better! +- If you **want to contribute**, submit a pull request! + +## Installation + +### CocoaPods + +[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +pod 'Alamofire', '~> 5.0' +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" "5.0" +``` + +### 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 +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.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 macOS. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as 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` + +## Resolved Radars + +The following radars have been resolved over time after being filed against the Alamofire project. + +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage. + - (Resolved): 9/1/17 in Xcode 9 beta 6. +- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ + - (Resolved): Just add `CFNetwork` to your linked frameworks. + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## 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. diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/AFError.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000..8ab282c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,840 @@ +// +// AFError.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +public enum AFError: Error { + /// The underlying reason the `.multipartEncodingFailed` error occurred. + public enum MultipartEncodingFailureReason { + /// The `fileURL` provided for reading an encodable body part isn't a file `URL`. + case bodyPartURLInvalid(url: URL) + /// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension. + case bodyPartFilenameInvalid(in: URL) + /// The file at the `fileURL` provided was not reachable. + case bodyPartFileNotReachable(at: URL) + /// Attempting to check the reachability of the `fileURL` provided threw an error. + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + /// The file at the `fileURL` provided is actually a directory. + case bodyPartFileIsDirectory(at: URL) + /// The size of the file at the `fileURL` provided was not returned by the system. + case bodyPartFileSizeNotAvailable(at: URL) + /// The attempt to find the size of the file at the `fileURL` provided threw an error. + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + /// An `InputStream` could not be created for the provided `fileURL`. + case bodyPartInputStreamCreationFailed(for: URL) + /// An `OutputStream` could not be created when attempting to write the encoded data to disk. + case outputStreamCreationFailed(for: URL) + /// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`. + case outputStreamFileAlreadyExists(at: URL) + /// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`. + case outputStreamURLInvalid(url: URL) + /// The attempt to write the encoded body data to disk failed with an underlying error. + case outputStreamWriteFailed(error: Error) + /// The attempt to read an encoded body part `InputStream` failed with underlying system error. + case inputStreamReadFailed(error: Error) + } + + /// The underlying reason the `.parameterEncodingFailed` error occurred. + public enum ParameterEncodingFailureReason { + /// The `URLRequest` did not have a `URL` to encode. + case missingURL + /// JSON serialization failed with an underlying system error during the encoding process. + case jsonEncodingFailed(error: Error) + /// Custom parameter encoding failed due to the associated `Error`. + case customEncodingFailed(error: Error) + } + + /// The underlying reason the `.parameterEncoderFailed` error occurred. + public enum ParameterEncoderFailureReason { + /// Possible missing components. + public enum RequiredComponent { + /// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding. + case url + /// The `HTTPMethod` could not be extracted from the passed `URLRequest`. + case httpMethod(rawValue: String) + } + + /// A `RequiredComponent` was missing during encoding. + case missingRequiredComponent(RequiredComponent) + /// The underlying encoder failed with the associated error. + case encoderFailed(error: Error) + } + + /// The underlying reason the `.responseValidationFailed` error occurred. + public enum ResponseValidationFailureReason { + /// The data file containing the server response did not exist. + case dataFileNil + /// The data file containing the server response at the associated `URL` could not be read. + case dataFileReadFailed(at: URL) + /// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a + /// wildcard type. + case missingContentType(acceptableContentTypes: [String]) + /// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`. + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + /// The response status code was not acceptable. + case unacceptableStatusCode(code: Int) + /// Custom response validation failed due to the associated `Error`. + case customValidationFailed(error: Error) + } + + /// The underlying reason the response serialization error occurred. + public enum ResponseSerializationFailureReason { + /// The server response contained no data or the data was zero length. + case inputDataNilOrZeroLength + /// The file containing the server response did not exist. + case inputFileNil + /// The file containing the server response could not be read from the associated `URL`. + case inputFileReadFailed(at: URL) + /// String serialization failed using the provided `String.Encoding`. + case stringSerializationFailed(encoding: String.Encoding) + /// JSON serialization failed with an underlying system error. + case jsonSerializationFailed(error: Error) + /// A `DataDecoder` failed to decode the response due to the associated `Error`. + case decodingFailed(error: Error) + /// A custom response serializer failed due to the associated `Error`. + case customSerializationFailed(error: Error) + /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type. + case invalidEmptyResponse(type: String) + } + + /// Underlying reason a server trust evaluation error occurred. + public enum ServerTrustFailureReason { + /// The output of a server trust evaluation. + public struct Output { + /// The host for which the evaluation was performed. + public let host: String + /// The `SecTrust` value which was evaluated. + public let trust: SecTrust + /// The `OSStatus` of evaluation operation. + public let status: OSStatus + /// The result of the evaluation operation. + public let result: SecTrustResultType + + /// Creates an `Output` value from the provided values. + init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) { + self.host = host + self.trust = trust + self.status = status + self.result = result + } + } + + /// No `ServerTrustEvaluator` was found for the associated host. + case noRequiredEvaluator(host: String) + /// No certificates were found with which to perform the trust evaluation. + case noCertificatesFound + /// No public keys were found with which to perform the trust evaluation. + case noPublicKeysFound + /// During evaluation, application of the associated `SecPolicy` failed. + case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus) + /// During evaluation, setting the associated anchor certificates failed. + case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate]) + /// During evaluation, creation of the revocation policy failed. + case revocationPolicyCreationFailed + /// `SecTrust` evaluation failed with the associated `Error`, if one was produced. + case trustEvaluationFailed(error: Error?) + /// Default evaluation failed with the associated `Output`. + case defaultEvaluationFailed(output: Output) + /// Host validation failed with the associated `Output`. + case hostValidationFailed(output: Output) + /// Revocation check failed with the associated `Output` and options. + case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options) + /// Certificate pinning failed. + case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate]) + /// Public key pinning failed. + case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey]) + /// Custom server trust evaluation failed due to the associated `Error`. + case customEvaluationFailed(error: Error) + } + + /// The underlying reason the `.urlRequestValidationFailed` + public enum URLRequestValidationFailureReason { + /// URLRequest with GET method had body data. + case bodyDataInGETRequest(Data) + } + + /// `UploadableConvertible` threw an error in `createUploadable()`. + case createUploadableFailed(error: Error) + /// `URLRequestConvertible` threw an error in `asURLRequest()`. + case createURLRequestFailed(error: Error) + /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL. + case downloadedFileMoveFailed(error: Error, source: URL, destination: URL) + /// `Request` was explicitly cancelled. + case explicitlyCancelled + /// `URLConvertible` type failed to create a valid `URL`. + case invalidURL(url: URLConvertible) + /// Multipart form encoding failed. + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + /// `ParameterEncoding` threw an error during the encoding process. + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + /// `ParameterEncoder` threw an error while running the encoder. + case parameterEncoderFailed(reason: ParameterEncoderFailureReason) + /// `RequestAdapter` threw an error during adaptation. + case requestAdaptationFailed(error: Error) + /// `RequestRetrier` threw an error during the request retry process. + case requestRetryFailed(retryError: Error, originalError: Error) + /// Response validation failed. + case responseValidationFailed(reason: ResponseValidationFailureReason) + /// Response serialization failed. + case responseSerializationFailed(reason: ResponseSerializationFailureReason) + /// `ServerTrustEvaluating` instance threw an error during trust evaluation. + case serverTrustEvaluationFailed(reason: ServerTrustFailureReason) + /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope. + case sessionDeinitialized + /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`. + case sessionInvalidated(error: Error?) + /// `URLSessionTask` completed with error. + case sessionTaskFailed(error: Error) + /// `URLRequest` failed validation. + case urlRequestValidationFailed(reason: URLRequestValidationFailureReason) +} + +extension Error { + /// Returns the instance cast as an `AFError`. + public var asAFError: AFError? { + return self as? AFError + } + + /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown. + public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError { + guard let afError = self as? AFError else { + fatalError(message(), file: file, line: line) + } + return afError + } + + /// Casts the instance as `AFError` or returns `defaultAFError` + func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError { + return self as? AFError ?? defaultAFError() + } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the instance is `.sessionDeinitialized`. + public var isSessionDeinitializedError: Bool { + if case .sessionDeinitialized = self { return true } + return false + } + + /// Returns whether the instance is `.sessionInvalidated`. + public var isSessionInvalidatedError: Bool { + if case .sessionInvalidated = self { return true } + return false + } + + /// Returns whether the instance is `.explicitlyCancelled`. + public var isExplicitlyCancelledError: Bool { + if case .explicitlyCancelled = self { return true } + return false + } + + /// Returns whether the instance is `.invalidURL`. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncoderError: Bool { + if case .parameterEncoderFailed = self { return true } + return false + } + + /// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError` + /// properties will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestAdaptationError: Bool { + if case .requestAdaptationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isServerTrustEvaluationError: Bool { + if case .serverTrustEvaluationFailed = self { return true } + return false + } + + /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestRetryError: Bool { + if case .requestRetryFailed = self { return true } + return false + } + + /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateUploadableError: Bool { + if case .createUploadableFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateURLRequestError: Bool { + if case .createURLRequestFailed = self { return true } + return false + } + + /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will + /// contain the associated values. + public var isDownloadedFileMoveError: Bool { + if case .downloadedFileMoveFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isSessionTaskError: Bool { + if case .sessionTaskFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + guard case let .invalidURL(url) = self else { return nil } + return url + } + + /// The `URL` associated with the error. + public var url: URL? { + guard case let .multipartEncodingFailed(reason) = self else { return nil } + return reason.url + } + + /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`, + /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`, + /// `.responseSerializationFailed`, `.requestRetryFailed` errors. + public var underlyingError: Error? { + switch self { + case let .multipartEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncoderFailed(reason): + return reason.underlyingError + case let .requestAdaptationFailed(error): + return error + case let .requestRetryFailed(retryError, _): + return retryError + case let .responseValidationFailed(reason): + return reason.underlyingError + case let .responseSerializationFailed(reason): + return reason.underlyingError + case let .serverTrustEvaluationFailed(reason): + return reason.underlyingError + case let .sessionInvalidated(error): + return error + case let .createUploadableFailed(error): + return error + case let .createURLRequestFailed(error): + return error + case let .downloadedFileMoveFailed(error, _, _): + return error + case let .sessionTaskFailed(error): + return error + case .explicitlyCancelled, + .invalidURL, + .sessionDeinitialized, + .urlRequestValidationFailed: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.acceptableContentTypes + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseContentType + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseCode + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + guard case let .responseSerializationFailed(reason) = self else { return nil } + return reason.failedStringEncoding + } + + /// The `source` URL of a `.downloadedFileMoveFailed` error. + public var sourceURL: URL? { + guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil } + return source + } + + /// The `destination` URL of a `.downloadedFileMoveFailed` error. + public var destinationURL: URL? { + guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil } + return destination + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case let .jsonEncodingFailed(error), + let .customEncodingFailed(error): + return error + case .missingURL: + return nil + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var underlyingError: Error? { + switch self { + case let .encoderFailed(error): + return error + case .missingRequiredComponent: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case let .bodyPartURLInvalid(url), + let .bodyPartFilenameInvalid(url), + let .bodyPartFileNotReachable(url), + let .bodyPartFileIsDirectory(url), + let .bodyPartFileSizeNotAvailable(url), + let .bodyPartInputStreamCreationFailed(url), + let .outputStreamCreationFailed(url), + let .outputStreamFileAlreadyExists(url), + let .outputStreamURLInvalid(url), + let .bodyPartFileNotReachableWithError(url, _), + let .bodyPartFileSizeQueryFailedWithError(url, _): + return url + case .outputStreamWriteFailed, + .inputStreamReadFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .bodyPartFileNotReachableWithError(_, error), + let .bodyPartFileSizeQueryFailedWithError(_, error), + let .outputStreamWriteFailed(error), + let .inputStreamReadFailed(error): + return error + case .bodyPartURLInvalid, + .bodyPartFilenameInvalid, + .bodyPartFileNotReachable, + .bodyPartFileIsDirectory, + .bodyPartFileSizeNotAvailable, + .bodyPartInputStreamCreationFailed, + .outputStreamCreationFailed, + .outputStreamFileAlreadyExists, + .outputStreamURLInvalid: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case let .missingContentType(types), + let .unacceptableContentType(types, _): + return types + case .dataFileNil, + .dataFileReadFailed, + .unacceptableStatusCode, + .customValidationFailed: + return nil + } + } + + var responseContentType: String? { + switch self { + case let .unacceptableContentType(_, responseType): + return responseType + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableStatusCode, + .customValidationFailed: + return nil + } + } + + var responseCode: Int? { + switch self { + case let .unacceptableStatusCode(code): + return code + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .customValidationFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .customValidationFailed(error): + return error + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .unacceptableStatusCode: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case let .stringSerializationFailed(encoding): + return encoding + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed(_), + .jsonSerializationFailed(_), + .decodingFailed(_), + .customSerializationFailed(_), + .invalidEmptyResponse: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .jsonSerializationFailed(error), + let .decodingFailed(error), + let .customSerializationFailed(error): + return error + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed, + .stringSerializationFailed, + .invalidEmptyResponse: + return nil + } + } +} + +extension AFError.ServerTrustFailureReason { + var output: AFError.ServerTrustFailureReason.Output? { + switch self { + case let .defaultEvaluationFailed(output), + let .hostValidationFailed(output), + let .revocationCheckFailed(output, _): + return output + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .trustEvaluationFailed, + .certificatePinningFailed, + .publicKeyPinningFailed, + .customEvaluationFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .customEvaluationFailed(error): + return error + case let .trustEvaluationFailed(error): + return error + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .defaultEvaluationFailed, + .hostValidationFailed, + .revocationCheckFailed, + .certificatePinningFailed, + .publicKeyPinningFailed: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .explicitlyCancelled: + return "Request explicitly cancelled." + case let .invalidURL(url): + return "URL is not valid: \(url)" + case let .parameterEncodingFailed(reason): + return reason.localizedDescription + case let .parameterEncoderFailed(reason): + return reason.localizedDescription + case let .multipartEncodingFailed(reason): + return reason.localizedDescription + case let .requestAdaptationFailed(error): + return "Request adaption failed with error: \(error.localizedDescription)" + case let .responseValidationFailed(reason): + return reason.localizedDescription + case let .responseSerializationFailed(reason): + return reason.localizedDescription + case let .requestRetryFailed(retryError, originalError): + return """ + Request retry failed with retry error: \(retryError.localizedDescription), \ + original error: \(originalError.localizedDescription) + """ + case .sessionDeinitialized: + return """ + Session was invalidated without error, so it was likely deinitialized unexpectedly. \ + Be sure to retain a reference to your Session for the duration of your requests. + """ + case let .sessionInvalidated(error): + return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")" + case let .serverTrustEvaluationFailed(reason): + return "Server trust evaluation failed due to reason: \(reason.localizedDescription)" + case let .urlRequestValidationFailed(reason): + return "URLRequest validation failed due to reason: \(reason.localizedDescription)" + case let .createUploadableFailed(error): + return "Uploadable creation failed with error: \(error.localizedDescription)" + case let .createURLRequestFailed(error): + return "URLRequest creation failed with error: \(error.localizedDescription)" + case let .downloadedFileMoveFailed(error, source, destination): + return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)" + case let .sessionTaskFailed(error): + return "URLSessionTask failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case let .jsonEncodingFailed(error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case let .customEncodingFailed(error): + return "Custom parameter encoder failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var localizedDescription: String { + switch self { + case let .missingRequiredComponent(component): + return "Encoding failed due to a missing request component: \(component)" + case let .encoderFailed(error): + return "The underlying encoder failed with the error: \(error)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case let .bodyPartURLInvalid(url): + return "The URL provided is not a file URL: \(url)" + case let .bodyPartFilenameInvalid(url): + return "The URL provided does not have a valid filename: \(url)" + case let .bodyPartFileNotReachable(url): + return "The URL provided is not reachable: \(url)" + case let .bodyPartFileNotReachableWithError(url, error): + return """ + The system returned an error while checking the provided URL for reachability. + URL: \(url) + Error: \(error) + """ + case let .bodyPartFileIsDirectory(url): + return "The URL provided is a directory: \(url)" + case let .bodyPartFileSizeNotAvailable(url): + return "Could not fetch the file size from the provided URL: \(url)" + case let .bodyPartFileSizeQueryFailedWithError(url, error): + return """ + The system returned an error while attempting to fetch the file size from the provided URL. + URL: \(url) + Error: \(error) + """ + case let .bodyPartInputStreamCreationFailed(url): + return "Failed to create an InputStream for the provided URL: \(url)" + case let .outputStreamCreationFailed(url): + return "Failed to create an OutputStream for URL: \(url)" + case let .outputStreamFileAlreadyExists(url): + return "A file already exists at the provided URL: \(url)" + case let .outputStreamURLInvalid(url): + return "The provided OutputStream URL is invalid: \(url)" + case let .outputStreamWriteFailed(error): + return "OutputStream write failed with error: \(error)" + case let .inputStreamReadFailed(error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case let .inputFileReadFailed(url): + return "Response could not be serialized, input file could not be read: \(url)." + case let .stringSerializationFailed(encoding): + return "String could not be serialized with encoding: \(encoding)." + case let .jsonSerializationFailed(error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case let .invalidEmptyResponse(type): + return """ + Empty response could not be serialized to type: \(type). \ + Use Empty as the expected type for such responses. + """ + case let .decodingFailed(error): + return "Response could not be decoded because of error:\n\(error.localizedDescription)" + case let .customSerializationFailed(error): + return "Custom response serializer failed with error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case let .dataFileReadFailed(url): + return "Response could not be validated, data file could not be read: \(url)." + case let .missingContentType(types): + return """ + Response Content-Type was missing and acceptable content types \ + (\(types.joined(separator: ","))) do not match "*/*". + """ + case let .unacceptableContentType(acceptableTypes, responseType): + return """ + Response Content-Type "\(responseType)" does not match any acceptable types: \ + \(acceptableTypes.joined(separator: ",")). + """ + case let .unacceptableStatusCode(code): + return "Response status code was unacceptable: \(code)." + case let .customValidationFailed(error): + return "Custom response validation failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ServerTrustFailureReason { + var localizedDescription: String { + switch self { + case let .noRequiredEvaluator(host): + return "A ServerTrustEvaluating value is required for host \(host) but none was found." + case .noCertificatesFound: + return "No certificates were found or provided for evaluation." + case .noPublicKeysFound: + return "No public keys were found or provided for evaluation." + case .policyApplicationFailed: + return "Attempting to set a SecPolicy failed." + case .settingAnchorCertificatesFailed: + return "Attempting to set the provided certificates as anchor certificates failed." + case .revocationPolicyCreationFailed: + return "Attempting to create a revocation policy failed." + case let .trustEvaluationFailed(error): + return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")" + case let .defaultEvaluationFailed(output): + return "Default evaluation failed for host \(output.host)." + case let .hostValidationFailed(output): + return "Host validation failed for host \(output.host)." + case let .revocationCheckFailed(output, _): + return "Revocation check failed for host \(output.host)." + case let .certificatePinningFailed(host, _, _, _): + return "Certificate pinning failed for host \(host)." + case let .publicKeyPinningFailed(host, _, _, _): + return "Public key pinning failed for host \(host)." + case let .customEvaluationFailed(error): + return "Custom trust evaluation failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.URLRequestValidationFailureReason { + var localizedDescription: String { + switch self { + case let .bodyDataInGETRequest(data): + return """ + Invalid URLRequest: Requests with GET method cannot have body data: + \(String(decoding: data, as: UTF8.self)) + """ + } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/Alamofire.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..9bbc2a1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,29 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +/// Reference to `Session.default` for quick bootstrapping and examples. +public let AF = Session.default + +/// Current Alamofire version. Necessary since SPM doesn't use dynamic libraries. Plus this will be more accurate. +let version = "5.0.0" diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/AlamofireExtended.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/AlamofireExtended.swift new file mode 100644 index 0000000..3009e8b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/AlamofireExtended.swift @@ -0,0 +1,58 @@ +// +// AlamofireExtended.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +/// Type that acts as a generic extension point for all `AlamofireExtended` types. +public struct AlamofireExtension { + /// Stores the type or metatype of any extended type. + let type: ExtendedType + + init(_ type: ExtendedType) { + self.type = type + } +} + +/// Protocol describing the `af` extension points for Alamofire extended types. +public protocol AlamofireExtended { + /// Type being extended. + associatedtype ExtendedType + + /// Static Alamofire extension point. + static var af: AlamofireExtension.Type { get set } + /// Instance Alamofire extension point. + var af: AlamofireExtension { get set } +} + +public extension AlamofireExtended { + /// Static Alamofire extension point. + static var af: AlamofireExtension.Type { + get { return AlamofireExtension.self } + set {} + } + + /// Instance Alamofire extension point. + var af: AlamofireExtension { + get { return AlamofireExtension(self) } + set {} + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/CachedResponseHandler.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/CachedResponseHandler.swift new file mode 100644 index 0000000..b6e0d4b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/CachedResponseHandler.swift @@ -0,0 +1,91 @@ +// +// CachedResponseHandler.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that handles whether the data task should store the HTTP response in the cache. +public protocol CachedResponseHandler { + /// Determines whether the HTTP response should be stored in the cache. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The cached response provided by the server (this is the most common use case). + /// 2. A modified version of the cached response (you may want to modify it in some way before caching). + /// 3. A `nil` value to prevent the cached response from being stored in the cache. + /// + /// - Parameters: + /// - task: The data task whose request resulted in the cached response. + /// - response: The cached response to potentially store in the cache. + /// - completion: The closure to execute containing cached response, a modified response, or `nil`. + func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) +} + +// MARK: - + +/// `ResponseCacher` is a convenience `CachedResponseHandler` making it easy to cache, not cache, or modify a cached +/// response. +public struct ResponseCacher { + /// Defines the behavior of the `ResponseCacher` type. + public enum Behavior { + /// Stores the cached response in the cache. + case cache + /// Prevents the cached response from being stored in the cache. + case doNotCache + /// Modifies the cached response before storing it in the cache. + case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?) + } + + /// Returns a `ResponseCacher` with a follow `Behavior`. + public static let cache = ResponseCacher(behavior: .cache) + /// Returns a `ResponseCacher` with a do not follow `Behavior`. + public static let doNotCache = ResponseCacher(behavior: .doNotCache) + + /// The `Behavior` of the `ResponseCacher`. + public let behavior: Behavior + + /// Creates a `ResponseCacher` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +extension ResponseCacher: CachedResponseHandler { + public func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) { + switch behavior { + case .cache: + completion(response) + case .doNotCache: + completion(nil) + case let .modify(closure): + let response = closure(task, response) + completion(response) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..10cd273 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation + +extension DispatchQueue { + /// Execute the provided closure after a `TimeInterval`. + /// + /// - Parameters: + /// - delay: `TimeInterval` to delay execution. + /// - closure: Closure to execute. + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/EventMonitor.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/EventMonitor.swift new file mode 100644 index 0000000..4363828 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/EventMonitor.swift @@ -0,0 +1,844 @@ +// +// EventMonitor.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various +/// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses. +public protocol EventMonitor { + /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default. + var queue: DispatchQueue { get } + + // MARK: - URLSession Events + + // MARK: URLSessionDelegate Events + + /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method. + func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) + + // MARK: URLSessionTaskDelegate Events + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method. + func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method. + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) + + // MARK: URLSessionDataDelegate Events + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) + + // MARK: URLSessionDownloadDelegate Events + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method. + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) + + // MARK: - Request Events + + /// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the + /// `URLRequest` will be adapted before being issued. + func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) + + /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails. + func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) + + /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`. + func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) + + /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`. + func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) + + /// Event called when a final `URLRequest` is created for a `Request`. + func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) + + /// Event called when a `URLSessionTask` subclass instance is created for a `Request`. + func request(_ request: Request, didCreateTask task: URLSessionTask) + + /// Event called when a `Request` receives a `URLSessionTaskMetrics` value. + func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) + + /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails. + func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) + + /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event + /// multiple times if it is retried. + func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) + + /// Event called when a `Request` is about to be retried. + func requestIsRetrying(_ request: Request) + + /// Event called when a `Request` finishes and response serializers are being called. + func requestDidFinish(_ request: Request) + + /// Event called when a `Request` receives a `resume` call. + func requestDidResume(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is resumed. + func request(_ request: Request, didResumeTask task: URLSessionTask) + + /// Event called when a `Request` receives a `suspend` call. + func requestDidSuspend(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is suspended. + func request(_ request: Request, didSuspendTask task: URLSessionTask) + + /// Event called when a `Request` receives a `cancel` call. + func requestDidCancel(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is cancelled. + func request(_ request: Request, didCancelTask task: URLSessionTask) + + // MARK: DataRequest Events + + /// Event called when a `DataRequest` calls a `Validation`. + func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) + + /// Event called when a `DataRequest` creates a `DataResponse` value without calling a `ResponseSerializer`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + // MARK: UploadRequest Events + + /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents. + func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) + + /// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error. + func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) + + /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if + /// the `InputStream` does not wrap a `Data` value or file `URL`. + func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) + + // MARK: DownloadRequest Events + + /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved. + func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) + + /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the + /// downloaded file will be moved to. + func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) + + /// Event called when a `DownloadRequest` calls a `Validation`. + func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) + + /// Event called when a `DownloadRequest` creates a `DownloadResponse` without calling a `ResponseSerializer`. + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) + + /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse` + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) +} + +extension EventMonitor { + /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default. + public var queue: DispatchQueue { return .main } + + // MARK: Default Implementations + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) {} + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didFinishCollecting metrics: URLSessionTaskMetrics) {} + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {} + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {} + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {} + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) {} + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {} + public func request(_ request: Request, + didAdaptInitialRequest initialRequest: URLRequest, + to adaptedRequest: URLRequest) {} + public func request(_ request: Request, + didFailToAdaptURLRequest initialRequest: URLRequest, + withError error: AFError) {} + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didCreateTask task: URLSessionTask) {} + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {} + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {} + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {} + public func requestIsRetrying(_ request: Request) {} + public func requestDidFinish(_ request: Request) {} + public func requestDidResume(_ request: Request) {} + public func request(_ request: Request, didResumeTask task: URLSessionTask) {} + public func requestDidSuspend(_ request: Request) {} + public func request(_ request: Request, didSuspendTask task: URLSessionTask) {} + public func requestDidCancel(_ request: Request) {} + public func request(_ request: Request, didCancelTask task: URLSessionTask) {} + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {} + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {} + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {} + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {} + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {} + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} +} + +/// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues. +public final class CompositeEventMonitor: EventMonitor { + public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor", qos: .background) + + let monitors: [EventMonitor] + + init(monitors: [EventMonitor]) { + self.monitors = monitors + } + + func performEvent(_ event: @escaping (EventMonitor) -> Void) { + queue.async { + for monitor in self.monitors { + monitor.queue.async { event(monitor) } + } + } + } + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) { + performEvent { $0.urlSession(session, task: task, didReceive: challenge) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + performEvent { + $0.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + } + + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + performEvent { + $0.urlSession(session, taskNeedsNewBodyStream: task) + } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + performEvent { + $0.urlSession(session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request) + } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) } + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) } + } + + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) } + } + + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) { + performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) { + performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } + } + + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) } + } + + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) } + } + + public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) } + } + + public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) } + } + + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateURLRequest: urlRequest) } + } + + public func request(_ request: Request, didCreateTask task: URLSessionTask) { + performEvent { $0.request(request, didCreateTask: task) } + } + + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + performEvent { $0.request(request, didGatherMetrics: metrics) } + } + + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + performEvent { $0.request(request, didFailTask: task, earlyWithError: error) } + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + performEvent { $0.request(request, didCompleteTask: task, with: error) } + } + + public func requestIsRetrying(_ request: Request) { + performEvent { $0.requestIsRetrying(request) } + } + + public func requestDidFinish(_ request: Request) { + performEvent { $0.requestDidFinish(request) } + } + + public func requestDidResume(_ request: Request) { + performEvent { $0.requestDidResume(request) } + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + performEvent { $0.request(request, didResumeTask: task) } + } + + public func requestDidSuspend(_ request: Request) { + performEvent { $0.requestDidSuspend(request) } + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + performEvent { $0.request(request, didSuspendTask: task) } + } + + public func requestDidCancel(_ request: Request) { + performEvent { $0.requestDidCancel(request) } + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + performEvent { $0.request(request, didCancelTask: task) } + } + + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + data: data, + withResult: result) + } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + performEvent { $0.request(request, didCreateUploadable: uploadable) } + } + + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateUploadableWithError: error) } + } + + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + performEvent { $0.request(request, didProvideInputStream: stream) } + } + + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) } + } + + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + performEvent { $0.request(request, didCreateDestinationURL: url) } + } + + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + fileURL: fileURL, + withResult: result) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } +} + +/// `EventMonitor` that allows optional closures to be set to receive events. +open class ClosureEventMonitor: EventMonitor { + /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)? + + /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)? + + /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)? + + /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event. + open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event. + open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)? + + /// Closure that receives the `urlSession(_:dataTask:didReceive:)` event. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` + /// event. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: - Request Events + + /// Closure called on the `request(_:didCreateInitialURLRequest:)` event. + open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event. + open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)? + + /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event. + open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event. + open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didCreateURLRequest:)` event. + open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didCreateTask:)` event. + open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didGatherMetrics:)` event. + open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `request(_:didFailTask:earlyWithError:)` event. + open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)? + + /// Closure called on the `request(_:didCompleteTask:with:)` event. + open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)? + + /// Closure called on the `requestIsRetrying(_:)` event. + open var requestIsRetrying: ((Request) -> Void)? + + /// Closure called on the `requestDidFinish(_:)` event. + open var requestDidFinish: ((Request) -> Void)? + + /// Closure called on the `requestDidResume(_:)` event. + open var requestDidResume: ((Request) -> Void)? + + /// Closure called on the `request(_:didResumeTask:)` event. + open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidSuspend(_:)` event. + open var requestDidSuspend: ((Request) -> Void)? + + /// Closure called on the `request(_:didSuspendTask:)` event. + open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidCancel(_:)` event. + open var requestDidCancel: ((Request) -> Void)? + + /// Closure called on the `request(_:didCancelTask:)` event. + open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event. + open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseResponse: ((DataRequest, DataResponse) -> Void)? + + /// Closure called on the `request(_:didCreateUploadable:)` event. + open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)? + + /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event. + open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didProvideInputStream:)` event. + open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)? + + /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event. + open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result) -> Void)? + + /// Closure called on the `request(_:didCreateDestinationURL:)` event. + open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event. + open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse) -> Void)? + + public let queue: DispatchQueue + + /// Creates an instance using the provided queue. + /// + /// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default. + public init(queue: DispatchQueue = .main) { + self.queue = queue + } + + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) { + taskDidReceiveChallenge?(session, task, challenge) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + taskNeedNewBodyStream?(session, task) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + taskWillPerformHTTPRedirection?(session, task, response, request) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + taskDidFinishCollectingMetrics?(session, task, metrics) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + taskDidComplete?(session, task, error) + } + + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + taskIsWaitingForConnectivity?(session, task) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + dataTaskDidReceiveData?(session, dataTask, data) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) { + dataTaskWillCacheResponse?(session, dataTask, proposedResponse) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location) + } + + // MARK: Request Events + + open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + requestDidCreateInitialURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + requestDidFailToCreateURLRequestWithError?(request, error) + } + + open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest) + } + + open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error) + } + + open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + requestDidCreateURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didCreateTask task: URLSessionTask) { + requestDidCreateTask?(request, task) + } + + open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + requestDidGatherMetrics?(request, metrics) + } + + open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + requestDidFailTaskEarlyWithError?(request, task, error) + } + + open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + requestDidCompleteTaskWithError?(request, task, error) + } + + open func requestIsRetrying(_ request: Request) { + requestIsRetrying?(request) + } + + open func requestDidFinish(_ request: Request) { + requestDidFinish?(request) + } + + open func requestDidResume(_ request: Request) { + requestDidResume?(request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + requestDidResumeTask?(request, task) + } + + open func requestDidSuspend(_ request: Request) { + requestDidSuspend?(request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + requestDidSuspendTask?(request, task) + } + + open func requestDidCancel(_ request: Request) { + requestDidCancel?(request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + requestDidCancelTask?(request, task) + } + + open func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result) + } + + open func request(_ request: DataRequest, didParseResponse response: DataResponse) { + requestDidParseResponse?(request, response) + } + + open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + requestDidCreateUploadable?(request, uploadable) + } + + open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + requestDidFailToCreateUploadableWithError?(request, error) + } + + open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + requestDidProvideInputStream?(request, stream) + } + + open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + requestDidFinishDownloadingUsingTaskWithResult?(request, task, result) + } + + open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + requestDidCreateDestinationURL?(request, url) + } + + open func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseFileURLWithResult?(request, + urlRequest, + response, + fileURL, + result) + } + + open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + requestDidParseDownloadResponse?(request, response) + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/HTTPHeaders.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/HTTPHeaders.swift new file mode 100644 index 0000000..641087c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/HTTPHeaders.swift @@ -0,0 +1,445 @@ +// +// HTTPHeaders.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// An order-preserving and case-insensitive representation of HTTP headers. +public struct HTTPHeaders { + private var headers: [HTTPHeader] = [] + + /// Creates an empty instance. + public init() {} + + /// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last + /// name and value encountered. + public init(_ headers: [HTTPHeader]) { + self.init() + + headers.forEach { update($0) } + } + + /// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name + /// and value encountered. + public init(_ dictionary: [String: String]) { + self.init() + + dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) } + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader value. + public mutating func add(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func add(_ header: HTTPHeader) { + update(header) + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader value. + public mutating func update(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func update(_ header: HTTPHeader) { + guard let index = headers.index(of: header.name) else { + headers.append(header) + return + } + + headers.replaceSubrange(index...index, with: [header]) + } + + /// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance. + /// + /// - Parameter name: The name of the `HTTPHeader` to remove. + public mutating func remove(name: String) { + guard let index = headers.index(of: name) else { return } + + headers.remove(at: index) + } + + /// Sort the current instance by header name. + public mutating func sort() { + headers.sort { $0.name < $1.name } + } + + /// Returns an instance sorted by header name. + /// + /// - Returns: A copy of the current instance sorted by name. + public func sorted() -> HTTPHeaders { + return HTTPHeaders(headers.sorted { $0.name < $1.name }) + } + + /// Case-insensitively find a header's value by name. + /// + /// - Parameter name: The name of the header to search for, case-insensitively. + /// + /// - Returns: The value of header, if it exists. + public func value(for name: String) -> String? { + guard let index = headers.index(of: name) else { return nil } + + return headers[index].value + } + + /// Case-insensitively access the header with the given name. + /// + /// - Parameter name: The name of the header. + public subscript(_ name: String) -> String? { + get { return value(for: name) } + set { + if let value = newValue { + update(name: name, value: value) + } else { + remove(name: name) + } + } + } + + /// The dictionary representation of all headers. + /// + /// This representation does not preserve the current order of the instance. + public var dictionary: [String: String] { + let namesAndValues = headers.map { ($0.name, $0.value) } + + return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last }) + } +} + +extension HTTPHeaders: ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, String)...) { + self.init() + + elements.forEach { update(name: $0.0, value: $0.1) } + } +} + +extension HTTPHeaders: ExpressibleByArrayLiteral { + public init(arrayLiteral elements: HTTPHeader...) { + self.init(elements) + } +} + +extension HTTPHeaders: Sequence { + public func makeIterator() -> IndexingIterator<[HTTPHeader]> { + return headers.makeIterator() + } +} + +extension HTTPHeaders: Collection { + public var startIndex: Int { + return headers.startIndex + } + + public var endIndex: Int { + return headers.endIndex + } + + public subscript(position: Int) -> HTTPHeader { + return headers[position] + } + + public func index(after i: Int) -> Int { + return headers.index(after: i) + } +} + +extension HTTPHeaders: CustomStringConvertible { + public var description: String { + return headers.map { $0.description } + .joined(separator: "\n") + } +} + +// MARK: - HTTPHeader + +/// A representation of a single HTTP header's name / value pair. +public struct HTTPHeader: Hashable { + /// Name of the header. + public let name: String + + /// Value of the header. + public let value: String + + /// Creates an instance from the given `name` and `value`. + /// + /// - Parameters: + /// - name: The name of the header. + /// - value: The value of the header. + public init(name: String, value: String) { + self.name = name + self.value = value + } +} + +extension HTTPHeader: CustomStringConvertible { + public var description: String { + return "\(name): \(value)" + } +} + +extension HTTPHeader { + /// Returns an `Accept` header. + /// + /// - Parameter value: The `Accept` value. + /// - Returns: The header. + public static func accept(_ value: String) -> HTTPHeader { + return HTTPHeader(name: "Accept", value: value) + } + + /// Returns an `Accept-Charset` header. + /// + /// - Parameter value: The `Accept-Charset` value. + /// - Returns: The header. + public static func acceptCharset(_ value: String) -> HTTPHeader { + return HTTPHeader(name: "Accept-Charset", value: value) + } + + /// Returns an `Accept-Language` header. + /// + /// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages. + /// Use `HTTPHeader.defaultAcceptLanguage`. + /// + /// - Parameter value: The `Accept-Language` value. + /// + /// - Returns: The header. + public static func acceptLanguage(_ value: String) -> HTTPHeader { + return HTTPHeader(name: "Accept-Language", value: value) + } + + /// Returns an `Accept-Encoding` header. + /// + /// Alamofire offers a default accept encoding value that provides the most common values. Use + /// `HTTPHeader.defaultAcceptEncoding`. + /// + /// - Parameter value: The `Accept-Encoding` value. + /// + /// - Returns: The header + public static func acceptEncoding(_ value: String) -> HTTPHeader { + return HTTPHeader(name: "Accept-Encoding", value: value) + } + + /// Returns a `Basic` `Authorization` header using the `username` and `password` provided. + /// + /// - Parameters: + /// - username: The username of the header. + /// - password: The password of the header. + /// + /// - Returns: The header. + public static func authorization(username: String, password: String) -> HTTPHeader { + let credential = Data("\(username):\(password)".utf8).base64EncodedString() + + return authorization("Basic \(credential)") + } + + /// Returns a `Bearer` `Authorization` header using the `bearerToken` provided + /// + /// - Parameter bearerToken: The bearer token. + /// + /// - Returns: The header. + public static func authorization(bearerToken: String) -> HTTPHeader { + return authorization("Bearer \(bearerToken)") + } + + /// Returns an `Authorization` header. + /// + /// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use + /// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use + /// `HTTPHeader.authorization(bearerToken:)`. + /// + /// - Parameter value: The `Authorization` value. + /// + /// - Returns: The header. + public static func authorization(_ value: String) -> HTTPHeader { + return HTTPHeader(name: "Authorization", value: value) + } + + /// Returns a `Content-Disposition` header. + /// + /// - Parameter value: The `Content-Disposition` value. + /// + /// - Returns: The header. + public static func contentDisposition(_ value: String) -> HTTPHeader { + return HTTPHeader(name: "Content-Disposition", value: value) + } + + /// Returns a `Content-Type` header. + /// + /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not be necessary to manually + /// set this value. + /// + /// - Parameter value: The `Content-Type` value. + /// + /// - Returns: The header. + public static func contentType(_ value: String) -> HTTPHeader { + return HTTPHeader(name: "Content-Type", value: value) + } + + /// Returns a `User-Agent` header. + /// + /// - Parameter value: The `User-Agent` value. + /// + /// - Returns: The header. + public static func userAgent(_ value: String) -> HTTPHeader { + return HTTPHeader(name: "User-Agent", value: value) + } +} + +extension Array where Element == HTTPHeader { + /// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists. + func index(of name: String) -> Int? { + let lowercasedName = name.lowercased() + return firstIndex { $0.name.lowercased() == lowercasedName } + } +} + +// MARK: - Defaults + +public extension HTTPHeaders { + /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and + /// `User-Agent`. + static let `default`: HTTPHeaders = [.defaultAcceptEncoding, + .defaultAcceptLanguage, + .defaultUserAgent] +} + +extension HTTPHeader { + /// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS + /// versions. + /// + /// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) . + public static let defaultAcceptEncoding: HTTPHeader = { + let encodings: [String] + if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) { + encodings = ["br", "gzip", "deflate"] + } else { + encodings = ["gzip", "deflate"] + } + + return .acceptEncoding(encodings.qualityEncoded()) + }() + + /// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's + /// `preferredLanguages`. + /// + /// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5). + public static let defaultAcceptLanguage: HTTPHeader = { + .acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded()) + }() + + /// Returns Alamofire's default `User-Agent` header. + /// + /// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3). + /// + /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0` + public static let defaultUserAgent: HTTPHeader = { + let 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)" + // swiftformat:disable indent + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "macOS" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + // swiftformat:enable indent + + return "\(osName) \(versionString)" + }() + + let alamofireVersion = "Alamofire/\(version)" + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return .userAgent(userAgent) + }() +} + +extension Collection where Element == String { + func qualityEncoded() -> String { + return enumerated().map { index, encoding in + let quality = 1.0 - (Double(index) * 0.1) + return "\(encoding);q=\(quality)" + }.joined(separator: ", ") + } +} + +// MARK: - System Type Extensions + +extension URLRequest { + /// Returns `allHTTPHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + get { return allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() } + set { allHTTPHeaderFields = newValue.dictionary } + } +} + +extension HTTPURLResponse { + /// Returns `allHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + return (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() + } +} + +public extension URLSessionConfiguration { + /// Returns `httpAdditionalHeaders` as `HTTPHeaders`. + var headers: HTTPHeaders { + get { return (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() } + set { httpAdditionalHeaders = newValue.dictionary } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/HTTPMethod.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/HTTPMethod.swift new file mode 100644 index 0000000..4867c1e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/HTTPMethod.swift @@ -0,0 +1,54 @@ +// +// HTTPMethod.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +/// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so +/// `HTTPMethod.get != HTTPMethod(rawValue: "get")`. +/// +/// See https://tools.ietf.org/html/rfc7231#section-4.3 +public struct HTTPMethod: RawRepresentable, Equatable, Hashable { + /// `CONNECT` method. + public static let connect = HTTPMethod(rawValue: "CONNECT") + /// `DELETE` method. + public static let delete = HTTPMethod(rawValue: "DELETE") + /// `GET` method. + public static let get = HTTPMethod(rawValue: "GET") + /// `HEAD` method. + public static let head = HTTPMethod(rawValue: "HEAD") + /// `OPTIONS` method. + public static let options = HTTPMethod(rawValue: "OPTIONS") + /// `PATCH` method. + public static let patch = HTTPMethod(rawValue: "PATCH") + /// `POST` method. + public static let post = HTTPMethod(rawValue: "POST") + /// `PUT` method. + public static let put = HTTPMethod(rawValue: "PUT") + /// `TRACE` method. + public static let trace = HTTPMethod(rawValue: "TRACE") + + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/MultipartFormData.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..4ef54aa --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,544 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if 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 Data(boundaryText.utf8) + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// Default memory threshold used when encoding `MultipartFormData`, in bytes. + public static let encodingMemoryThreshold: UInt64 = 10_000_000 + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + let fileManager: FileManager + + private var bodyParts: [BodyPart] + private var bodyPartError: AFError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /// Creates an instance. + /// + /// - Parameters: + /// - fileManager: `FileManager` to use for file operations, if needed. + /// - boundary: Boundary `String` used to separate body parts. + public init(fileManager: FileManager = .default, boundary: String? = nil) { + self.fileManager = fileManager + self.boundary = boundary ?? BoundaryGenerator.randomBoundary() + bodyParts = [] + + // + // The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + // information, please refer to the following article: + // - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + // + streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /// Creates a body part from the data and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - Parameters: + /// - data: `Data` to encoding into the instance. + /// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the file and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + /// system associated MIME type. + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. + public func append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// Creates a body part from the file and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + /// - Content-Type: #{mimeType} (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header. + public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + 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.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, headers: headers) + } + + /// Creates a body part from the stream and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header. + public func append(_ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part with the stream, length, and headers and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - headers: `HTTPHeaders` for the body part. + public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all appended body parts into a single `Data` value. + /// + /// - Note: This method will load all the appended body parts into memory all at the same time. This method should + /// only be used when the encoded data will have a small memory footprint. For large data cases, please use + /// the `writeEncodedData(to:))` method. + /// + /// - Returns: The encoded `Data`, if encoding is successful. + /// - Throws: An `AFError` if encoding encounters an error. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(encodedData) + } + + return encoded + } + + /// Writes all appended body parts to the given file `URL`. + /// + /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, + /// this approach is very memory efficient and should be used for large body part data. + /// + /// - Parameter fileURL: File `URL` to which to write the form data. + /// - Throws: An `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if fileManager.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" } + .joined() + + EncodingCharacters.crlf + + return Data(headerText.utf8) + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + 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.. 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.. 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) -> HTTPHeaders { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers: HTTPHeaders = [.contentDisposition(disposition)] + if let mimeType = mimeType { headers.add(.contentType(mimeType)) } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + 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) + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/MultipartUpload.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/MultipartUpload.swift new file mode 100644 index 0000000..4772c30 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/MultipartUpload.swift @@ -0,0 +1,87 @@ +// +// MultipartUpload.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Internal type which encapsulates a `MultipartFormData` upload. +final class MultipartUpload { + lazy var result = Result { try build() } + + let isInBackgroundSession: Bool + let multipartFormData: MultipartFormData + let encodingMemoryThreshold: UInt64 + let request: URLRequestConvertible + let fileManager: FileManager + + init(isInBackgroundSession: Bool, + encodingMemoryThreshold: UInt64, + request: URLRequestConvertible, + multipartFormData: MultipartFormData) { + self.isInBackgroundSession = isInBackgroundSession + self.encodingMemoryThreshold = encodingMemoryThreshold + self.request = request + fileManager = multipartFormData.fileManager + self.multipartFormData = multipartFormData + } + + func build() throws -> (request: URLRequest, uploadable: UploadRequest.Uploadable) { + var urlRequest = try request.asURLRequest() + urlRequest.setValue(multipartFormData.contentType, forHTTPHeaderField: "Content-Type") + + let uploadable: UploadRequest.Uploadable + if multipartFormData.contentLength < encodingMemoryThreshold && !isInBackgroundSession { + let data = try multipartFormData.encode() + + uploadable = .data(data) + } else { + let tempDirectoryURL = fileManager.temporaryDirectory + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + + do { + try multipartFormData.writeEncodedData(to: fileURL) + } catch { + // Cleanup after attempted write if it fails. + try? fileManager.removeItem(at: fileURL) + } + + uploadable = .file(fileURL, shouldRemove: true) + } + + return (request: urlRequest, uploadable: uploadable) + } +} + +extension MultipartUpload: UploadConvertible { + func asURLRequest() throws -> URLRequest { + return try result.get().request + } + + func createUploadable() throws -> UploadRequest.Uploadable { + return try result.get().uploadable + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..d2c4338 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,266 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !(os(watchOS) || os(Linux)) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +open class NetworkReachabilityManager { + /// Defines the various states of network reachability. + public enum NetworkReachabilityStatus { + /// It is unknown whether the network is reachable. + case unknown + /// The network is not reachable. + case notReachable + /// The network is reachable on the associated `ConnectionType`. + case reachable(ConnectionType) + + init(_ flags: SCNetworkReachabilityFlags) { + guard flags.isActuallyReachable else { self = .notReachable; return } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + if flags.isCellular { networkStatus = .reachable(.cellular) } + + self = networkStatus + } + + /// Defines the various connection types detected by reachability flags. + public enum ConnectionType { + /// The connection type is either over Ethernet or WiFi. + case ethernetOrWiFi + /// The connection type is a cellular connection. + case cellular + } + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`. + public static let `default` = NetworkReachabilityManager() + + // MARK: - Properties + + /// Whether the network is currently reachable. + open var isReachable: Bool { return isReachableOnCellular || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the cellular interface. + /// + /// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended. + /// Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued. + /// + open var isReachableOnCellular: Bool { return status == .reachable(.cellular) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + open var isReachableOnEthernetOrWiFi: Bool { return status == .reachable(.ethernetOrWiFi) } + + /// `DispatchQueue` on which reachability will update. + public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue") + + /// Flags of the current reachability type, if any. + open var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + return (SCNetworkReachabilityGetFlags(reachability, &flags)) ? flags : nil + } + + /// The current network reachability status. + open var status: NetworkReachabilityStatus { + return flags.map(NetworkReachabilityStatus.init) ?? .unknown + } + + /// Mutable state storage. + struct MutableState { + /// A closure executed when the network reachability status changes. + var listener: Listener? + /// `DispatchQueue` on which listeners will be called. + var listenerQueue: DispatchQueue? + /// Previously calculated status. + var previousStatus: NetworkReachabilityStatus? + } + + /// `SCNetworkReachability` instance providing notifications. + private let reachability: SCNetworkReachability + + /// Protected storage for mutable state. + private let mutableState = Protector(MutableState()) + + // MARK: - Initialization + + /// Creates an instance with the specified host. + /// + /// - Note: The `host` value must *not* contain a scheme, just the hostname. + /// + /// - Parameters: + /// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`). + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + + self.init(reachability: reachability) + } + + /// Creates an instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + public convenience init?() { + var zero = sockaddr() + zero.sa_len = UInt8(MemoryLayout.size) + zero.sa_family = sa_family_t(AF_INET) + + guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - Note: Stops and removes any existing listener. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default. + /// - listener: `Listener` closure called when reachability changes. + /// + /// - Returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + open func startListening(onQueue queue: DispatchQueue = .main, + onUpdatePerforming listener: @escaping Listener) -> Bool { + stopListening() + + mutableState.write { state in + state.listenerQueue = queue + state.listener = listener + } + + var context = SCNetworkReachabilityContext(version: 0, + info: Unmanaged.passRetained(self).toOpaque(), + retain: nil, + release: nil, + copyDescription: nil) + let callback: SCNetworkReachabilityCallBack = { _, flags, info in + guard let info = info else { return } + + let instance = Unmanaged.fromOpaque(info).takeUnretainedValue() + instance.notifyListener(flags) + } + + let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue) + let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context) + + // Manually call listener to give initial state, since the framework may not. + if let currentFlags = flags { + reachabilityQueue.async { + self.notifyListener(currentFlags) + } + } + + return callbackAdded && queueAdded + } + + /// Stops listening for changes in network reachability status. + open func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + mutableState.write { state in + state.listener = nil + state.listenerQueue = nil + state.previousStatus = nil + } + } + + // MARK: - Internal - Listener Notification + + /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed. + /// + /// - Note: Should only be called from the `reachabilityQueue`. + /// + /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status. + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + let newStatus = NetworkReachabilityStatus(flags) + + mutableState.write { state in + guard state.previousStatus != newStatus else { return } + + state.previousStatus = newStatus + + let listener = state.listener + state.listenerQueue?.async { listener?(newStatus) } + } + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +extension SCNetworkReachabilityFlags { + var isReachable: Bool { return contains(.reachable) } + var isConnectionRequired: Bool { return contains(.connectionRequired) } + var canConnectAutomatically: Bool { return contains(.connectionOnDemand) || contains(.connectionOnTraffic) } + var canConnectWithoutUserInteraction: Bool { return canConnectAutomatically && !contains(.interventionRequired) } + var isActuallyReachable: Bool { return isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) } + var isCellular: Bool { +#if os(iOS) || os(tvOS) + return contains(.isWWAN) +#else + return false +#endif + } + + /// Human readable `String` for all states, to help with debugging. + var readableDescription: String { + let W = isCellular ? "W" : "-" + let R = isReachable ? "R" : "-" + let c = isConnectionRequired ? "c" : "-" + let t = contains(.transientConnection) ? "t" : "-" + let i = contains(.interventionRequired) ? "i" : "-" + let C = contains(.connectionOnTraffic) ? "C" : "-" + let D = contains(.connectionOnDemand) ? "D" : "-" + let l = contains(.isLocalAddress) ? "l" : "-" + let d = contains(.isDirect) ? "d" : "-" + let a = contains(.connectionAutomatic) ? "a" : "-" + + return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)" + } +} +#endif diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/Notifications.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..4a4b25a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,115 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +public extension Request { + /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`. + static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume") + /// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`. + static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend") + /// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`. + static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel") + /// Posted when a `Request` is finished. The `Notification` contains the completed `Request`. + static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish") + + /// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + static let didResumeTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResumeTask") + /// Posted when a `URLSessionTask` is suspended. The `Notification` contains the `Request` associated with the `URLSessionTask`. + static let didSuspendTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspendTask") + /// Posted when a `URLSessionTask` is cancelled. The `Notification` contains the `Request` associated with the `URLSessionTask`. + static let didCancelTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancelTask") + /// Posted when a `URLSessionTask` is completed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask") +} + +// MARK: - + +extension Notification { + /// The `Request` contained by the instance's `userInfo`, `nil` otherwise. + public var request: Request? { + return userInfo?[String.requestKey] as? Request + } + + /// Convenience initializer for a `Notification` containing a `Request` payload. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + init(name: Notification.Name, request: Request) { + self.init(name: name, object: nil, userInfo: [String.requestKey: request]) + } +} + +extension NotificationCenter { + /// Convenience function for posting notifications with `Request` payloads. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + func postNotification(named name: Notification.Name, with request: Request) { + let notification = Notification(name: name, request: request) + post(notification) + } +} + +extension String { + /// User info dictionary key representing the `Request` associated with the notification. + fileprivate static let requestKey = "org.alamofire.notification.key.request" +} + +/// `EventMonitor` that provides Alamofire's notifications. +public final class AlamofireNotifications: EventMonitor { + public func requestDidResume(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didResumeNotification, with: request) + } + + public func requestDidSuspend(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didSuspendNotification, with: request) + } + + public func requestDidCancel(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didCancelNotification, with: request) + } + + public func requestDidFinish(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didFinishNotification, with: request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didResumeTaskNotification, with: request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didSuspendTaskNotification, with: request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didCancelTaskNotification, with: request) + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request) + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/OperationQueue+Alamofire.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/OperationQueue+Alamofire.swift new file mode 100644 index 0000000..b06a0cc --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/OperationQueue+Alamofire.swift @@ -0,0 +1,49 @@ +// +// OperationQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension OperationQueue { + /// Creates an instance using the provided parameters. + /// + /// - Parameters: + /// - qualityOfService: `QualityOfService` to be applied to the queue. `.default` by default. + /// - maxConcurrentOperationCount: Maximum concurrent operations. + /// `OperationQueue.defaultMaxConcurrentOperationCount` by default. + /// - underlyingQueue: Underlying `DispatchQueue`. `nil` by default. + /// - name: Name for the queue. `nil` by default. + /// - startSuspended: Whether the queue starts suspended. `false` by default. + convenience init(qualityOfService: QualityOfService = .default, + maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount, + underlyingQueue: DispatchQueue? = nil, + name: String? = nil, + startSuspended: Bool = false) { + self.init() + self.qualityOfService = qualityOfService + self.maxConcurrentOperationCount = maxConcurrentOperationCount + self.underlyingQueue = underlyingQueue + self.name = name + isSuspended = startSuspended + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/ParameterEncoder.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/ParameterEncoder.swift new file mode 100644 index 0000000..1e5c70a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/ParameterEncoder.swift @@ -0,0 +1,184 @@ +// +// ParameterEncoder.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that can encode any `Encodable` type into a `URLRequest`. +public protocol ParameterEncoder { + /// Encode the provided `Encodable` parameters into `request`. + /// + /// - Parameters: + /// - parameters: The `Encodable` parameter value. + /// - request: The `URLRequest` into which to encode the parameters. + /// + /// - Returns: A `URLRequest` with the result of the encoding. + /// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of + /// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`. + func encode(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest +} + +/// A `ParameterEncoder` that encodes types as JSON body data. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`. +open class JSONParameterEncoder: ParameterEncoder { + /// Returns an encoder with default parameters. + public static var `default`: JSONParameterEncoder { return JSONParameterEncoder() } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`. + public static var prettyPrinted: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .prettyPrinted + + return JSONParameterEncoder(encoder: encoder) + } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`. + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public static var sortedKeys: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + + return JSONParameterEncoder(encoder: encoder) + } + + /// `JSONEncoder` used to encode parameters. + public let encoder: JSONEncoder + + /// Creates an instance with the provided `JSONEncoder`. + /// + /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default. + public init(encoder: JSONEncoder = JSONEncoder()) { + self.encoder = encoder + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters = parameters else { return request } + + var request = request + + do { + let data = try encoder.encode(parameters) + request.httpBody = data + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/json")) + } + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return request + } +} + +/// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending +/// on the `Destination` set. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer. +open class URLEncodedFormParameterEncoder: ParameterEncoder { + /// Defines where the URL-encoded string should be set for each `URLRequest`. + public enum Destination { + /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request. + /// Sets it to the `httpBody` for all other methods. + case methodDependent + /// Applies the encoded query string to any existing query string from the `URLRequest`. + case queryString + /// Applies the encoded query string to the `httpBody` of the `URLRequest`. + case httpBody + + /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`. + /// + /// - Parameter method: The `HTTPMethod`. + /// + /// - Returns: Whether the URL-encoded string should be applied to a `URL`. + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: return [.get, .head, .delete].contains(method) + case .queryString: return true + case .httpBody: return false + } + } + } + + /// Returns an encoder with default parameters. + public static var `default`: URLEncodedFormParameterEncoder { return URLEncodedFormParameterEncoder() } + + /// The `URLEncodedFormEncoder` to use. + public let encoder: URLEncodedFormEncoder + + /// The `Destination` for the URL-encoded string. + public let destination: Destination + + /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value. + /// + /// - Parameters: + /// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default. + /// - destination: The `Destination`. `.methodDependent` by default. + public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) { + self.encoder = encoder + self.destination = destination + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters = parameters else { return request } + + var request = request + + guard let url = request.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + guard let method = request.method else { + let rawValue = request.method?.rawValue ?? "nil" + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue))) + } + + if destination.encodesParametersInURL(for: method), + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { + let query: String = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands() + components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString + + guard let newURL = components.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + request.url = newURL + } else { + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) + } + + request.httpBody = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + } + + return request + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/ParameterEncoding.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..fbf1701 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,314 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// Creates a `URLRequest` by encoding parameters and applying them on the passed request. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. + /// - parameters: `Parameters` to encode onto the request. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during parameter encoding. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// There is no published specification for how to encode collection types. By default the convention of appending +/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for +/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the +/// square brackets appended to array keys. +/// +/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. +public struct URLEncoding: ParameterEncoding { + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + public enum Destination { + /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and + /// sets as the HTTP body for requests with any other HTTP method. + case methodDependent + /// Sets or appends encoded query string result to existing query string. + case queryString + /// Sets encoded query string result as the HTTP body of the URL request. + case httpBody + + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: return [.get, .head, .delete].contains(method) + case .queryString: return true + case .httpBody: return false + } + } + } + + /// Configures how `Array` parameters are encoded. + public enum ArrayEncoding { + /// An empty set of square brackets is appended to the key for every value. This is the default behavior. + case brackets + /// No brackets are appended. The key is encoded as is. + case noBrackets + + func encode(key: String) -> String { + switch self { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + } + } + } + + /// Configures how `Bool` parameters are encoded. + public enum BoolEncoding { + /// Encode `true` as `1` and `false` as `0`. This is the default behavior. + case numeric + /// Encode `true` and `false` as string literals. + case literal + + func encode(value: Bool) -> String { + switch self { + case .numeric: + return value ? "1" : "0" + case .literal: + return value ? "true" : "false" + } + } + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance with a `.methodDependent` destination. + public static var `default`: URLEncoding { 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 an instance using the specified parameters. + /// + /// - Parameters: + /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by + /// default. + /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default. + public init(destination: Destination = .methodDependent, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric) { + self.destination = destination + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + } + + // MARK: Encoding + + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = urlRequest.method, destination.encodesParametersInURL(for: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = Data(query(parameters).utf8) + } + + return urlRequest + } + + /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively. + /// + /// - Parameters: + /// - key: Key of the query component. + /// - value: Value of the query component. + /// + /// - Returns: The percent-escaped, URL encoded query string components. + public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + + 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 + } + + /// Creates a percent-escaped string following RFC 3986 for a query string key or value. + /// + /// - Parameter string: `String` to be percent-escaped. + /// + /// - Returns: The percent-escaped `String`. + public func escape(_ string: String) -> String { + return string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string + } + + private func query(_ parameters: [String: Any]) -> String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + return components.map { "\($0)=\($1)" }.joined(separator: "&") + } +} + +// MARK: - + +/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the +/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +public struct JSONEncoding: ParameterEncoding { + // 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 an instance using the specified `WritingOptions`. + /// + /// - Parameter options: `JSONSerialization.WritingOptions` to use. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + 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 + } + + /// Encodes any JSON compatible object into a `URLRequest`. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value into which the object will be encoded. + /// - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during encoding. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + 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: - + +extension NSNumber { + fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/Protector.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/Protector.swift new file mode 100644 index 0000000..3e42a53 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/Protector.swift @@ -0,0 +1,167 @@ +// +// Protector.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +// MARK: - + +/// An `os_unfair_lock` wrapper. +final class UnfairLock { + private let unfairLock: os_unfair_lock_t + + init() { + unfairLock = .allocate(capacity: 1) + unfairLock.initialize(to: os_unfair_lock()) + } + + deinit { + unfairLock.deinitialize(count: 1) + unfairLock.deallocate() + } + + private func lock() { + os_unfair_lock_lock(unfairLock) + } + + private func unlock() { + os_unfair_lock_unlock(unfairLock) + } + + /// Executes a closure returning a value while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + /// + /// - Returns: The value the closure generated. + func around(_ closure: () -> T) -> T { + lock(); defer { unlock() } + return closure() + } + + /// Execute a closure while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + func around(_ closure: () -> Void) { + lock(); defer { unlock() } + return closure() + } +} + +/// A thread-safe wrapper around a value. +final class Protector { + private let lock = UnfairLock() + private var value: T + + init(_ value: T) { + self.value = value + } + + /// The contained value. Unsafe for anything more than direct read or write. + var directValue: T { + get { return lock.around { value } } + set { lock.around { value = newValue } } + } + + /// Synchronously read or transform the contained value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The return value of the closure passed. + func read(_ closure: (T) -> U) -> U { + return lock.around { closure(self.value) } + } + + /// Synchronously modify the protected value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The modified value. + @discardableResult + func write(_ closure: (inout T) -> U) -> U { + return lock.around { closure(&self.value) } + } +} + +extension Protector where T: RangeReplaceableCollection { + /// Adds a new element to the end of this protected collection. + /// + /// - Parameter newElement: The `Element` to append. + func append(_ newElement: T.Element) { + write { (ward: inout T) in + ward.append(newElement) + } + } + + /// Adds the elements of a sequence to the end of this protected collection. + /// + /// - Parameter newElements: The `Sequence` to append. + func append(contentsOf newElements: S) where S.Element == T.Element { + write { (ward: inout T) in + ward.append(contentsOf: newElements) + } + } + + /// Add the elements of a collection to the end of the protected collection. + /// + /// - Parameter newElements: The `Collection` to append. + func append(contentsOf newElements: C) where C.Element == T.Element { + write { (ward: inout T) in + ward.append(contentsOf: newElements) + } + } +} + +extension Protector where T == Data? { + /// Adds the contents of a `Data` value to the end of the protected `Data`. + /// + /// - Parameter data: The `Data` to be appended. + func append(_ data: Data) { + write { (ward: inout T) in + ward?.append(data) + } + } +} + +extension Protector where T == Request.MutableState { + /// Attempts to transition to the passed `State`. + /// + /// - Parameter state: The `State` to attempt transition to. + /// + /// - Returns: Whether the transition occurred. + func attemptToTransitionTo(_ state: Request.State) -> Bool { + return lock.around { + guard value.state.canTransitionTo(state) else { return false } + + value.state = state + + return true + } + } + + /// Perform a closure while locked with the provided `Request.State`. + /// + /// - Parameter perform: The closure to perform while locked. + func withState(perform: (Request.State) -> Void) { + lock.around { perform(value.state) } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/RedirectHandler.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/RedirectHandler.swift new file mode 100644 index 0000000..b6c069c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/RedirectHandler.swift @@ -0,0 +1,95 @@ +// +// RedirectHandler.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that handles how an HTTP redirect response from a remote server should be redirected to the new request. +public protocol RedirectHandler { + /// Determines how the HTTP redirect response should be redirected to the new request. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The new request specified by the redirect (this is the most common use case). + /// 2. A modified version of the new request (you may want to route it somewhere else). + /// 3. A `nil` value to deny the redirect request and return the body of the redirect response. + /// + /// - Parameters: + /// - task: The `URLSessionTask` whose request resulted in a redirect. + /// - request: The `URLRequest` to the new location specified by the redirect response. + /// - response: The `HTTPURLResponse` containing the server's response to the original request. + /// - completion: The closure to execute containing the new `URLRequest`, a modified `URLRequest`, or `nil`. + func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) +} + +// MARK: - + +/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect. +public struct Redirector { + /// Defines the behavior of the `Redirector` type. + public enum Behavior { + /// Follow the redirect as defined in the response. + case follow + /// Do not follow the redirect defined in the response. + case doNotFollow + /// Modify the redirect request defined in the response. + case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) + } + + /// Returns a `Redirector` with a `.follow` `Behavior`. + public static let follow = Redirector(behavior: .follow) + /// Returns a `Redirector` with a `.doNotFollow` `Behavior`. + public static let doNotFollow = Redirector(behavior: .doNotFollow) + + /// The `Behavior` of the `Redirector`. + public let behavior: Behavior + + /// Creates a `Redirector` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +// MARK: - + +extension Redirector: RedirectHandler { + public func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) { + switch behavior { + case .follow: + completion(request) + case .doNotFollow: + completion(nil) + case let .modify(closure): + let request = closure(task, request, response) + completion(request) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/Request.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000..6398d96 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,1460 @@ +// +// Request.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback +/// handling. +public class Request { + /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or + /// `cancel()` on the `Request`. + public enum State { + /// Initial state of the `Request`. + case initialized + /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on + /// them in this state. + case resumed + /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on + /// them in this state. + case suspended + /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on + /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition + /// to any other state. + case cancelled + /// `State` set when all response serialization completion closures have been cleared on the `Request` and + /// enqueued on their respective queues. + case finished + + /// Determines whether `self` can be transitioned to the provided `State`. + func canTransitionTo(_ state: State) -> Bool { + switch (self, state) { + case (.initialized, _): + return true + case (_, .initialized), (.cancelled, _), (.finished, _): + return false + case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed): + return true + case (.suspended, .suspended), (.resumed, .resumed): + return false + case (_, .finished): + return true + } + } + } + + // MARK: - Initial State + + /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances. + public let id: UUID + /// The serial queue for all internal async actions. + public let underlyingQueue: DispatchQueue + /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`. + public let serializationQueue: DispatchQueue + /// `EventMonitor` used for event callbacks. + public let eventMonitor: EventMonitor? + /// The `Request`'s interceptor. + public let interceptor: RequestInterceptor? + /// The `Request`'s delegate. + public private(set) weak var delegate: RequestDelegate? + + // MARK: - Mutable State + + /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`. + struct MutableState { + /// State of the `Request`. + var state: State = .initialized + /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks. + var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks. + var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `RedirectHandler` provided for to handle request redirection. + var redirectHandler: RedirectHandler? + /// `CachedResponseHandler` provided to handle response caching. + var cachedResponseHandler: CachedResponseHandler? + /// Closure called when the `Request` is able to create a cURL description of itself. + var cURLHandler: ((String) -> Void)? + /// Response serialization closures that handle response parsing. + var responseSerializers: [() -> Void] = [] + /// Response serialization completion closures executed once all response serializers are complete. + var responseSerializerCompletions: [() -> Void] = [] + /// Whether response serializer processing is finished. + var responseSerializerProcessingFinished = false + /// `URLCredential` used for authentication challenges. + var credential: URLCredential? + /// All `URLRequest`s created by Alamofire on behalf of the `Request`. + var requests: [URLRequest] = [] + /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`. + var tasks: [URLSessionTask] = [] + /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond + /// exactly the the `tasks` created. + var metrics: [URLSessionTaskMetrics] = [] + /// Number of times any retriers provided retried the `Request`. + var retryCount = 0 + /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`. + var error: AFError? + } + + /// Protected `MutableState` value that provides thread-safe access to state values. + fileprivate let protectedMutableState: Protector = Protector(MutableState()) + + /// `State` of the `Request`. + public var state: State { return protectedMutableState.directValue.state } + /// Returns whether `state` is `.initialized`. + public var isInitialized: Bool { return state == .initialized } + /// Returns whether `state is `.resumed`. + public var isResumed: Bool { return state == .resumed } + /// Returns whether `state` is `.suspended`. + public var isSuspended: Bool { return state == .suspended } + /// Returns whether `state` is `.cancelled`. + public var isCancelled: Bool { return state == .cancelled } + /// Returns whether `state` is `.finished`. + public var isFinished: Bool { return state == .finished } + + // MARK: Progress + + /// Closure type executed when monitoring the upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried. + public let uploadProgress = Progress(totalUnitCount: 0) + /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried. + public let downloadProgress = Progress(totalUnitCount: 0) + /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`. + fileprivate var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { return protectedMutableState.directValue.uploadProgressHandler } + set { protectedMutableState.write { $0.uploadProgressHandler = newValue } } + } + + /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. + fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { return protectedMutableState.directValue.downloadProgressHandler } + set { protectedMutableState.write { $0.downloadProgressHandler = newValue } } + } + + // MARK: Redirect Handling + + /// `RedirectHandler` set on the instance. + public private(set) var redirectHandler: RedirectHandler? { + get { return protectedMutableState.directValue.redirectHandler } + set { protectedMutableState.write { $0.redirectHandler = newValue } } + } + + // MARK: Cached Response Handling + + /// `CachedResponseHandler` set on the instance. + public private(set) var cachedResponseHandler: CachedResponseHandler? { + get { return protectedMutableState.directValue.cachedResponseHandler } + set { protectedMutableState.write { $0.cachedResponseHandler = newValue } } + } + + // MARK: URLCredential + + /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. + public private(set) var credential: URLCredential? { + get { return protectedMutableState.directValue.credential } + set { protectedMutableState.write { $0.credential = newValue } } + } + + // MARK: Validators + + /// `Validator` callback closures that store the validation calls enqueued. + fileprivate var protectedValidators: Protector<[() -> Void]> = Protector([]) + + // MARK: URLRequests + + /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests. + public var requests: [URLRequest] { return protectedMutableState.directValue.requests } + /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. + public var firstRequest: URLRequest? { return requests.first } + /// Last `URLRequest` created on behalf of the `Request`. + public var lastRequest: URLRequest? { return requests.last } + /// Current `URLRequest` created on behalf of the `Request`. + public var request: URLRequest? { return lastRequest } + + /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from + /// `requests` due to `URLSession` manipulation. + public var performedRequests: [URLRequest] { + return protectedMutableState.read { $0.tasks.compactMap { $0.currentRequest } } + } + + // MARK: HTTPURLResponse + + /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the + /// last `URLSessionTask`. + public var response: HTTPURLResponse? { return lastTask?.response as? HTTPURLResponse } + + // MARK: Tasks + + /// All `URLSessionTask`s created on behalf of the `Request`. + public var tasks: [URLSessionTask] { return protectedMutableState.directValue.tasks } + /// First `URLSessionTask` created on behalf of the `Request`. + public var firstTask: URLSessionTask? { return tasks.first } + /// Last `URLSessionTask` crated on behalf of the `Request`. + public var lastTask: URLSessionTask? { return tasks.last } + /// Current `URLSessionTask` created on behalf of the `Request`. + public var task: URLSessionTask? { return lastTask } + + // MARK: Metrics + + /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. + public var allMetrics: [URLSessionTaskMetrics] { return protectedMutableState.directValue.metrics } + /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var firstMetrics: URLSessionTaskMetrics? { return allMetrics.first } + /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var lastMetrics: URLSessionTaskMetrics? { return allMetrics.last } + /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var metrics: URLSessionTaskMetrics? { return lastMetrics } + + // MARK: Retry Count + + /// Number of times the `Request` has been retried. + public var retryCount: Int { return protectedMutableState.directValue.retryCount } + + // MARK: Error + + /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. + public fileprivate(set) var error: AFError? { + get { return protectedMutableState.directValue.error } + set { protectedMutableState.write { $0.error = newValue } } + } + + /// Default initializer for the `Request` superclass. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.id = id + self.underlyingQueue = underlyingQueue + self.serializationQueue = serializationQueue + self.eventMonitor = eventMonitor + self.interceptor = interceptor + self.delegate = delegate + } + + // MARK: - Internal Event API + + // All API must be called from underlyingQueue. + + /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, + /// the `URLRequest` will be adapted before being issued. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateInitialURLRequest(_ request: URLRequest) { + protectedMutableState.write { $0.requests.append(request) } + + eventMonitor?.request(self, didCreateInitialURLRequest: request) + } + + /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. + /// + /// - Note: Triggers retry. + /// + /// - Parameter error: `AFError` thrown from the failed creation. + func didFailToCreateURLRequest(with error: AFError) { + self.error = error + + eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`. + /// + /// - Parameters: + /// - initialRequest: The `URLRequest` that was adapted. + /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`. + func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) { + protectedMutableState.write { $0.requests.append(adaptedRequest) } + + eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) + } + + /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. + /// + /// - Note: Triggers retry. + /// + /// - Parameters: + /// - request: The `URLRequest` the adapter was called with. + /// - error: The `AFError` returned by the `RequestAdapter`. + func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { + self.error = error + + eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Final `URLRequest` has been created for the instance. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateURLRequest(_ request: URLRequest) { + eventMonitor?.request(self, didCreateURLRequest: request) + + callCURLHandlerIfNecessary() + } + + /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. + private func callCURLHandlerIfNecessary() { + protectedMutableState.write { mutableState in + guard let cURLHandler = mutableState.cURLHandler else { return } + + self.underlyingQueue.async { cURLHandler(self.cURLDescription()) } + mutableState.cURLHandler = nil + } + } + + /// Called when a `URLSessionTask` is created on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` created. + func didCreateTask(_ task: URLSessionTask) { + protectedMutableState.write { $0.tasks.append(task) } + + eventMonitor?.request(self, didCreateTask: task) + } + + /// Called when resumption is completed. + func didResume() { + eventMonitor?.requestDidResume(self) + } + + /// Called when a `URLSessionTask` is resumed on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` resumed. + func didResumeTask(_ task: URLSessionTask) { + eventMonitor?.request(self, didResumeTask: task) + } + + /// Called when suspension is completed. + func didSuspend() { + eventMonitor?.requestDidSuspend(self) + } + + /// Called when a `URLSessionTask` is suspended on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` suspended. + func didSuspendTask(_ task: URLSessionTask) { + eventMonitor?.request(self, didSuspendTask: task) + } + + /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. + func didCancel() { + error = AFError.explicitlyCancelled + + eventMonitor?.requestDidCancel(self) + } + + /// Called when a `URLSessionTask` is cancelled on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` cancelled. + func didCancelTask(_ task: URLSessionTask) { + eventMonitor?.request(self, didCancelTask: task) + } + + /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance. + /// + /// - Parameter metrics: The `URLSessionTaskMetrics` gathered. + func didGatherMetrics(_ metrics: URLSessionTaskMetrics) { + protectedMutableState.write { $0.metrics.append(metrics) } + + eventMonitor?.request(self, didGatherMetrics: metrics) + } + + /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which failed. + /// - error: The early failure `AFError`. + func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) { + self.error = error + + // Task will still complete, so didCompleteTask(_:with:) will handle retry. + eventMonitor?.request(self, didFailTask: task, earlyWithError: error) + } + + /// Called when a `URLSessionTask` completes. All tasks will eventually call this method. + /// + /// - Note: Response validation is synchronously triggered in this step. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which completed. + /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this + /// value is ignored. + func didCompleteTask(_ task: URLSessionTask, with error: AFError?) { + self.error = self.error ?? error + protectedValidators.directValue.forEach { $0() } + + eventMonitor?.request(self, didCompleteTask: task, with: error) + + retryOrFinish(error: self.error) + } + + /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. + func prepareForRetry() { + protectedMutableState.write { $0.retryCount += 1 } + + reset() + + eventMonitor?.requestIsRetrying(self) + } + + /// Called to determine whether retry will be triggered for the particular error, or whether the instance should + /// call `finish()`. + /// + /// - Parameter error: The possible `AFError` which may trigger retry. + func retryOrFinish(error: AFError?) { + guard let error = error, let delegate = delegate else { finish(); return } + + delegate.retryResult(for: self, dueTo: error) { retryResult in + switch retryResult { + case .doNotRetry: + self.finish() + case let .doNotRetryWithError(retryError): + self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + + /// Finishes this `Request` and starts the response serializers. + /// + /// - Parameter error: The possible `Error` with which the instance will finish. + func finish(error: AFError? = nil) { + if let error = error { self.error = error } + + // Start response handlers + processNextResponseSerializer() + + eventMonitor?.requestDidFinish(self) + } + + /// Appends the response serialization closure to the instance. + /// + /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. + /// + /// - Parameter closure: The closure containing the response serialization call. + func appendResponseSerializer(_ closure: @escaping () -> Void) { + protectedMutableState.write { mutableState in + mutableState.responseSerializers.append(closure) + + if mutableState.state == .finished { + mutableState.state = .resumed + } + + if mutableState.responseSerializerProcessingFinished { + underlyingQueue.async { self.processNextResponseSerializer() } + } + + if mutableState.state.canTransitionTo(.resumed) { + underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } } + } + } + } + + /// Returns the next response serializer closure to execute if there's one left. + /// + /// - Returns: The next response serialization closure, if there is one. + func nextResponseSerializer() -> (() -> Void)? { + var responseSerializer: (() -> Void)? + + protectedMutableState.write { mutableState in + let responseSerializerIndex = mutableState.responseSerializerCompletions.count + + if responseSerializerIndex < mutableState.responseSerializers.count { + responseSerializer = mutableState.responseSerializers[responseSerializerIndex] + } + } + + return responseSerializer + } + + /// Processes the next response serializer and calls all completions if response serialization is complete. + func processNextResponseSerializer() { + guard let responseSerializer = nextResponseSerializer() else { + // Execute all response serializer completions and clear them + var completions: [() -> Void] = [] + + protectedMutableState.write { mutableState in + completions = mutableState.responseSerializerCompletions + + // Clear out all response serializers and response serializer completions in mutable state since the + // request is complete. It's important to do this prior to calling the completion closures in case + // the completions call back into the request triggering a re-processing of the response serializers. + // An example of how this can happen is by calling cancel inside a response completion closure. + mutableState.responseSerializers.removeAll() + mutableState.responseSerializerCompletions.removeAll() + + if mutableState.state.canTransitionTo(.finished) { + mutableState.state = .finished + } + + mutableState.responseSerializerProcessingFinished = true + } + + completions.forEach { $0() } + + // Cleanup the request + cleanup() + + return + } + + serializationQueue.async { responseSerializer() } + } + + /// Notifies the `Request` that the response serializer is complete. + /// + /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers + /// are complete. + func responseSerializerDidComplete(completion: @escaping () -> Void) { + protectedMutableState.write { $0.responseSerializerCompletions.append(completion) } + processNextResponseSerializer() + } + + /// Resets all task and response serializer related state for retry. + func reset() { + error = nil + + uploadProgress.totalUnitCount = 0 + uploadProgress.completedUnitCount = 0 + downloadProgress.totalUnitCount = 0 + downloadProgress.completedUnitCount = 0 + + protectedMutableState.write { $0.responseSerializerCompletions = [] } + } + + /// Called when updating the upload progress. + /// + /// - Parameters: + /// - totalBytesSent: Total bytes sent so far. + /// - totalBytesExpectedToSend: Total bytes expected to send. + func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } + } + + /// Perform a closure on the current `state` while locked. + /// + /// - Parameter perform: The closure to perform. + func withState(perform: (State) -> Void) { + protectedMutableState.withState(perform: perform) + } + + // MARK: Task Creation + + /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override. + /// + /// - Parameters: + /// - request: `URLRequest` to use to create the `URLSessionTask`. + /// - session: `URLSession` which creates the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + fatalError("Subclasses must override.") + } + + // MARK: - Public API + + // These APIs are callable from any queue. + + // MARK: State + + /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. + /// + /// - Returns: The instance. + @discardableResult + public func cancel() -> Self { + protectedMutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + underlyingQueue.async { self.didCancelTask(task) } + } + + return self + } + + /// Suspends the instance. + /// + /// - Returns: The instance. + @discardableResult + public func suspend() -> Self { + protectedMutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.suspended) else { return } + + mutableState.state = .suspended + + underlyingQueue.async { self.didSuspend() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.suspend() + underlyingQueue.async { self.didSuspendTask(task) } + } + + return self + } + + /// Resumes the instance. + /// + /// - Returns: The instance. + @discardableResult + public func resume() -> Self { + protectedMutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.resumed) else { return } + + mutableState.state = .resumed + + underlyingQueue.async { self.didResume() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.resume() + underlyingQueue.async { self.didResumeTask(task) } + } + + return self + } + + // MARK: - Closure API + + /// Associates a credential using the provided values with the instance. + /// + /// - Parameters: + /// - username: The username. + /// - password: The password. + /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { + let credential = URLCredential(user: username, password: password, persistence: persistence) + + return authenticate(with: credential) + } + + /// Associates the provided credential with the instance. + /// + /// - Parameter credential: The `URLCredential`. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(with credential: URLCredential) -> Self { + protectedMutableState.write { $0.credential = credential } + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is read from the server. + /// + /// - Returns: The instance. + @discardableResult + public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) } + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is sent to the server. + /// + /// - Returns: The instance. + @discardableResult + public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) } + + return self + } + + // MARK: Redirects + + /// Sets the redirect handler for the instance which will be used if a redirect response is encountered. + /// + /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `RedirectHandler`. + /// + /// - Returns: The instance. + @discardableResult + public func redirect(using handler: RedirectHandler) -> Self { + protectedMutableState.write { mutableState in + precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") + mutableState.redirectHandler = handler + } + + return self + } + + // MARK: Cached Responses + + /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response. + /// + /// - Note: Attempting to set the cache handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `CachedResponseHandler`. + /// + /// - Returns: The instance. + @discardableResult + public func cacheResponse(using handler: CachedResponseHandler) -> Self { + protectedMutableState.write { mutableState in + precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") + mutableState.cachedResponseHandler = handler + } + + return self + } + + /// Sets a handler to be called when the cURL description of the request is available. + /// + /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. + /// + /// - Parameter handler: Closure to be called when the cURL description is available. + /// + /// - Returns: The instance. + @discardableResult + public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { + protectedMutableState.write { mutableState in + if mutableState.requests.last != nil { + underlyingQueue.async { handler(self.cURLDescription()) } + } else { + mutableState.cURLHandler = handler + } + } + + return self + } + + // MARK: Cleanup + + /// Final cleanup step executed when the instance finishes response serialization. + func cleanup() { + delegate?.cleanup(after: self) + // No-op: override in subclass + } +} + +// MARK: - Protocol Conformances + +extension Request: Equatable { + public static func ==(lhs: Request, rhs: Request) -> Bool { + return lhs.id == rhs.id + } +} + +extension Request: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(id) + } +} + +extension Request: CustomStringConvertible { + /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been + /// created, as well as the response status code, if a response has been received. + public var description: String { + guard let request = performedRequests.last ?? lastRequest, + let url = request.url, + let method = request.httpMethod else { return "No request created yet." } + + let requestDescription = "\(method) \(url.absoluteString)" + + return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription + } +} + +extension Request { + /// cURL representation of the instance. + /// + /// - Returns: The cURL equivalent of the instance. + public func cURLDescription() -> String { + guard + let request = lastRequest, + let url = request.url, + let host = url.host, + let method = request.httpMethod else { return "$ curl command could not be created" } + + var components = ["$ curl -v"] + + components.append("-X \(method)") + + if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace(host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic) + + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { + for credential in credentials { + guard let user = credential.user, let password = credential.password else { continue } + components.append("-u \(user):\(password)") + } + } else { + if let credential = credential, let user = credential.user, let password = credential.password { + components.append("-u \(user):\(password)") + } + } + } + + if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { + if + let cookieStorage = configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { + let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";") + + components.append("-b \"\(allCookies)\"") + } + } + + var headers = HTTPHeaders() + + if let sessionHeaders = delegate?.sessionConfiguration.headers { + for header in sessionHeaders where header.name != "Cookie" { + headers[header.name] = header.value + } + } + + for header in request.headers where header.name != "Cookie" { + headers[header.name] = header.value + } + + for header in headers { + let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"") + components.append("-H \"\(header.name): \(escapedValue)\"") + } + + if let httpBodyData = request.httpBody { + let httpBody = String(decoding: httpBodyData, as: UTF8.self) + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(url.absoluteString)\"") + + return components.joined(separator: " \\\n\t") + } +} + +/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`. +public protocol RequestDelegate: AnyObject { + /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s. + var sessionConfiguration: URLSessionConfiguration { get } + + /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler. + var startImmediately: Bool { get } + + /// Notifies the delegate the `Request` has reached a point where it needs cleanup. + /// + /// - Parameter request: The `Request` to cleanup after. + func cleanup(after request: Request) + + /// Asynchronously ask the delegate whether a `Request` will be retried. + /// + /// - Parameters: + /// - request: `Request` which failed. + /// - error: `Error` which produced the failure. + /// - completion: Closure taking the `RetryResult` for evaluation. + func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) + + /// Asynchronously retry the `Request`. + /// + /// - Parameters: + /// - request: `Request` which will be retried. + /// - timeDelay: `TimeInterval` after which the retry will be triggered. + func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) +} + +// MARK: - Subclasses + +// MARK: - DataRequest + +/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`. +public class DataRequest: Request { + /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. + public let convertible: URLRequestConvertible + /// `Data` read from the server so far. + public var data: Data? { return protectedData.directValue } + + /// Protected storage for the `Data` read by the instance. + private var protectedData: Protector = Protector(nil) + + /// Creates a `DataRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: URLRequestConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.convertible = convertible + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + protectedData.directValue = nil + } + + /// Called when `Data` is received by this instance. + /// + /// - Note: Also calls `updateDownloadProgress`. + /// + /// - Parameter data: The `Data` received. + func didReceive(data: Data) { + if self.data == nil { + protectedData.directValue = data + } else { + protectedData.append(data) + } + + updateDownloadProgress() + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + /// Called to updated the `downloadProgress` of the instance. + func updateDownloadProgress() { + let totalBytesReceived = Int64(data?.count ?? 0) + let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + downloadProgress.totalUnitCount = totalBytesExpected + downloadProgress.completedUnitCount = totalBytesReceived + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure used to validate the response. + /// + /// - Returns: The instance. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard self.error == nil, let response = self.response else { return } + + let result = validation(self.request, response, self.data) + + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } + + self.eventMonitor?.request(self, + didValidateRequest: self.request, + response: response, + data: self.data, + withResult: result) + } + + protectedValidators.append(validator) + + return self + } +} + +// MARK: - DownloadRequest + +/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`. +public class DownloadRequest: Request { + /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination + /// `URL`. + public struct Options: OptionSet { + /// Specifies that intermediate directories for the destination URL should be created. + public static let createIntermediateDirectories = Options(rawValue: 1 << 0) + /// Specifies that any previous file at the destination `URL` should be removed. + public static let removePreviousFile = Options(rawValue: 1 << 1) + + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + } + + // MARK: Destination + + /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the + /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL + /// and the 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 Destination = (_ temporaryURL: URL, + _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) + + /// Creates a download file destination closure which uses the default file manager to move the temporary file to a + /// file URL in the first available directory with the specified search path directory and search path domain mask. + /// + /// - Parameters: + /// - directory: The search path directory. `.documentDirectory` by default. + /// - domain: The search path domain mask. `.userDomainMask` by default. + /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by + /// default. + /// - Returns: The `Destination` closure. + public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask, + options: Options = []) -> Destination { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL + + return (url, options) + } + } + + /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends + /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files + /// with this destination must be additionally moved if they should survive the system reclamation of temporary + /// space. + static let defaultDestination: Destination = { url, _ in + let filename = "Alamofire_\(url.lastPathComponent)" + let destination = url.deletingLastPathComponent().appendingPathComponent(filename) + + return (destination, []) + } + + // MARK: Downloadable + + /// Type describing the source used to create the underlying `URLSessionDownloadTask`. + public enum Downloadable { + /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. + case request(URLRequestConvertible) + /// Download should be started from the associated resume `Data` value. + case resumeData(Data) + } + + // MARK: Mutable State + + /// Type containing all mutable state for `DownloadRequest` instances. + private struct DownloadRequestMutableState { + /// Possible resume `Data` produced when cancelling the instance. + var resumeData: Data? + /// `URL` to which `Data` is being downloaded. + var fileURL: URL? + } + + /// Protected mutable state specific to `DownloadRequest`. + private let protectedDownloadMutableState: Protector = Protector(DownloadRequestMutableState()) + + /// If the download is resumable and eventually cancelled, this value may be used to resume the download using the + /// `download(resumingWith data:)` API. + /// + /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel). + public var resumeData: Data? { return protectedDownloadMutableState.directValue.resumeData } + /// If the download is successful, the `URL` where the file was downloaded. + public var fileURL: URL? { return protectedDownloadMutableState.directValue.fileURL } + + // MARK: Initial State + + /// `Downloadable` value used for this instance. + public let downloadable: Downloadable + /// The `Destination` to which the downloaded file is moved. + let destination: Destination + + /// Creates a `DownloadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request` + /// - destination: `Destination` closure used to move the downloaded file to its final location. + init(id: UUID = UUID(), + downloadable: Downloadable, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate, + destination: @escaping Destination) { + self.downloadable = downloadable + self.destination = destination + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + protectedDownloadMutableState.write { + $0.resumeData = nil + $0.fileURL = nil + } + } + + /// Called when a download has finished. + /// + /// - Parameters: + /// - task: `URLSessionTask` that finished the download. + /// - result: `Result` of the automatic move to `destination`. + func didFinishDownloading(using task: URLSessionTask, with result: Result) { + eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) + + switch result { + case let .success(url): protectedDownloadMutableState.write { $0.fileURL = url } + case let .failure(error): self.error = error + } + } + + /// Updates the `downloadProgress` using the provided values. + /// + /// - Parameters: + /// - bytesWritten: Total bytes written so far. + /// - totalBytesExpectedToWrite: Total bytes expected to write. + func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + downloadProgress.totalUnitCount = totalBytesExpectedToWrite + downloadProgress.completedUnitCount += bytesWritten + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + return session.downloadTask(with: request) + } + + /// Creates a `URLSessionTask` from the provided resume data. + /// + /// - Parameters: + /// - data: `Data` used to resume the download. + /// - session: `URLSession` used to create the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { + return session.downloadTask(withResumeData: data) + } + + /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended. + /// + /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use + /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`. + /// + /// - Returns: The instance. + @discardableResult + public override func cancel() -> Self { + return cancel(producingResumeData: false) + } + + /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be + /// resumed or suspended. + /// + /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if + /// available. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self { + return cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil) + } + + /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed + /// or suspended. + /// + /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` + /// property. + /// + /// - Parameter completionHandler: The completion handler that is called when the download has been successfully + /// cancelled. It is not guaranteed to be called on a particular queue, so you may + /// want use an appropriate queue to perform your work. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self { + return cancel(optionallyProducingResumeData: completionHandler) + } + + /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed, + /// cancellation is performed without producing resume data. + /// + /// - Parameter completionHandler: Optional resume data handler. + /// + /// - Returns: The instance. + private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self { + protectedMutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + if let completionHandler = completionHandler { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel { resumeData in + self.protectedDownloadMutableState.write { $0.resumeData = resumeData } + self.underlyingQueue.async { self.didCancelTask(task) } + completionHandler(resumeData) + } + } else { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + self.underlyingQueue.async { self.didCancelTask(task) } + } + } + + return self + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure to validate the response. + /// + /// - Returns: The instance. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard self.error == nil, let response = self.response else { return } + + let result = validation(self.request, response, self.fileURL) + + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } + + self.eventMonitor?.request(self, + didValidateRequest: self.request, + response: response, + fileURL: self.fileURL, + withResult: result) + } + + protectedValidators.append(validator) + + return self + } +} + +// MARK: - UploadRequest + +/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`. +public class UploadRequest: DataRequest { + /// Type describing the origin of the upload, whether `Data`, file, or stream. + public enum Uploadable { + /// Upload from the provided `Data` value. + case data(Data) + /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be + /// automatically removed once uploaded. + case file(URL, shouldRemove: Bool) + /// Upload from the provided `InputStream`. + case stream(InputStream) + } + + // MARK: Initial State + + /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. + public let upload: UploadableConvertible + + /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written + /// to disk. + public let fileManager: FileManager + + // MARK: Mutable State + + /// `Uploadable` value used by the instance. + public var uploadable: Uploadable? + + /// Creates an `UploadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: UploadConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + fileManager: FileManager, + delegate: RequestDelegate) { + upload = convertible + self.fileManager = fileManager + + super.init(id: id, + convertible: convertible, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + /// Called when the `Uploadable` value has been created from the `UploadConvertible`. + /// + /// - Parameter uploadable: The `Uploadable` that was created. + func didCreateUploadable(_ uploadable: Uploadable) { + self.uploadable = uploadable + + eventMonitor?.request(self, didCreateUploadable: uploadable) + } + + /// Called when the `Uploadable` value could not be created. + /// + /// - Parameter error: `AFError` produced by the failure. + func didFailToCreateUploadable(with error: AFError) { + self.error = error + + eventMonitor?.request(self, didFailToCreateUploadableWithError: error) + + retryOrFinish(error: error) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + guard let uploadable = uploadable else { + fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.") + } + + switch uploadable { + case let .data(data): return session.uploadTask(with: request, from: data) + case let .file(url, _): return session.uploadTask(with: request, fromFile: url) + case .stream: return session.uploadTask(withStreamedRequest: request) + } + } + + /// Produces the `InputStream` from `uploadable`, if it can. + /// + /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash. + /// + /// - Returns: The `InputStream`. + func inputStream() -> InputStream { + guard let uploadable = uploadable else { + fatalError("Attempting to access the input stream but the uploadable doesn't exist.") + } + + guard case let .stream(stream) = uploadable else { + fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") + } + + eventMonitor?.request(self, didProvideInputStream: stream) + + return stream + } + + public override func cleanup() { + defer { super.cleanup() } + + guard + let uploadable = self.uploadable, + case let .file(url, shouldRemove) = uploadable, + shouldRemove + else { return } + + try? fileManager.removeItem(at: url) + } +} + +/// A type that can produce an `UploadRequest.Uploadable` value. +public protocol UploadableConvertible { + /// Produces an `UploadRequest.Uploadable` value from the instance. + /// + /// - Returns: The `UploadRequest.Uploadable`. + /// - Throws: Any `Error` produced during creation. + func createUploadable() throws -> UploadRequest.Uploadable +} + +extension UploadRequest.Uploadable: UploadableConvertible { + public func createUploadable() throws -> UploadRequest.Uploadable { + return self + } +} + +/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. +public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/RequestInterceptor.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/RequestInterceptor.swift new file mode 100644 index 0000000..09ba4ee --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/RequestInterceptor.swift @@ -0,0 +1,243 @@ +// +// RequestInterceptor.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest` to adapt. + /// - session: The `Session` that will execute the `URLRequest`. + /// - completion: The completion handler that must be called when adaptation is complete. + func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) +} + +// MARK: - + +/// Outcome of determination whether retry is necessary. +public enum RetryResult { + /// Retry should be attempted immediately. + case retry + /// Retry should be attempted after the associated `TimeInterval`. + case retryWithDelay(TimeInterval) + /// Do not retry. + case doNotRetry + /// Do not retry due to the associated `Error`. + case doNotRetryWithError(Error) +} + +extension RetryResult { + var retryRequired: Bool { + switch self { + case .retry, .retryWithDelay: return true + default: return false + } + } + + var delay: TimeInterval? { + switch self { + case let .retryWithDelay(delay): return delay + default: return nil + } + } + + var error: Error? { + guard case let .doNotRetryWithError(error) = self else { return nil } + return error + } +} + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - Parameters: + /// - request: `Request` that failed due to the provided `Error`. + /// - session: `Session` that produced the `Request`. + /// - error: `Error` encountered while executing the `Request`. + /// - completion: Completion closure to be executed when a retry decision has been determined. + func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) +} + +// MARK: - + +/// Type that provides both `RequestAdapter` and `RequestRetrier` functionality. +public protocol RequestInterceptor: RequestAdapter, RequestRetrier {} + +extension RequestInterceptor { + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + completion(.success(urlRequest)) + } + + public func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + completion(.doNotRetry) + } +} + +/// `RequestAdapter` closure definition. +public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result) -> Void) -> Void +/// `RequestRetrier` closure definition. +public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void + +// MARK: - + +/// Closure-based `RequestAdapter`. +open class Adapter: RequestInterceptor { + private let adaptHandler: AdaptHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation. + public init(_ adaptHandler: @escaping AdaptHandler) { + self.adaptHandler = adaptHandler + } + + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + adaptHandler(urlRequest, session, completion) + } +} + +// MARK: - + +/// Closure-based `RequestRetrier`. +open class Retrier: RequestInterceptor { + private let retryHandler: RetryHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry. + public init(_ retryHandler: @escaping RetryHandler) { + self.retryHandler = retryHandler + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + retryHandler(request, session, error, completion) + } +} + +// MARK: - + +/// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values. +open class Interceptor: RequestInterceptor { + /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails. + public let adapters: [RequestAdapter] + /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry. + public let retriers: [RequestRetrier] + + /// Creates an instance from `AdaptHandler` and `RetryHandler` closures. + /// + /// - Parameters: + /// - adaptHandler: `AdaptHandler` closure to be used. + /// - retryHandler: `RetryHandler` closure to be used. + public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) { + adapters = [Adapter(adaptHandler)] + retriers = [Retrier(retryHandler)] + } + + /// Creates an instance from `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapter: `RequestAdapter` value to be used. + /// - retrier: `RequestRetrier` value to be used. + public init(adapter: RequestAdapter, retrier: RequestRetrier) { + adapters = [adapter] + retriers = [retrier] + } + + /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapters: `RequestAdapter` values to be used. + /// - retriers: `RequestRetrier` values to be used. + public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = []) { + self.adapters = adapters + self.retriers = retriers + } + + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + adapt(urlRequest, for: session, using: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + for session: Session, + using adapters: [RequestAdapter], + completion: @escaping (Result) -> Void) { + var pendingAdapters = adapters + + guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } + + let adapter = pendingAdapters.removeFirst() + + adapter.adapt(urlRequest, for: session) { result in + switch result { + case let .success(urlRequest): + self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion) + case .failure: + completion(result) + } + } + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + retry(request, for: session, dueTo: error, using: retriers, completion: completion) + } + + private func retry(_ request: Request, + for session: Session, + dueTo error: Error, + using retriers: [RequestRetrier], + completion: @escaping (RetryResult) -> Void) { + var pendingRetriers = retriers + + guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return } + + let retrier = pendingRetriers.removeFirst() + + retrier.retry(request, for: session, dueTo: error) { result in + switch result { + case .retry, .retryWithDelay, .doNotRetryWithError: + completion(result) + case .doNotRetry: + // Only continue to the next retrier if retry was not triggered and no error was encountered + self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion) + } + } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/RequestTaskMap.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/RequestTaskMap.swift new file mode 100644 index 0000000..8d4f33d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/RequestTaskMap.swift @@ -0,0 +1,136 @@ +// +// RequestTaskMap.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that maintains a two way, one to one map of `URLSessionTask`s to `Request`s. +struct RequestTaskMap { + private var tasksToRequests: [URLSessionTask: Request] + private var requestsToTasks: [Request: URLSessionTask] + private var taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] + + var requests: [Request] { + return Array(tasksToRequests.values) + } + + init(tasksToRequests: [URLSessionTask: Request] = [:], + requestsToTasks: [Request: URLSessionTask] = [:], + taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:]) { + self.tasksToRequests = tasksToRequests + self.requestsToTasks = requestsToTasks + self.taskEvents = taskEvents + } + + subscript(_ request: Request) -> URLSessionTask? { + get { return requestsToTasks[request] } + set { + guard let newValue = newValue else { + guard let task = requestsToTasks[request] else { + fatalError("RequestTaskMap consistency error: no task corresponding to request found.") + } + + requestsToTasks.removeValue(forKey: request) + tasksToRequests.removeValue(forKey: task) + taskEvents.removeValue(forKey: task) + + return + } + + requestsToTasks[request] = newValue + tasksToRequests[newValue] = request + taskEvents[newValue] = (completed: false, metricsGathered: false) + } + } + + subscript(_ task: URLSessionTask) -> Request? { + get { return tasksToRequests[task] } + set { + guard let newValue = newValue else { + guard let request = tasksToRequests[task] else { + fatalError("RequestTaskMap consistency error: no request corresponding to task found.") + } + + tasksToRequests.removeValue(forKey: task) + requestsToTasks.removeValue(forKey: request) + taskEvents.removeValue(forKey: task) + + return + } + + tasksToRequests[task] = newValue + requestsToTasks[newValue] = task + taskEvents[task] = (completed: false, metricsGathered: false) + } + } + + var count: Int { + precondition(tasksToRequests.count == requestsToTasks.count, + "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)") + + return tasksToRequests.count + } + + var eventCount: Int { + precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)") + + return taskEvents.count + } + + var isEmpty: Bool { + precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty, + "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)") + + return tasksToRequests.isEmpty + } + + var isEventsEmpty: Bool { + precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)") + + return taskEvents.isEmpty + } + + mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.") + case (false, false): taskEvents[task] = (completed: false, metricsGathered: true) + case (true, false): self[task] = nil + } + } + + mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.") + case (false, false): taskEvents[task] = (completed: true, metricsGathered: false) + case (false, true): self[task] = nil + } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/Response.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..5874b28 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,399 @@ +// +// Response.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDataResponse = DataResponse +/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDownloadResponse = DownloadResponse + +/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The final metrics of the response. + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { return result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { return result.failure } + + /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - data: The `Data` returned by the server. + /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.data = data + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return "\(result)" + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data, the duration of the network and serialization actions, and the response serialization + /// result. + public var debugDescription: String { + let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil" + let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None" + let responseDescription = response.map { response in + let sortedHeaders = response.headers.sorted() + + return """ + [Status Code]: \(response.statusCode) + [Headers]: + \(sortedHeaders) + """ + } ?? "nil" + let responseBody = data.map { String(decoding: $0, as: UTF8.self) } ?? "None" + let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + + return """ + [Request]: \(requestDescription) + [Request Body]: \n\(requestBody) + [Response]: \n\(responseDescription) + [Response Body]: \n\(responseBody) + [Data]: \(data?.description ?? "None") + [Network Duration]: \(metricsDescription) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Success) -> NewSuccess) -> DataResponse { + return DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DataResponse { + return DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func mapError(_ transform: (Failure) -> NewFailure) -> DataResponse { + return DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DataResponse { + return DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The final destination URL of the data returned from the server after it is moved. + public let fileURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The final metrics of the response. + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { return result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { return result.failure } + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - 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. + /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + fileURL: URL?, + resumeData: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.fileURL = fileURL + self.resumeData = resumeData + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return "\(result)" + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization + /// actions, and the response serialization result. + public var debugDescription: String { + let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil" + let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None" + let responseDescription = response.map { response in + let sortedHeaders = response.headers.sorted() + + return """ + [Status Code]: \(response.statusCode) + [Headers]: + \(sortedHeaders) + """ + } ?? "nil" + let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + let resumeDataDescription = resumeData.map { "\($0)" } ?? "None" + + return """ + [Request]: \(requestDescription) + [Request Body]: \n\(requestBody) + [Response]: \n\(responseDescription) + [File URL]: \(fileURL?.path ?? "nil") + [ResumeData]: \(resumeDataDescription) + [Network Duration]: \(metricsDescription) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Success) -> NewSuccess) -> DownloadResponse { + return DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse { + return DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func mapError(_ transform: (Failure) -> NewFailure) -> DownloadResponse { + return DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse { + return DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/ResponseSerialization.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..61b2cd5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,800 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +// MARK: Protocols + +/// The type to which all data response serializers must conform in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created. + associatedtype SerializedObject + + /// Serialize the response `Data` into the provided type.. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - data: `Data` returned from the server, if any. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject +} + +/// The type to which all download response serializers must conform in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created. + associatedtype SerializedObject + + /// Serialize the downloaded response `Data` from disk into the provided type.. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - fileURL: File `URL` to which the response data was downloaded. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject +} + +/// A serializer that can handle both data and download responses. +public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { + /// `DataPreprocessor` used to prepare incoming `Data` for serialization. + var dataPreprocessor: DataPreprocessor { get } + /// `HTTPMethod`s for which empty response bodies are considered appropriate. + var emptyRequestMethods: Set { get } + /// HTTP response codes for which empty response bodies are considered appropriate. + var emptyResponseCodes: Set { get } +} + +/// Type used to preprocess `Data` before it handled by a serializer. +public protocol DataPreprocessor { + /// Process `Data` before it's handled by a serializer. + /// - Parameter data: The raw `Data` to process. + func preprocess(_ data: Data) throws -> Data +} + +/// `DataPreprocessor` that returns passed `Data` without any transform. +public struct PassthroughPreprocessor: DataPreprocessor { + public init() {} + + public func preprocess(_ data: Data) throws -> Data { return data } +} + +/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header. +public struct GoogleXSSIPreprocessor: DataPreprocessor { + public init() {} + + public func preprocess(_ data: Data) throws -> Data { + return (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data + } +} + +extension ResponseSerializer { + /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default. + public static var defaultDataPreprocessor: DataPreprocessor { return PassthroughPreprocessor() } + /// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default. + public static var defaultEmptyRequestMethods: Set { return [.head] } + /// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default. + public static var defaultEmptyResponseCodes: Set { return [204, 205] } + + public var dataPreprocessor: DataPreprocessor { return Self.defaultDataPreprocessor } + public var emptyRequestMethods: Set { return Self.defaultEmptyRequestMethods } + public var emptyResponseCodes: Set { return Self.defaultEmptyResponseCodes } + + /// Determines whether the `request` allows empty response bodies, if `request` exists. + /// + /// - Parameter request: `URLRequest` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`. + public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? { + return request.flatMap { $0.httpMethod } + .flatMap(HTTPMethod.init) + .map { emptyRequestMethods.contains($0) } + } + + /// Determines whether the `response` allows empty response bodies, if `response` exists`. + /// + /// - Parameter response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`. + public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? { + return response.flatMap { $0.statusCode } + .map { emptyResponseCodes.contains($0) } + } + + /// Determines whether `request` and `response` allow empty response bodies. + /// + /// - Parameters: + /// - request: `URLRequest` to evaluate. + /// - response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise. + public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool { + return (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true) + } +} + +/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds +/// the data read from disk into the data response serializer. +public extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol { + func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject { + guard error == nil else { throw error! } + + guard let fileURL = fileURL else { + throw AFError.responseSerializationFailed(reason: .inputFileNil) + } + + let data: Data + do { + data = try Data(contentsOf: fileURL) + } catch { + throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)) + } + + do { + return try serialize(request: request, response: response, data: data, error: error) + } catch { + throw error + } + } +} + +// MARK: - Default + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.data, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = CFAbsoluteTimeGetCurrent() + let result: AFResult = Result { + try responseSerializer.serialize(request: self.request, + response: self.response, + data: self.data, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + + let end = CFAbsoluteTimeGetCurrent() + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (() -> Void)? + + defer { + if let didComplete = didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.fileURL, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data + /// contained in the destination `URL`. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = CFAbsoluteTimeGetCurrent() + let result: AFResult = Result { + try responseSerializer.serializeDownload(request: self.request, + response: self.response, + fileURL: self.fileURL, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + let end = CFAbsoluteTimeGetCurrent() + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (() -> Void)? + + defer { + if let didComplete = didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } +} + +// MARK: - Data + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseData(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + return response(queue: queue, + responseSerializer: DataResponseSerializer(), + completionHandler: completionHandler) + } +} + +/// A `ResponseSerializer` that performs minimal response checking and returns any response data as-is. By default, a +/// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for +/// empty responses (`204`, `205`), then an empty `Data` value is returned. +public final class DataResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance using the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return Data() + } + + data = try dataPreprocessor.preprocess(data) + + return data + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseData(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + return response(queue: queue, + responseSerializer: DataResponseSerializer(), + completionHandler: completionHandler) + } +} + +// MARK: - String + +/// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no +/// data is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`), +/// then an empty `String` is returned. +public final class StringResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + /// Optional string encoding used to validate the response. + public let encoding: String.Encoding? + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.encoding = encoding + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return "" + } + + data = try dataPreprocessor.preprocess(data) + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil { + let ianaCharSet = CFStringConvertIANACharSetNameToEncoding(encodingName) + let nsStringEncoding = CFStringConvertEncodingToNSStringEncoding(ianaCharSet) + convertedEncoding = String.Encoding(rawValue: nsStringEncoding) + } + + let actualEncoding = convertedEncoding ?? .isoLatin1 + + guard let string = String(data: data, encoding: actualEncoding) else { + throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)) + } + + return string + } +} + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from + /// the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseString(queue: DispatchQueue = .main, + encoding: String.Encoding? = nil, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + return response(queue: queue, + responseSerializer: StringResponseSerializer(encoding: encoding), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined from + /// the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseString(queue: DispatchQueue = .main, + encoding: String.Encoding? = nil, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + return response(queue: queue, + responseSerializer: StringResponseSerializer(encoding: encoding), + completionHandler: completionHandler) + } +} + +// MARK: - JSON + +/// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning +/// `nil` or no data is considered an error. However, if the response is has a status code valid for empty responses +/// (`204`, `205`), then an `NSNull` value is returned. +public final class JSONResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + /// `JSONSerialization.ReadingOptions` used when serializing a response. + public let options: JSONSerialization.ReadingOptions + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// - options: The options to use. `.allowFragments` by default. + public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + self.options = options + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return NSNull() + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try JSONSerialization.jsonObject(with: data, options: options) + } catch { + throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)) + } + } +} + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - options: The JSON serialization reading options. `.allowFragments` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + return response(queue: queue, + responseSerializer: JSONResponseSerializer(options: options), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - options: The JSON serialization reading options. `.allowFragments` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + return response(queue: queue, + responseSerializer: JSONResponseSerializer(options: options), + completionHandler: completionHandler) + } +} + +// MARK: - Empty + +/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance. +public protocol EmptyResponse { + /// Empty value for the conforming type. + /// + /// - Returns: Value of `Self` to use for empty values. + static func emptyValue() -> Self +} + +/// Type representing an empty response. Use `Empty.value` to get the static instance. +public struct Empty: Decodable { + /// Static `Empty` instance used for all `Empty` responses. + public static let value = Empty() +} + +extension Empty: EmptyResponse { + public static func emptyValue() -> Empty { + return value + } +} + +// MARK: - DataDecoder Protocol + +/// Any type which can decode `Data` into a `Decodable` type. +public protocol DataDecoder { + /// Decode `Data` into the provided type. + /// + /// - Parameters: + /// - type: The `Type` to be decoded. + /// - data: The `Data` to be decoded. + /// + /// - Returns: The decoded value of type `D`. + /// - Throws: Any error that occurs during decode. + func decode(_ type: D.Type, from data: Data) throws -> D +} + +/// `JSONDecoder` automatically conforms to `DataDecoder`. +extension JSONDecoder: DataDecoder {} + +// MARK: - Decodable + +/// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to +/// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data +/// is considered an error. However, if the response is has a status code valid for empty responses (`204`, `205`), then +/// the `Empty.value` value is returned. +public final class DecodableResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + /// The `DataDecoder` instance used to decode responses. + public let decoder: DataDecoder + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance using the values provided. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.decoder = decoder + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T { + guard error == nil else { throw error! } + + guard var data = data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else { + throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)")) + } + + return emptyValue + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try decoder.decode(T.self, from: data) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) + } + } +} + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + decoder: DataDecoder = JSONDecoder(), + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + return response(queue: queue, + responseSerializer: DecodableResponseSerializer(decoder: decoder), + completionHandler: completionHandler) + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + decoder: DataDecoder = JSONDecoder(), + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + return response(queue: queue, + responseSerializer: DecodableResponseSerializer(decoder: decoder), + completionHandler: completionHandler) + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/Result+Alamofire.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/Result+Alamofire.swift new file mode 100644 index 0000000..60b35f8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/Result+Alamofire.swift @@ -0,0 +1,109 @@ +// +// Result+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Default type of `Result` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFResult = Result + +// MARK: - Internal APIs + +extension Result { + /// Returns the associated value if the result is a success, `nil` otherwise. + var success: Success? { + guard case let .success(value) = self else { return nil } + return value + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + var failure: Failure? { + guard case let .failure(error) = self else { return nil } + return error + } + + /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise. + /// + /// - Parameters: + /// - value: A value. + /// - error: An `Error`. + init(value: Success, error: Failure?) { + if let error = error { + self = .failure(error) + } else { + self = .success(value) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + func tryMap(_ transform: (Success) throws -> NewSuccess) -> Result { + switch self { + case let .success(value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case let .failure(error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same success. + func tryMapError(_ transform: (Failure) throws -> NewFailure) -> Result { + switch self { + case let .failure(error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case let .success(value): + return .success(value) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/RetryPolicy.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/RetryPolicy.swift new file mode 100644 index 0000000..7400718 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/RetryPolicy.swift @@ -0,0 +1,363 @@ +// +// RetryPolicy.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes +/// as well as certain types of networking errors. +open class RetryPolicy: RequestInterceptor { + /// The default retry limit for retry policies. + public static let defaultRetryLimit: UInt = 2 + + /// The default exponential backoff base for retry policies (must be a minimum of 2). + public static let defaultExponentialBackoffBase: UInt = 2 + + /// The default exponential backoff scale for retry policies. + public static let defaultExponentialBackoffScale: Double = 0.5 + + /// The default HTTP methods to retry. + /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information. + public static let defaultRetryableHTTPMethods: Set = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent + .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent + .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent + .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent + .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent + .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent + ] + + /// The default HTTP status codes to retry. + /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information. + public static let defaultRetryableHTTPStatusCodes: Set = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9) + 500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1) + 502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3) + 503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4) + 504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5) + ] + + /// The default URL error codes to retry. + public static let defaultRetryableURLErrorCodes: Set = [// [Security] App Transport Security disallowed a connection because there is no secure network connection. + // - [Disabled] ATS settings do not change at runtime. + // .appTransportSecurityRequiresSecureConnection, + + // [System] An app or app extension attempted to connect to a background session that is already connected to a + // process. + // - [Enabled] The other process could release the background session. + .backgroundSessionInUseByAnotherProcess, + + // [System] The shared container identifier of the URL session configuration is needed but has not been set. + // - [Disabled] Cannot change at runtime. + // .backgroundSessionRequiresSharedContainer, + + // [System] The app is suspended or exits while a background data task is processing. + // - [Enabled] App can be foregrounded or launched to recover. + .backgroundSessionWasDisconnected, + + // [Network] The URL Loading system received bad data from the server. + // - [Enabled] Server could return valid data when retrying. + .badServerResponse, + + // [Resource] A malformed URL prevented a URL request from being initiated. + // - [Disabled] URL was most likely constructed incorrectly. + // .badURL, + + // [System] A connection was attempted while a phone call is active on a network that does not support + // simultaneous phone and data communication (EDGE or GPRS). + // - [Enabled] Phone call could be ended to allow request to recover. + .callIsActive, + + // [Client] An asynchronous load has been canceled. + // - [Disabled] Request was cancelled by the client. + // .cancelled, + + // [File System] A download task couldn’t close the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCloseFile, + + // [Network] An attempt to connect to a host failed. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotConnectToHost, + + // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCreateFile, + + // [Data] Content data received during a connection request had an unknown content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeContentData, + + // [Data] Content data received during a connection request could not be decoded for a known content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeRawData, + + // [Network] The host name for a URL could not be resolved. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotFindHost, + + // [Network] A request to load an item only from the cache could not be satisfied. + // - [Enabled] Cache could be populated during a retry. + .cannotLoadFromNetwork, + + // [File System] A download task was unable to move a downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotMoveFile, + + // [File System] A download task was unable to open the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotOpenFile, + + // [Data] A task could not parse a response. + // - [Disabled] Invalid response is unlikely to recover with retry. + // .cannotParseResponse, + + // [File System] A download task was unable to remove a downloaded file from disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotRemoveFile, + + // [File System] A download task was unable to write to the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotWriteToFile, + + // [Security] A client certificate was rejected. + // - [Disabled] Client certificate is unlikely to change with retry. + // .clientCertificateRejected, + + // [Security] A client certificate was required to authenticate an SSL connection during a request. + // - [Disabled] Client certificate is unlikely to be provided with retry. + // .clientCertificateRequired, + + // [Data] The length of the resource data exceeds the maximum allowed. + // - [Disabled] Resource will likely still exceed the length maximum on retry. + // .dataLengthExceedsMaximum, + + // [System] The cellular network disallowed a connection. + // - [Enabled] WiFi connection could be established during retry. + .dataNotAllowed, + + // [Network] The host address could not be found via DNS lookup. + // - [Enabled] DNS lookup could succeed during retry. + .dnsLookupFailed, + + // [Data] A download task failed to decode an encoded file during the download. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedMidStream, + + // [Data] A download task failed to decode an encoded file after downloading. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedToComplete, + + // [File System] A file does not exist. + // - [Disabled] File system error is unlikely to recover with retry. + // .fileDoesNotExist, + + // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file, + // but a directory. + // - [Disabled] FTP directory is not likely to change to a file during a retry. + // .fileIsDirectory, + + // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been + // exceeded (currently 16). + // - [Disabled] The redirect loop is unlikely to be resolved within the retry window. + // .httpTooManyRedirects, + + // [System] The attempted connection required activating a data context while roaming, but international roaming + // is disabled. + // - [Enabled] WiFi connection could be established during retry. + .internationalRoamingOff, + + // [Connectivity] A client or server connection was severed in the middle of an in-progress load. + // - [Enabled] A network connection could be established during retry. + .networkConnectionLost, + + // [File System] A resource couldn’t be read because of insufficient permissions. + // - [Disabled] Permissions are unlikely to be granted during retry. + // .noPermissionsToReadFile, + + // [Connectivity] A network resource was requested, but an internet connection has not been established and + // cannot be established automatically. + // - [Enabled] A network connection could be established during retry. + .notConnectedToInternet, + + // [Resource] A redirect was specified by way of server response code, but the server did not accompany this + // code with a redirect URL. + // - [Disabled] The redirect URL is unlikely to be supplied during a retry. + // .redirectToNonExistentLocation, + + // [Client] A body stream is needed but the client did not provide one. + // - [Disabled] The client will be unlikely to supply a body stream during retry. + // .requestBodyStreamExhausted, + + // [Resource] A requested resource couldn’t be retrieved. + // - [Disabled] The resource is unlikely to become available during the retry window. + // .resourceUnavailable, + + // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more + // specifically. + // - [Enabled] The secure connection could be established during a retry given the lack of specificity + // provided by the error. + .secureConnectionFailed, + + // [Security] A server certificate had a date which indicates it has expired, or is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateHasBadDate, + + // [Security] A server certificate was not signed by any root server. + // - [Disabled] The server certificate is unlikely to change during the retry window. + // .serverCertificateHasUnknownRoot, + + // [Security] A server certificate is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateNotYetValid, + + // [Security] A server certificate was signed by a root server that isn’t trusted. + // - [Disabled] The server certificate is unlikely to become trusted within the retry window. + // .serverCertificateUntrusted, + + // [Network] An asynchronous operation timed out. + // - [Enabled] The request timed out for an unknown reason and should be retried. + .timedOut + + // [System] The URL Loading System encountered an error that it can’t interpret. + // - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry. + // .unknown, + + // [Resource] A properly formed URL couldn’t be handled by the framework. + // - [Disabled] The URL is unlikely to change during a retry. + // .unsupportedURL, + + // [Client] Authentication is required to access a resource. + // - [Disabled] The user authentication is unlikely to be provided by retrying. + // .userAuthenticationRequired, + + // [Client] An asynchronous request for authentication has been canceled by the user. + // - [Disabled] The user cancelled authentication and explicitly took action to not retry. + // .userCancelledAuthentication, + + // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection + // gracefully without sending any data. + // - [Disabled] The server is unlikely to provide data during the retry window. + // .zeroByteResource, + ] + + /// The total number of times the request is allowed to be retried. + public let retryLimit: UInt + + /// The base of the exponential backoff policy (should always be greater than or equal to 2). + public let exponentialBackoffBase: UInt + + /// The scale of the exponential backoff. + public let exponentialBackoffScale: Double + + /// The HTTP methods that are allowed to be retried. + public let retryableHTTPMethods: Set + + /// The HTTP status codes that are automatically retried by the policy. + public let retryableHTTPStatusCodes: Set + + /// The URL error codes that are automatically retried by the policy. + public let retryableURLErrorCodes: Set + + /// Creates an `ExponentialBackoffRetryPolicy` from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. + /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. + /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) { + precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.") + + self.retryLimit = retryLimit + self.exponentialBackoffBase = exponentialBackoffBase + self.exponentialBackoffScale = exponentialBackoffScale + self.retryableHTTPMethods = retryableHTTPMethods + self.retryableHTTPStatusCodes = retryableHTTPStatusCodes + self.retryableURLErrorCodes = retryableURLErrorCodes + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + if + request.retryCount < retryLimit, + let httpMethod = request.request?.method, + retryableHTTPMethods.contains(httpMethod), + shouldRetry(response: request.response, error: error) { + let timeDelay = pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale + completion(.retryWithDelay(timeDelay)) + } else { + completion(.doNotRetry) + } + } + + private func shouldRetry(response: HTTPURLResponse?, error: Error) -> Bool { + if let statusCode = response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) { + return true + } else if let errorCode = (error as? URLError)?.code, retryableURLErrorCodes.contains(errorCode) { + return true + } + + return false + } +} + +// MARK: - + +/// A retry policy that automatically retries idempotent requests for network connection lost errors. For more +/// information about retrying network connection lost errors, please refer to Apple's +/// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html). +open class ConnectionLostRetryPolicy: RetryPolicy { + /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. + /// `RetryPolicy.defaultRetryLimit` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. + /// `RetryPolicy.defaultExponentialBackoffBase` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. + /// `RetryPolicy.defaultExponentialBackoffScale` by default. + /// - retryableHTTPMethods: The idempotent http methods to retry. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) { + super.init(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: [], + retryableURLErrorCodes: [.networkConnectionLost]) + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/ServerTrustEvaluation.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/ServerTrustEvaluation.swift new file mode 100644 index 0000000..e2a4d47 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/ServerTrustEvaluation.swift @@ -0,0 +1,606 @@ +// +// ServerTrustPolicy.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts. +open class ServerTrustManager { + /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default. + public let allHostsMustBeEvaluated: Bool + + /// The dictionary of policies mapped to a particular host. + public let evaluators: [String: ServerTrustEvaluating] + + /// Initializes the `ServerTrustManager` instance with the given evaluators. + /// + /// Since different servers and web services can have different leaf certificates, intermediate and even root + /// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + /// pinning for host3 and disabling evaluation for host4. + /// + /// - Parameters: + /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true` + /// by default. + /// - evaluators: A dictionary of evaluators mapped to hosts. + public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) { + self.allHostsMustBeEvaluated = allHostsMustBeEvaluated + self.evaluators = evaluators + } + + /// Returns the `ServerTrustEvaluating` value for the given host, if one is set. + /// + /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override + /// this method and implement more complex mapping implementations such as wildcards. + /// + /// - Parameter host: The host to use when searching for a matching policy. + /// + /// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise. + /// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching + /// evaluators are found. + open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? { + guard let evaluator = evaluators[host] else { + if allHostsMustBeEvaluated { + throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host)) + } + + return nil + } + + return evaluator + } +} + +/// A protocol describing the API used to evaluate server trusts. +public protocol ServerTrustEvaluating { +#if os(Linux) +// Implement this once Linux has API for evaluating server trusts. +#else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`. + func evaluate(_ trust: SecTrust, forHost host: String) throws +#endif +} + +// MARK: - Server Trust Evaluators + +/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the +/// host provided by the challenge. Applications are encouraged to always validate the host in production environments +/// to guarantee the validity of the server's certificate chain. +public final class DefaultTrustEvaluator: ServerTrustEvaluating { + private let validateHost: Bool + + /// Creates a `DefaultTrustEvaluator`. + /// + /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default. + public init(validateHost: Bool = true) { + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if validateHost { + try trust.af.performValidation(forHost: host) + } + + try trust.af.performDefaultValidation(forHost: host) + } +} + +/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate +/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. +/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS +/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production +/// environments to guarantee the validity of the server's certificate chain. +public final class RevocationTrustEvaluator: ServerTrustEvaluating { + /// Represents the options to be use when evaluating the status of a certificate. + /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants). + public struct Options: OptionSet { + /// Perform revocation checking using the CRL (Certification Revocation List) method. + public static let crl = Options(rawValue: kSecRevocationCRLMethod) + /// Consult only locally cached replies; do not use network access. + public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled) + /// Perform revocation checking using OCSP (Online Certificate Status Protocol). + public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod) + /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred. + public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL) + /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a + /// "best attempt" basis, where failure to reach the server is not considered fatal. + public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse) + /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the + /// certificate and the value of `preferCRL`. + public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod) + + /// The raw value of the option. + public let rawValue: CFOptionFlags + + /// Creates an `Options` value with the given `CFOptionFlags`. + /// + /// - Parameter rawValue: The `CFOptionFlags` value to initialize with. + public init(rawValue: CFOptionFlags) { + self.rawValue = rawValue + } + } + + private let performDefaultValidation: Bool + private let validateHost: Bool + private let options: Options + + /// Creates a `RevocationTrustEvaluator`. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + /// - options: The `Options` to use to check the revocation status of the certificate. `.any` + /// by default. + public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) { + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + self.options = options + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { + try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) + } else { + try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) + } + } + } +} + +/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned +/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate +/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate chain in production +/// environments. +public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating { + private let certificates: [SecCertificate] + private let acceptSelfSignedCertificates: Bool + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PinnedCertificatesTrustEvaluator`. + /// + /// - Parameters: + /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing + /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE + /// FALSE IN PRODUCTION! + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + public init(certificates: [SecCertificate] = Bundle.main.af.certificates, + acceptSelfSignedCertificates: Bool = false, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.certificates = certificates + self.acceptSelfSignedCertificates = acceptSelfSignedCertificates + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !certificates.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) + } + + if acceptSelfSignedCertificates { + try trust.af.setAnchorCertificates(certificates) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let serverCertificatesData = Set(trust.af.certificateData) + let pinnedCertificatesData = Set(certificates.af.data) + let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData) + if !pinnedCertificatesInServerData { + throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host, + trust: trust, + pinnedCertificates: certificates, + serverCertificates: trust.af.certificates)) + } + } +} + +/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned +/// public keys match one of the server certificate public keys. By validating both the certificate chain and host, +/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate chain in production +/// environments. +public final class PublicKeysTrustEvaluator: ServerTrustEvaluating { + private let keys: [SecKey] + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PublicKeysTrustEvaluator`. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all + /// certificates included in the main bundle. + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + public init(keys: [SecKey] = Bundle.main.af.publicKeys, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.keys = keys + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !keys.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let pinnedKeysInServerKeys: Bool = { + for serverPublicKey in trust.af.publicKeys { + for pinnedPublicKey in keys { + if serverPublicKey == pinnedPublicKey { + return true + } + } + } + return false + }() + + if !pinnedKeysInServerKeys { + throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host, + trust: trust, + pinnedKeys: keys, + serverKeys: trust.af.publicKeys)) + } + } +} + +/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the +/// evaluators consider it valid. +public final class CompositeTrustEvaluator: ServerTrustEvaluating { + private let evaluators: [ServerTrustEvaluating] + + /// Creates a `CompositeTrustEvaluator`. + /// + /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. + public init(evaluators: [ServerTrustEvaluating]) { + self.evaluators = evaluators + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + try evaluators.evaluate(trust, forHost: host) + } +} + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +public final class DisabledEvaluator: ServerTrustEvaluating { + /// Creates an instance. + public init() {} + + public func evaluate(_ trust: SecTrust, forHost host: String) throws {} +} + +// MARK: - Extensions + +public extension Array where Element == ServerTrustEvaluating { +#if os(Linux) +// Add this same convenience method for Linux. +#else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`. + func evaluate(_ trust: SecTrust, forHost host: String) throws { + for evaluator in self { + try evaluator.evaluate(trust, forHost: host) + } + } +#endif +} + +extension Bundle: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType: Bundle { + /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle. + var certificates: [SecCertificate] { + return paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in + guard + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil } + + return certificate + } + } + + /// Returns all public keys for the valid certificates in the bundle. + var publicKeys: [SecKey] { + return certificates.af.publicKeys + } + + /// Returns all pathnames for the resources identified by the provided file extensions. + /// + /// - Parameter types: The filename extensions locate. + /// + /// - Returns: All pathnames for the given filename extensions. + func paths(forResourcesOfTypes types: [String]) -> [String] { + return Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) })) + } +} + +extension SecTrust: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType == SecTrust { + /// Evaluates `self` after applying the `SecPolicy` value provided. + /// + /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation. + /// + /// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + func evaluate(afterApplying policy: SecPolicy) throws { + try apply(policy: policy).af.evaluate() + } + + /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed. + /// + /// - Parameters: + /// - policy: The `SecPolicy` used to evaluate `self`. + /// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`. + /// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)") + func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { + try apply(policy: policy).af.validate(errorProducer: errorProducer) + } + + /// Applies a `SecPolicy` to `self`, throwing if it fails. + /// + /// - Parameter policy: The `SecPolicy`. + /// + /// - Returns: `self`, with the policy applied. + /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason. + func apply(policy: SecPolicy) throws -> SecTrust { + let status = SecTrustSetPolicies(type, policy) + + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type, + policy: policy, + status: status)) + } + + return type + } + + /// Evaluate `self`, throwing an `Error` if evaluation fails. + /// + /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from + /// the underlying evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + func evaluate() throws { + var error: CFError? + let evaluationSucceeded = SecTrustEvaluateWithError(type, &error) + + if !evaluationSucceeded { + throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error)) + } + } + + /// Validate `self`, passing any failure values through `errorProducer`. + /// + /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an + /// `Error`. + /// - Throws: The `Error` produced by the `errorProducer` closure. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()") + func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(type, &result) + + guard status.af.isSuccess && result.af.isSuccess else { + throw errorProducer(status, result) + } + } + + /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain. + /// + /// - Parameter certificates: The `SecCertificate`s to add to the chain. + /// - Throws: Any error produced when applying the new certificate chain. + func setAnchorCertificates(_ certificates: [SecCertificate]) throws { + // Add additional anchor certificates. + let status = SecTrustSetAnchorCertificates(type, certificates as CFArray) + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status, + certificates: certificates)) + } + + // Reenable system anchor certificates. + let systemStatus = SecTrustSetAnchorCertificatesOnly(type, true) + guard systemStatus.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: systemStatus, + certificates: certificates)) + } + } + + /// The public keys contained in `self`. + var publicKeys: [SecKey] { + return certificates.af.publicKeys + } + + /// The `SecCertificate`s contained i `self`. + var certificates: [SecCertificate] { + return (0.. SecPolicy { + return SecPolicyCreateSSL(true, hostname as CFString) + } + + /// Creates a `SecPolicy` which checks the revocation of certificates. + /// + /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation. + /// + /// - Returns: The `SecPolicy`. + /// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed` + /// if the policy cannot be created. + static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy { + guard let policy = SecPolicyCreateRevocation(options.rawValue) else { + throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed) + } + + return policy + } +} + +extension Array: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType == [SecCertificate] { + /// All `Data` values for the contained `SecCertificate`s. + var data: [Data] { + return type.map { SecCertificateCopyData($0) as Data } + } + + /// All public `SecKey` values for the contained `SecCertificate`s. + var publicKeys: [SecKey] { + return type.compactMap { $0.af.publicKey } + } +} + +extension SecCertificate: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType == SecCertificate { + /// The public key for `self`, if it can be extracted. + var publicKey: SecKey? { + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust) + + guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil } + + return SecTrustCopyPublicKey(createdTrust) + } +} + +extension OSStatus: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType == OSStatus { + /// Returns whether `self` is `errSecSuccess`. + var isSuccess: Bool { return type == errSecSuccess } +} + +extension SecTrustResultType: AlamofireExtended {} +public extension AlamofireExtension where ExtendedType == SecTrustResultType { + /// Returns whether `self is `.unspecified` or `.proceed`. + var isSuccess: Bool { + return (type == .unspecified || type == .proceed) + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/Session.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/Session.swift new file mode 100644 index 0000000..c73cfc1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/Session.swift @@ -0,0 +1,1039 @@ +// +// Session.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common +/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response +/// cache handling. +open class Session { + /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified. + public static let `default` = Session() + + /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's + /// `delegate` handles `URLSessionDelegate` callbacks. + public let session: URLSession + /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction. + public let delegate: SessionDelegate + /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue. + public let rootQueue: DispatchQueue + /// Value determining whether this instance automatically calls `resume()` on all created `Request`s. + public let startRequestsImmediately: Bool + /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its + /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile + /// and test before introducing an additional queue. + public let requestQueue: DispatchQueue + /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this + /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined + /// to be a bottleneck. Always profile and test before introducing an additional queue. + public let serializationQueue: DispatchQueue + /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a + /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value. + public let interceptor: RequestInterceptor? + /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning. + public let serverTrustManager: ServerTrustManager? + /// `RedirectHandler` instance used to provide customization for request redirection. + public let redirectHandler: RedirectHandler? + /// `CachedResponseHandler` instance used to provide customization of cached response handling. + public let cachedResponseHandler: CachedResponseHandler? + /// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s. + public let eventMonitor: CompositeEventMonitor + /// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default. + public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()] + + /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them. + var requestTaskMap = RequestTaskMap() + /// Set of currently active `Request`s. + var activeRequests: Set = [] + + /// Creates a `Session` from a `URLSession` and other parameters. + /// + /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and + /// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer. + /// + /// - Parameters: + /// - session: Underlying `URLSession` for this instance. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a + /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. + public init(session: URLSession, + delegate: SessionDelegate, + rootQueue: DispatchQueue, + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: RequestInterceptor? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: RedirectHandler? = nil, + cachedResponseHandler: CachedResponseHandler? = nil, + eventMonitors: [EventMonitor] = []) { + precondition(session.configuration.identifier == nil, + "Alamofire does not support background URLSessionConfigurations.") + precondition(session.delegateQueue.underlyingQueue === rootQueue, + "Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.") + + self.session = session + self.delegate = delegate + self.rootQueue = rootQueue + self.startRequestsImmediately = startRequestsImmediately + self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue) + self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue) + self.interceptor = interceptor + self.serverTrustManager = serverTrustManager + self.redirectHandler = redirectHandler + self.cachedResponseHandler = cachedResponseHandler + eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors) + delegate.eventMonitor = eventMonitor + delegate.stateProvider = self + } + + /// Creates a `Session` from a `URLSessionConfiguration`. + /// + /// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its + /// `delegateQueue`, and is the recommended initializer for most uses. + /// + /// - Parameters: + /// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes + /// to this value after being passed to this initializer will have no effect. + /// `URLSessionConfiguration.af.default` by default. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. `SessionDelegate()` by default. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a + /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. + public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default, + delegate: SessionDelegate = SessionDelegate(), + rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"), + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: RequestInterceptor? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: RedirectHandler? = nil, + cachedResponseHandler: CachedResponseHandler? = nil, + eventMonitors: [EventMonitor] = []) { + precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.") + + let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: rootQueue, name: "org.alamofire.session.sessionDelegateQueue") + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue) + + self.init(session: session, + delegate: delegate, + rootQueue: rootQueue, + startRequestsImmediately: startRequestsImmediately, + requestQueue: requestQueue, + serializationQueue: serializationQueue, + interceptor: interceptor, + serverTrustManager: serverTrustManager, + redirectHandler: redirectHandler, + cachedResponseHandler: cachedResponseHandler, + eventMonitors: eventMonitors) + } + + deinit { + finishRequestsForDeinit() + session.invalidateAndCancel() + } + + // MARK: - Cancellation + + /// Cancel all active `Request`s, optionally calling a completion handler when complete. + /// + /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled + /// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to + /// completion when cancelled. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default. + /// - completion: Closure to be called when all `Request`s have been cancelled. + public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) { + rootQueue.async { + self.activeRequests.forEach { $0.cancel() } + queue.async { completion?() } + } + } + + // MARK: - DataRequest + + struct RequestConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoding: ParameterEncoding + let headers: HTTPHeaders? + + func asURLRequest() throws -> URLRequest { + let request = try URLRequest(url: url, method: method, headers: headers) + return try encoding.encode(request, with: parameters) + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncoding.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) -> DataRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers) + + return request(convertible, interceptor: interceptor) + } + + struct RequestEncodableConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoder: ParameterEncoder + let headers: HTTPHeaders? + + func asURLRequest() throws -> URLRequest { + let request = try URLRequest(url: url, method: method, headers: headers) + + return try parameters.map { try encoder.encode($0, into: request) } ?? request + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncodedFormParameterEncoder.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) -> DataRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers) + + return request(convertible, interceptor: interceptor) + } + + /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { + let request = DataRequest(convertible: convertible, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + // MARK: - DownloadRequest + + /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and + /// `Destination`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. Defaults + /// to `URLEncoding.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and + /// a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. Defaults + /// to `URLEncodedFormParameterEncoder.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .request(convertible), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as + /// well as a `RequestInterceptor`, and a `Destination`. + /// + /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by + /// Alamofire. The file will not be deleted until the system purges the temporary files. + /// + /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), + /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` + /// generation logic where the data is written incorrectly and will always fail to resume the download. For more + /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462). + /// + /// - Parameters: + /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(resumingWith data: Data, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .resumeData(data), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + // MARK: - UploadRequest + + struct ParameterlessRequestConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let headers: HTTPHeaders? + + func asURLRequest() throws -> URLRequest { + return try URLRequest(url: url, method: method, headers: headers) + } + } + + struct Upload: UploadConvertible { + let request: URLRequestConvertible + let uploadable: UploadableConvertible + + func createUploadable() throws -> UploadRequest.Uploadable { + return try uploadable.createUploadable() + } + + func asURLRequest() throws -> URLRequest { + return try request.asURLRequest() + } + } + + // MARK: Data + + /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers) + + return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: File + + /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided + /// components and `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers) + + return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers) + + return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + return upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: MultipartFormData + + /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided + /// `URLRequest` components and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + to url: URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers) + + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: convertible, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible` + /// value, and a `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: request, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components + /// and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + to url: URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers) + + let multipartUpload = MultipartUpload(isInBackgroundSession: session.configuration.identifier != nil, + encodingMemoryThreshold: encodingMemoryThreshold, + request: convertible, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible` + /// value and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let multipartUpload = MultipartUpload(isInBackgroundSession: session.configuration.identifier != nil, + encodingMemoryThreshold: encodingMemoryThreshold, + request: request, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: - Internal API + + // MARK: Uploadable + + func upload(_ uploadable: UploadRequest.Uploadable, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor?, + fileManager: FileManager) -> UploadRequest { + let uploadable = Upload(request: convertible, uploadable: uploadable) + + return upload(uploadable, interceptor: interceptor, fileManager: fileManager) + } + + func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest { + let request = UploadRequest(convertible: upload, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + fileManager: fileManager, + delegate: self) + + perform(request) + + return request + } + + // MARK: Perform + + /// Perform `Request`. + /// + /// - Note: Called during retry. + /// + /// - Parameter request: The `Request` to perform. + func perform(_ request: Request) { + switch request { + case let r as DataRequest: perform(r) + case let r as UploadRequest: perform(r) + case let r as DownloadRequest: perform(r) + default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") + } + } + + func perform(_ request: DataRequest) { + requestQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + self.performSetupOperations(for: request, convertible: request.convertible) + } + } + + func perform(_ request: UploadRequest) { + requestQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + do { + let uploadable = try request.upload.createUploadable() + self.rootQueue.async { request.didCreateUploadable(uploadable) } + + self.performSetupOperations(for: request, convertible: request.convertible) + } catch { + self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) } + } + } + } + + func perform(_ request: DownloadRequest) { + requestQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + switch request.downloadable { + case let .request(convertible): + self.performSetupOperations(for: request, convertible: convertible) + case let .resumeData(resumeData): + self.rootQueue.async { self.didReceiveResumeData(resumeData, for: request) } + } + } + } + + func performSetupOperations(for request: Request, convertible: URLRequestConvertible) { + let initialRequest: URLRequest + + do { + initialRequest = try convertible.asURLRequest() + try initialRequest.validate() + } catch { + rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) } + return + } + + rootQueue.async { request.didCreateInitialURLRequest(initialRequest) } + + guard !request.isCancelled else { return } + + guard let adapter = adapter(for: request) else { + rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) } + return + } + + adapter.adapt(initialRequest, for: self) { result in + do { + let adaptedRequest = try result.get() + try adaptedRequest.validate() + + self.rootQueue.async { + request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) + self.didCreateURLRequest(adaptedRequest, for: request) + } + } catch { + self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) } + } + } + } + + // MARK: - Task Handling + + func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) { + request.didCreateURLRequest(urlRequest) + + guard !request.isCancelled else { return } + + let task = request.task(for: urlRequest, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func didReceiveResumeData(_ data: Data, for request: DownloadRequest) { + guard !request.isCancelled else { return } + + let task = request.task(forResumeData: data, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func updateStatesForTask(_ task: URLSessionTask, request: Request) { + request.withState { state in + switch state { + case .initialized, .finished: + // Do nothing. + break + case .resumed: + task.resume() + rootQueue.async { request.didResumeTask(task) } + case .suspended: + task.suspend() + rootQueue.async { request.didSuspendTask(task) } + case .cancelled: + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + rootQueue.async { request.didCancelTask(task) } + } + } + } + + // MARK: - Adapters and Retriers + + func adapter(for request: Request) -> RequestAdapter? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + return Interceptor(adapters: [requestInterceptor, sessionInterceptor]) + } else { + return request.interceptor ?? interceptor + } + } + + func retrier(for request: Request) -> RequestRetrier? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + return Interceptor(retriers: [requestInterceptor, sessionInterceptor]) + } else { + return request.interceptor ?? interceptor + } + } + + // MARK: - Invalidation + + func finishRequestsForDeinit() { + requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionDeinitialized) } + } +} + +// MARK: - RequestDelegate + +extension Session: RequestDelegate { + public var sessionConfiguration: URLSessionConfiguration { + return session.configuration + } + + public var startImmediately: Bool { return startRequestsImmediately } + + public func cleanup(after request: Request) { + activeRequests.remove(request) + } + + public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) { + guard let retrier = retrier(for: request) else { + rootQueue.async { completion(.doNotRetry) } + return + } + + retrier.retry(request, for: self, dueTo: error) { retryResult in + self.rootQueue.async { + guard let retryResultError = retryResult.error else { completion(retryResult); return } + + let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error) + completion(.doNotRetryWithError(retryError)) + } + } + } + + public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) { + rootQueue.async { + let retry: () -> Void = { + guard !request.isCancelled else { return } + + request.prepareForRetry() + self.perform(request) + } + + if let retryDelay = timeDelay { + self.rootQueue.after(retryDelay) { retry() } + } else { + retry() + } + } + } +} + +// MARK: - SessionStateProvider + +extension Session: SessionStateProvider { + func request(for task: URLSessionTask) -> Request? { + return requestTaskMap[task] + } + + func didGatherMetricsForTask(_ task: URLSessionTask) { + requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task) + } + + func didCompleteTask(_ task: URLSessionTask) { + requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task) + } + + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? { + return requestTaskMap[task]?.credential ?? + session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace) + } + + func cancelRequestsForSessionInvalidation(with error: Error?) { + requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/SessionDelegate.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..77f5379 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,326 @@ +// +// SessionDelegate.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. +open class SessionDelegate: NSObject { + private let fileManager: FileManager + + weak var stateProvider: SessionStateProvider? + var eventMonitor: EventMonitor? + + /// Creates an instance from the given `FileManager`. + /// + /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files. + /// `.default` by default. + public init(fileManager: FileManager = .default) { + self.fileManager = fileManager + } + + /// Internal method to find and cast requests while maintaining some integrity checking. + /// + /// - Parameters: + /// - task: The `URLSessionTask` for which to find the associated `Request`. + /// - type: The `Request` subclass type to cast any `Request` associate with `task`. + func request(for task: URLSessionTask, as type: R.Type) -> R? { + guard let provider = stateProvider else { + assertionFailure("StateProvider is nil.") + return nil + } + + guard let request = provider.request(for: task) as? R else { + fatalError("Returned Request is not of expected type: \(R.self).") + } + + return request + } +} + +/// Type which provides various `Session` state values. +protocol SessionStateProvider: AnyObject { + var serverTrustManager: ServerTrustManager? { get } + var redirectHandler: RedirectHandler? { get } + var cachedResponseHandler: CachedResponseHandler? { get } + + func request(for task: URLSessionTask) -> Request? + func didGatherMetricsForTask(_ task: URLSessionTask) + func didCompleteTask(_ task: URLSessionTask) + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? + func cancelRequestsForSessionInvalidation(with error: Error?) +} + +// MARK: URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) + + stateProvider?.cancelRequestsForSessionInvalidation(with: error) + } +} + +// MARK: URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// Result of a `URLAuthenticationChallenge` evaluation. + typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?) + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + eventMonitor?.urlSession(session, task: task, didReceive: challenge) + + let evaluation: ChallengeEvaluation + switch challenge.protectionSpace.authenticationMethod { + case NSURLAuthenticationMethodServerTrust: + evaluation = attemptServerTrustAuthentication(with: challenge) + case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, + NSURLAuthenticationMethodNegotiate, NSURLAuthenticationMethodClientCertificate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + default: + evaluation = (.performDefaultHandling, nil, nil) + } + + if let error = evaluation.error { + stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) + } + + completionHandler(evaluation.disposition, evaluation.credential) + } + + /// Evaluates the server trust `URLAuthenticationChallenge` received. + /// + /// - Parameter challenge: The `URLAuthenticationChallenge`. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { + let host = challenge.protectionSpace.host + + guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, + let trust = challenge.protectionSpace.serverTrust + else { + return (.performDefaultHandling, nil, nil) + } + + do { + guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { + return (.performDefaultHandling, nil, nil) + } + + try evaluator.evaluate(trust, forHost: host) + + return (.useCredential, URLCredential(trust: trust), nil) + } catch { + return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) + } + } + + /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. + /// + /// - Parameters: + /// - challenge: The `URLAuthenticationChallenge`. + /// - task: The `URLSessionTask` which received the challenge. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge, + belongingTo task: URLSessionTask) -> ChallengeEvaluation { + guard challenge.previousFailureCount == 0 else { + return (.rejectProtectionSpace, nil, nil) + } + + guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { + return (.performDefaultHandling, nil, nil) + } + + return (.useCredential, credential, nil) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + eventMonitor?.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + + stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { + eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) + + guard let request = request(for: task, as: UploadRequest.self) else { + assertionFailure("needNewBodyStream did not find UploadRequest.") + completionHandler(nil) + return + } + + completionHandler(request.inputStream()) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { + eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request) + + if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { + redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) + } else { + completionHandler(request) + } + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) + + stateProvider?.request(for: task)?.didGatherMetrics(metrics) + + stateProvider?.didGatherMetricsForTask(task) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) + + stateProvider?.request(for: task)?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) + + stateProvider?.didCompleteTask(task) + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task) + } +} + +// MARK: URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) + + guard let request = request(for: dataTask, as: DataRequest.self) else { + assertionFailure("dataTask did not find DataRequest.") + return + } + + request.didReceive(data: data) + } + + open func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) { + eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) + + if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { + handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, + totalBytesExpectedToWrite: expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + + guard let request = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + guard let response = request.response else { + fatalError("URLSessionDownloadTask finished downloading with no response.") + } + + let (destination, options) = (request.destination)(location, response) + + eventMonitor?.request(request, didCreateDestinationURL: destination) + + do { + if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { + try fileManager.removeItem(at: destination) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destination.deletingLastPathComponent() + try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try fileManager.moveItem(at: location, to: destination) + + request.didFinishDownloading(using: downloadTask, with: .success(destination)) + } catch { + request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, source: location, destination: destination))) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift new file mode 100644 index 0000000..9ac00ef --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/URLConvertible+URLRequestConvertible.swift @@ -0,0 +1,105 @@ +// +// URLConvertible+URLRequestConvertible.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `URLConvertible` protocol can be used to construct `URL`s, which can then be used to construct +/// `URLRequests`. +public protocol URLConvertible { + /// Returns a `URL` from the conforming instance or throws. + /// + /// - Returns: The `URL` created from the instance. + /// - Throws: Any error thrown while creating the `URL`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a `URL` if `self` can be used to initialize a `URL` instance, otherwise throws. + /// + /// - Returns: The `URL` initialized with `self`. + /// - Throws: An `AFError.invalidURL` instance. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + + return url + } +} + +extension URL: URLConvertible { + /// Returns `self`. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a `URL` if the `self`'s `url` is not nil, otherwise throws. + /// + /// - Returns: The `URL` from the `url` property. + /// - Throws: An `AFError.invalidURL` instance. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to safely construct `URLRequest`s. +public protocol URLRequestConvertible { + /// Returns a `URLRequest` or throws if an `Error` was encountered. + /// + /// - Returns: A `URLRequest`. + /// - Throws: Any error thrown while constructing the `URLRequest`. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The `URLRequest` returned by discarding any `Error` encountered. + public var urlRequest: URLRequest? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns `self`. + public func asURLRequest() throws -> URLRequest { return self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `url`, `method`, and `headers`. + /// + /// - Parameters: + /// - url: The `URLConvertible` value. + /// - method: The `HTTPMethod`. + /// - headers: The `HTTPHeaders`, `nil` by default. + /// - Throws: Any error thrown while converting the `URLConvertible` to a `URL`. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + allHTTPHeaderFields = headers?.dictionary + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/URLEncodedFormEncoder.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/URLEncodedFormEncoder.swift new file mode 100644 index 0000000..8da3576 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/URLEncodedFormEncoder.swift @@ -0,0 +1,973 @@ +// +// URLEncodedFormEncoder.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// An object that encodes instances into URL-encoded query strings. +/// +/// 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 `Bool` values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. +/// +/// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` +/// strategy is used, which formats dates from their structure. +/// +/// `SpaceEncoding` can be used to configure how spaces are encoded. Modern encodings use percent replacement (`%20`), +/// while older encodings may expect spaces to be replaced with `+`. +/// +/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. +public final class URLEncodedFormEncoder { + /// Encoding to use for `Array` values. + public enum ArrayEncoding { + /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding. + case brackets + /// No brackets are appended to the key and the key is encoded as is. + case noBrackets + + /// Encodes the key according to the encoding. + /// + /// - Parameter key: The `key` to encode. + /// - Returns: The encoded key. + func encode(_ key: String) -> String { + switch self { + case .brackets: return "\(key)[]" + case .noBrackets: return key + } + } + } + + /// Encoding to use for `Bool` values. + public enum BoolEncoding { + /// Encodes `true` as `1`, `false` as `0`. + case numeric + /// Encodes `true` as "true", `false` as "false". This is the default encoding. + case literal + + /// Encodes the given `Bool` as a `String`. + /// + /// - Parameter value: The `Bool` to encode. + /// + /// - Returns: The encoded `String`. + func encode(_ value: Bool) -> String { + switch self { + case .numeric: return value ? "1" : "0" + case .literal: return value ? "true" : "false" + } + } + } + + /// Encoding to use for `Data` values. + public enum DataEncoding { + /// Defers encoding to the `Data` type. + case deferredToData + /// Encodes `Data` as a Base64-encoded string. This is the default encoding. + case base64 + /// Encode the `Data` as a custom value encoded by the given closure. + case custom((Data) throws -> String) + + /// Encodes `Data` according to the encoding. + /// + /// - Parameter data: The `Data` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its + /// `Encodable` implementation. + func encode(_ data: Data) throws -> String? { + switch self { + case .deferredToData: return nil + case .base64: return data.base64EncodedString() + case let .custom(encoding): return try encoding(data) + } + } + } + + /// Encoding to use for `Date` values. + public enum DateEncoding { + /// ISO8601 and RFC3339 formatter. + private static let iso8601Formatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter + }() + + /// Defers encoding to the `Date` type. This is the default encoding. + case deferredToDate + /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970. + case secondsSince1970 + /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970. + case millisecondsSince1970 + /// Encodes `Date`s according to the ISO8601 and RFC3339 standards. + case iso8601 + /// Encodes `Date`s using the given `DateFormatter`. + case formatted(DateFormatter) + /// Encodes `Date`s using the given closure. + case custom((Date) throws -> String) + + /// Encodes the date according to the encoding. + /// + /// - Parameter date: The `Date` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its + /// `Encodable` implementation. + func encode(_ date: Date) throws -> String? { + switch self { + case .deferredToDate: + return nil + case .secondsSince1970: + return String(date.timeIntervalSince1970) + case .millisecondsSince1970: + return String(date.timeIntervalSince1970 * 1000.0) + case .iso8601: + return DateEncoding.iso8601Formatter.string(from: date) + case let .formatted(formatter): + return formatter.string(from: date) + case let .custom(closure): + return try closure(date) + } + } + } + + /// Encoding to use for keys. + /// + /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128) + /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102). + public enum KeyEncoding { + /// Use the keys specified by each type. This is the default encoding. + case useDefaultKeys + /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key. + /// + /// Capital characters are determined by testing membership in + /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` + /// (Unicode General Categories Lu and Lt). + /// The conversion to lower case uses `Locale.system`, also known as + /// the ICU "root" locale. This means the result is consistent + /// regardless of the current user's locale and language preferences. + /// + /// Converting from camel case to snake case: + /// 1. Splits words at the boundary of lower-case to upper-case + /// 2. Inserts `_` between words + /// 3. Lowercases the entire string + /// 4. Preserves starting and ending `_`. + /// + /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. + /// + /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. + case convertToSnakeCase + /// Same as convertToSnakeCase, but using `-` instead of `_`. + /// For example `oneTwoThree` becomes `one-two-three`. + case convertToKebabCase + /// Capitalize the first letter only. + /// For example `oneTwoThree` becomes `OneTwoThree`. + case capitalized + /// Uppercase all letters. + /// For example `oneTwoThree` becomes `ONETWOTHREE`. + case uppercased + /// Lowercase all letters. + /// For example `oneTwoThree` becomes `onetwothree`. + case lowercased + /// A custom encoding using the provided closure. + case custom((String) -> String) + + func encode(_ key: String) -> String { + switch self { + case .useDefaultKeys: return key + case .convertToSnakeCase: return convertToSnakeCase(key) + case .convertToKebabCase: return convertToKebabCase(key) + case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst()) + case .uppercased: return key.uppercased() + case .lowercased: return key.lowercased() + case let .custom(encoding): return encoding(key) + } + } + + private func convertToSnakeCase(_ key: String) -> String { + return convert(key, usingSeparator: "_") + } + + private func convertToKebabCase(_ key: String) -> String { + return convert(key, usingSeparator: "-") + } + + private func convert(_ key: String, usingSeparator separator: String) -> String { + guard !key.isEmpty else { return key } + + var words: [Range] = [] + // The general idea of this algorithm is to split words on + // transition from lower to upper case, then on transition of >1 + // upper case characters to lowercase + // + // myProperty -> my_property + // myURLProperty -> my_url_property + // + // It is assumed, per Swift naming conventions, that the first character of the key is lowercase. + var wordStart = key.startIndex + var searchRange = key.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before the lower case character. + let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound) + words.append(upperCaseRange.lowerBound.. String { + switch self { + case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20") + case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+") + } + } + } + + /// `URLEncodedFormEncoder` error. + public enum Error: Swift.Error { + /// An invalid root object was created by the encoder. Only keyed values are valid. + case invalidRootObject(String) + + var localizedDescription: String { + switch self { + case let .invalidRootObject(object): + return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead." + } + } + } + + /// Whether or not to sort the encoded key value pairs. + /// + /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, + /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to + /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order. + public let alphabetizeKeyValuePairs: Bool + /// The `ArrayEncoding` to use. + public let arrayEncoding: ArrayEncoding + /// The `BoolEncoding` to use. + public let boolEncoding: BoolEncoding + /// THe `DataEncoding` to use. + public let dataEncoding: DataEncoding + /// The `DateEncoding` to use. + public let dateEncoding: DateEncoding + /// The `KeyEncoding` to use. + public let keyEncoding: KeyEncoding + /// The `SpaceEncoding` to use. + public let spaceEncoding: SpaceEncoding + /// The `CharacterSet` of allowed (non-escaped) characters. + public var allowedCharacters: CharacterSet + + /// Creates an instance from the supplied parameters. + /// + /// - Parameters: + /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default. + /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default. + /// - dataEncoding: The `DataEncoding` to use. `.base64` by default. + /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default. + /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default. + /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default. + /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by + /// default. + public init(alphabetizeKeyValuePairs: Bool = true, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric, + dataEncoding: DataEncoding = .base64, + dateEncoding: DateEncoding = .deferredToDate, + keyEncoding: KeyEncoding = .useDefaultKeys, + spaceEncoding: SpaceEncoding = .percentEscaped, + allowedCharacters: CharacterSet = .afURLQueryAllowed) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.keyEncoding = keyEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func encode(_ value: Encodable) throws -> URLEncodedFormComponent { + let context = URLEncodedFormContext(.object([])) + let encoder = _URLEncodedFormEncoder(context: context, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + try value.encode(to: encoder) + + return context.component + } + + /// Encodes the `value` as a URL form encoded `String`. + /// + /// - Parameter value: The `Encodable` value.` + /// + /// - Returns: The encoded `String`. + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: Encodable) throws -> String { + let component: URLEncodedFormComponent = try encode(value) + + guard case let .object(object) = component else { + throw Error.invalidRootObject("\(component)") + } + + let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs, + arrayEncoding: arrayEncoding, + keyEncoding: keyEncoding, + spaceEncoding: spaceEncoding, + allowedCharacters: allowedCharacters) + let query = serializer.serialize(object) + + return query + } + + /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the + /// `.utf8` data. + /// + /// - Parameter value: The `Encodable` value. + /// + /// - Returns: The encoded `Data`. + /// + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: Encodable) throws -> Data { + let string: String = try encode(value) + + return Data(string.utf8) + } +} + +final class _URLEncodedFormEncoder { + var codingPath: [CodingKey] + // Returns an empty dictionary, as this encoder doesn't support userInfo. + var userInfo: [CodingUserInfoKey: Any] { return [:] } + + let context: URLEncodedFormContext + + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey] = [], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + } +} + +extension _URLEncodedFormEncoder: Encoder { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { + return _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } + + func singleValueContainer() -> SingleValueEncodingContainer { + return _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } +} + +final class URLEncodedFormContext { + var component: URLEncodedFormComponent + + init(_ component: URLEncodedFormComponent) { + self.component = component + } +} + +enum URLEncodedFormComponent { + typealias Object = [(key: String, value: URLEncodedFormComponent)] + + case string(String) + case array([URLEncodedFormComponent]) + case object(Object) + + /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible. + var array: [URLEncodedFormComponent]? { + switch self { + case let .array(array): return array + default: return nil + } + } + + /// Converts self to an `Object` or returns `nil` if not convertible. + var object: Object? { + switch self { + case let .object(object): return object + default: return nil + } + } + + /// Sets self to the supplied value at a given path. + /// + /// data.set(to: "hello", at: ["path", "to", "value"]) + /// + /// - parameters: + /// - value: Value of `Self` to set at the supplied path. + /// - path: `CodingKey` path to update with the supplied value. + public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) { + set(&self, to: value, at: path) + } + + /// Recursive backing method to `set(to:at:)`. + private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) { + guard path.count >= 1 else { + context = value + return + } + + let end = path[0] + var child: URLEncodedFormComponent + switch path.count { + case 1: + child = value + case 2...: + if let index = end.intValue { + let array = context.array ?? [] + if array.count > index { + child = array[index] + } else { + child = .array([]) + } + set(&child, to: value, at: Array(path[1...])) + } else { + child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init()) + set(&child, to: value, at: Array(path[1...])) + } + default: fatalError("Unreachable") + } + + if let index = end.intValue { + if var array = context.array { + if array.count > index { + array[index] = child + } else { + array.append(child) + } + context = .array(array) + } else { + context = .array([child]) + } + } else { + if var object = context.object { + if let index = object.firstIndex(where: { $0.key == end.stringValue }) { + object[index] = (key: end.stringValue, value: child) + } else { + object.append((key: end.stringValue, value: child)) + } + context = .object(object) + } else { + context = .object([(key: end.stringValue, value: child)]) + } + } + } +} + +struct AnyCodingKey: CodingKey, Hashable { + let stringValue: String + let intValue: Int? + + init?(stringValue: String) { + self.stringValue = stringValue + intValue = nil + } + + init?(intValue: Int) { + stringValue = "\(intValue)" + self.intValue = intValue + } + + init(_ base: Key) where Key: CodingKey { + if let intValue = base.intValue { + self.init(intValue: intValue)! + } else { + self.init(stringValue: base.stringValue)! + } + } +} + +extension _URLEncodedFormEncoder { + final class KeyedContainer where Key: CodingKey { + var codingPath: [CodingKey] + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + } + + private func nestedCodingPath(for key: CodingKey) -> [CodingKey] { + return codingPath + [key] + } + } +} + +extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol { + func encodeNil(forKey key: Key) throws { + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "URLEncodedFormEncoder cannot encode nil values.") + throw EncodingError.invalidValue("\(key): nil", context) + } + + func encode(_ value: T, forKey key: Key) throws where T: Encodable { + var container = nestedSingleValueEncoder(for: key) + try container.encode(value) + } + + func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer { + let container = _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + + return container + } + + func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { + let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + + return container + } + + func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + + return KeyedEncodingContainer(container) + } + + func superEncoder() -> Encoder { + return _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } + + func superEncoder(forKey key: Key) -> Encoder { + return _URLEncodedFormEncoder(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } +} + +extension _URLEncodedFormEncoder { + final class SingleValueContainer { + var codingPath: [CodingKey] + + private var canEncodeNewValue = true + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + } + + private func checkCanEncode(value: Any?) throws { + guard canEncodeNewValue else { + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "Attempt to encode value through single value container when previously value already encoded.") + throw EncodingError.invalidValue(value as Any, context) + } + } + } +} + +extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer { + func encodeNil() throws { + try checkCanEncode(value: nil) + defer { canEncodeNewValue = false } + + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "URLEncodedFormEncoder cannot encode nil values.") + throw EncodingError.invalidValue("nil", context) + } + + func encode(_ value: Bool) throws { + try encode(value, as: String(boolEncoding.encode(value))) + } + + func encode(_ value: String) throws { + try encode(value, as: value) + } + + func encode(_ value: Double) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Float) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int64) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt64) throws { + try encode(value, as: String(value)) + } + + private func encode(_ value: T, as string: String) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + context.component.set(to: .string(string), at: codingPath) + } + + func encode(_ value: T) throws where T: Encodable { + switch value { + case let date as Date: + guard let string = try dateEncoding.encode(date) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + case let data as Data: + guard let string = try dataEncoding.encode(data) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + default: + try attemptToEncode(value) + } + } + + private func attemptToEncode(_ value: T) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + let encoder = _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + try value.encode(to: encoder) + } +} + +extension _URLEncodedFormEncoder { + final class UnkeyedContainer { + var codingPath: [CodingKey] + + var count = 0 + var nestedCodingPath: [CodingKey] { + return codingPath + [AnyCodingKey(intValue: count)!] + } + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + } + } +} + +extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer { + func encodeNil() throws { + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "URLEncodedFormEncoder cannot encode nil values.") + throw EncodingError.invalidValue("nil", context) + } + + func encode(_ value: T) throws where T: Encodable { + var container = nestedSingleValueContainer() + try container.encode(value) + } + + func nestedSingleValueContainer() -> SingleValueEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } + + func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey: CodingKey { + defer { count += 1 } + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + + return KeyedEncodingContainer(container) + } + + func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } + + func superEncoder() -> Encoder { + defer { count += 1 } + + return _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding) + } +} + +final class URLEncodedFormSerializer { + private let alphabetizeKeyValuePairs: Bool + private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding + private let keyEncoding: URLEncodedFormEncoder.KeyEncoding + private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding + private let allowedCharacters: CharacterSet + + init(alphabetizeKeyValuePairs: Bool, + arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, + keyEncoding: URLEncodedFormEncoder.KeyEncoding, + spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, + allowedCharacters: CharacterSet) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.keyEncoding = keyEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func serialize(_ object: URLEncodedFormComponent.Object) -> String { + var output: [String] = [] + for (key, component) in object { + let value = serialize(component, forKey: key) + output.append(value) + } + output = alphabetizeKeyValuePairs ? output.sorted() : output + + return output.joinedWithAmpersands() + } + + func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { + switch component { + case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))" + case let .array(array): return serialize(array, forKey: key) + case let .object(object): return serialize(object, forKey: key) + } + } + + func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String { + var segments: [String] = object.map { subKey, value in + let keyPath = "[\(subKey)]" + return serialize(value, forKey: key + keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { + var segments: [String] = array.map { component in + let keyPath = arrayEncoding.encode(key) + return serialize(component, forKey: keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func escape(_ query: String) -> String { + var allowedCharactersWithSpace = allowedCharacters + allowedCharactersWithSpace.insert(charactersIn: " ") + let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query + let spaceEncodedQuery = spaceEncoding.encode(escapedQuery) + + return spaceEncodedQuery + } +} + +extension Array where Element == String { + func joinedWithAmpersands() -> String { + return joined(separator: "&") + } +} + +public extension CharacterSet { + /// Creates a CharacterSet from RFC 3986 allowed characters. + /// + /// RFC 3986 states that the following characters are "reserved" characters. + /// + /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// + /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + /// should be percent-escaped in the query string. + static let afURLQueryAllowed: CharacterSet = { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters) + }() +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/URLRequest+Alamofire.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/URLRequest+Alamofire.swift new file mode 100644 index 0000000..b198fe0 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/URLRequest+Alamofire.swift @@ -0,0 +1,39 @@ +// +// URLRequest+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +public extension URLRequest { + /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type. + var method: HTTPMethod? { + get { return httpMethod.flatMap(HTTPMethod.init) } + set { httpMethod = newValue?.rawValue } + } + + func validate() throws { + if method == .get, let bodyData = httpBody { + throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData)) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift new file mode 100644 index 0000000..de3e290 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/URLSessionConfiguration+Alamofire.swift @@ -0,0 +1,37 @@ +// +// URLSessionConfiguration+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension URLSessionConfiguration: AlamofireExtended {} +extension AlamofireExtension where ExtendedType: URLSessionConfiguration { + /// Alamofire's default configuration. Same as `URLSessionConfiguration.default` but adds Alamofire default + /// `Accept-Language`, `Accept-Encoding`, and `User-Agent` headers. + public static var `default`: URLSessionConfiguration { + let configuration = URLSessionConfiguration.default + configuration.headers = .default + + return configuration + } +} diff --git a/TesteArenaFelipePerius/Pods/Alamofire/Source/Validation.swift b/TesteArenaFelipePerius/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..1f702b9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,247 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// Used to represent whether a validation succeeded or failed. + public typealias ValidationResult = Result + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { return type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] + + return split.components(separatedBy: "/") + }() + + if let type = components.first, let subtype = components.last { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(_ mime: MIMEType) -> Bool { + switch (type, subtype) { + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: Range { return 200..<300 } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate(statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int { + if acceptableStatusCodes.contains(response.statusCode) { + return .success(Void()) + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate(contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String { + guard let data = data, data.count > 0 else { return .success(Void()) } + + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success(Void()) + } + } + + 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(Void()) + } + } + + 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 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(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + self.validate(contentType: acceptableContentTypes(), response: response, data: data) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + let contentTypes: () -> [String] = { [unowned self] in + self.acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = (_ request: URLRequest?, + _ response: HTTPURLResponse, + _ fileURL: URL?) + -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, fileURL in + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes(), response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + let contentTypes = { [unowned self] in + self.acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} diff --git a/TesteArenaFelipePerius/Pods/Manifest.lock b/TesteArenaFelipePerius/Pods/Manifest.lock new file mode 100644 index 0000000..81647ea --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Manifest.lock @@ -0,0 +1,24 @@ +PODS: + - Alamofire (5.0.0) + - ObjectMapper (3.5.1) + - RxSwift (4.5.0) + +DEPENDENCIES: + - Alamofire (~> 5.0) + - ObjectMapper (~> 3.4) + - RxSwift (~> 4.0) + +SPEC REPOS: + trunk: + - Alamofire + - ObjectMapper + - RxSwift + +SPEC CHECKSUMS: + Alamofire: 58ff2bfb8daaacaa233d5c36e37b10a5248f59b1 + ObjectMapper: 70187b8941977c62ccfb423caf6b50be405cabf0 + RxSwift: f172070dfd1a93d70a9ab97a5a01166206e1c575 + +PODFILE CHECKSUM: 8aff128e776311a1989b50e8a54660c9cb8a4c53 + +COCOAPODS: 1.8.4 diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/LICENSE b/TesteArenaFelipePerius/Pods/ObjectMapper/LICENSE new file mode 100644 index 0000000..be48bc6 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2014 Hearst + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/README-CN.md b/TesteArenaFelipePerius/Pods/ObjectMapper/README-CN.md new file mode 100644 index 0000000..1651759 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/README-CN.md @@ -0,0 +1,500 @@ +# ObjectMapper-CN-Guide +> 文档由Swift老司机活动中心负责翻译,欢迎关注[@SwiftOldDriver](http://weibo.com/6062089411)。翻译有问题可以到 [ObjectMapper-CN-Guide](https://github.com/SwiftOldDriver/ObjectMapper-CN-Guide) 提 PR。 + +[ObjectMapper](https://github.com/Hearst-DD/ObjectMapper) 是一个使用 Swift 编写的用于 model 对象(类和结构体)和 JSON 之间转换的框架。 + +- [特性](#特性) +- [基础使用方法](#基础使用方法) +- [映射嵌套对象](#映射嵌套对象) +- [自定义转换规则](#自定义转换规则) +- [继承](#继承) +- [泛型对象](#泛型对象) +- [映射时的上下文对象](#映射时的上下文对象) +- [ObjectMapper + Alamofire](#objectmapper--alamofire) +- [ObjectMapper + Realm](#objectmapper--realm) +- [待完成](#待完成) +- [安装](#安装) + +# 特性: +- 把 JSON 映射成对象 +- 把对象映射 JSON +- 支持嵌套对象 (单独的成员变量、在数组或字典中都可以) +- 在转换过程支持自定义规则 +- 支持结构体( Struct ) +- [Immutable support](#immutablemappable-protocol-beta) (目前还在 beta ) + +# 基础使用方法 +为了支持映射,类或者结构体只需要实现```Mappable```协议。这个协议包含以下方法: +```swift +init?(map: Map) +mutating func mapping(map: Map) +``` +ObjectMapper使用自定义的```<-``` 运算符来声明成员变量和 JSON 的映射关系。 +```swift +class User: Mappable { + var username: String? + var age: Int? + var weight: Double! + var array: [AnyObject]? + var dictionary: [String : AnyObject] = [:] + var bestFriend: User? // 嵌套的 User 对象 + var friends: [User]? // Users 的数组 + var birthday: NSDate? + + required init?(map: Map) { + + } + + // Mappable + func mapping(map: Map) { + username <- map["username"] + age <- map["age"] + weight <- map["weight"] + array <- map["arr"] + dictionary <- map["dict"] + bestFriend <- map["best_friend"] + friends <- map["friends"] + birthday <- (map["birthday"], DateTransform()) + } +} + +struct Temperature: Mappable { + var celsius: Double? + var fahrenheit: Double? + + init?(map: Map) { + + } + + mutating func mapping(map: Map) { + celsius <- map["celsius"] + fahrenheit <- map["fahrenheit"] + } +} +``` + +一旦你的对象实现了 `Mappable`, ObjectMapper就可以让你轻松的实现和 JSON 之间的转换。 + +把 JSON 字符串转成 model 对象: + +```swift +let user = User(JSONString: JSONString) +``` + +把一个 model 转成 JSON 字符串: + +```swift +let JSONString = user.toJSONString(prettyPrint: true) +``` + +也可以使用`Mapper.swift`类来完成转换(这个类还额外提供了一些函数来处理一些特殊的情况: + +```swift +// 把 JSON 字符串转成 Model +let user = Mapper().map(JSONString: JSONString) +// 根据 Model 生成 JSON 字符串 +let JSONString = Mapper().toJSONString(user, prettyPrint: true) +``` + +ObjectMapper支持以下的类型映射到对象中: + +- `Int` +- `Bool` +- `Double` +- `Float` +- `String` +- `RawRepresentable` (枚举) +- `Array` +- `Dictionary` +- `Object` +- `Array` +- `Array>` +- `Set` +- `Dictionary` +- `Dictionary>` +- 以上所有的 Optional 类型 +- 以上所有的隐式强制解包类型(Implicitly Unwrapped Optional) + +## `Mappable` 协议 + +#### `mutating func mapping(map: Map)` +所有的映射最后都会调用到这个函数。当解析 JSON 时,这个函数会在对象创建成功后被执行。当生成 JSON 时就只有这个函数会被对象调用。 + +#### `init?(map: Map)` +这个可失败的初始化函数是 ObjectMapper 创建对象的时候使用的。开发者可以通过这个函数在映射前校验 JSON 。如果在这个方法里返回 nil 就不会执行 `mapping` 函数。可以通过传入的保存着 JSON 的 `Map` 对象进行校验: + +```swift +required init?(map: Map){ + // 检查 JSON 里是否有一定要有的 "name" 属性 + if map.JSONDictionary["name"] == nil { + return nil + } +} +``` + +## `StaticMappable` 协议 +`StaticMappable` 是 `Mappable` 之外的另一种选择。 这个协议可以让开发者通过一个静态函数初始化对象而不是通过 `init?(map: Map)`。 + +注意: `StaticMappable` 和 `Mappable` 都继承了 `BaseMappable` 协议。 `BaseMappable` 协议声明了 `mapping(map: Map)` 函数。 + +#### `static func objectForMapping(map: Map) -> BaseMappable?` +ObjectMapper 使用这个函数获取对象后进行映射。开发者需要在这个函数里返回一个实现 `BaseMappable` 对象的实例。这个函数也可以用于: + +- 在对象进行映射前校验 JSON +- 提供一个缓存过的对象用于映射 +- 返回另外一种类型的对象(当然是必须实现了 BaseMappable)用于映射。比如你可能通过检查 JSON 推断出用于映射的对象 ([看这个例子](https://github.com/Hearst-DD/ObjectMapper/blob/master/ObjectMapperTests/ClassClusterTests.swift#L62))。 + +如果你需要在 extension 里实现 ObjectMapper,你需要选择这个协议而不是 `Mappable` 。 + +## `ImmutableMappable` Protocol + +使用 `ImmutableMappable` 可以映射不可变的属性。下面的表格展示了 `ImmutableMappable` 和 `Mappable` 的不同: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ImmutableMappableMappable
Properties
+
+let id: Int
+let name: String?
+
+
+
+var id: Int!
+var name: String?
+
+
JSON -> Model
+
+init(map: Map) throws {
+  id   = try map.value("id")
+  name = try? map.value("name")
+}
+
+
+
+mutating func mapping(map: Map) {
+  id   <- map["id"]
+  name <- map["name"]
+}
+
+
Model -> JSON
+
+mutating func mapping(map: Map) {
+  id   >>> map["id"]
+  name >>> map["name"]
+}
+
+
+
+mutating func mapping(map: Map) {
+  id   <- map["id"]
+  name <- map["name"]
+}
+
+
Initializing
+
+try User(JSONString: JSONString)
+
+
+
+User(JSONString: JSONString)
+
+
+ +#### `init(map: Map) throws` + +这个可能抛出异常的初始化函数用于在提供的 `Map` 里映射不可变属性。每个不可变的初始化属性都要在这个初始化函数里初始化。 + +当发生下列情况时初始化函数会抛出一个错误: + +- `Map` 根据提供的键名获取不到对应值 +- `Map` 使用 `Transform` 后没有得到值 + +`ImmutableMappable` 使用 `Map.value(_:using:)` 方法从 `Map` 中获取值。因为可能抛出异常,这个方法在使用时需要使用 `try` 关键字。 `Optional` 的属性可以简单的用 `try?` 处理。 + +```swift +init(map: Map) throws { + name = try map.value("name") // throws an error when it fails + createdAt = try map.value("createdAt", using: DateTransform()) // throws an error when it fails + updatedAt = try? map.value("updatedAt", using: DateTransform()) // optional + posts = (try? map.value("posts")) ?? [] // optional + default value +} +``` + +#### `mutating func mapping(map: Map)` + +这个方法是在 Model 转回 JSON 时调用的。因为不可变的属性不能被 `<-` 映射,所以映射回来时需要使用 `>>>` 。 + +```swift +mutating func mapping(map: Map) { + name >>> map["name"] + createdAt >>> (map["createdAt"], DateTransform()) + updatedAt >>> (map["updatedAt"], DateTransform()) + posts >>> map["posts"] +} +``` +# 轻松映射嵌套对象 + +ObjectMapper 支持使用点语法来轻松实现嵌套对象的映射。比如有如下的 JSON 字符串: + +```json +"distance" : { + "text" : "102 ft", + "value" : 31 +} +``` +你可以通过这种写法直接访问到嵌套对象: + +```swift +func mapping(map: Map) { + distance <- map["distance.value"] +} +``` +嵌套的键名也支持访问数组中的值。如果有一个返回的 JSON 是一个包含 distance 的数组,可以通过这种写法访问: + +``` +distance <- map["distances.0.value"] +``` +如果你的键名刚好含有 `.` 符号,你需要特别声明关闭上面提到的获取嵌套对象功能: + +```swift +func mapping(map: Map) { + identifier <- map["app.identifier", nested: false] +} +``` +如果刚好有嵌套的对象的键名还有 `.` ,可以在中间加入一个自定义的分割符([#629](https://github.com/Hearst-DD/ObjectMapper/pull/629)): +```swift +func mapping(map: Map) { + appName <- map["com.myapp.info->com.myapp.name", delimiter: "->"] +} +``` +这种情况的 JSON 是这样的: + +```json +"com.myapp.info" : { + "com.myapp.name" : "SwiftOldDriver" +} +``` + +# 自定义转换规则 +ObjectMapper 也支持在映射时自定义转换规则。如果要使用自定义转换,创建一个 tuple(元祖)包含 ```map["field_name"]``` 和你要使用的变换放在 ```<-``` 的右边: + +```swift +birthday <- (map["birthday"], DateTransform()) +``` +当解析 JSON 时上面的转换会把 JSON 里面的 Int 值转成一个 NSDate ,如果是对象转为 JSON 时,则会把 NSDate 对象转成 Int 值。 + +只要实现```TransformType``` 协议就可以轻松的创建自定义的转换规则: + +```swift +public protocol TransformType { + associatedtype Object + associatedtype JSON + + func transformFromJSON(_ value: Any?) -> Object? + func transformToJSON(_ value: Object?) -> JSON? +} +``` + +### TransformOf +大多数情况下你都可以使用框架提供的转换类 ```TransformOf``` 来快速的实现一个期望的转换。 ```TransformOf``` 的初始化需要两个类型和两个闭包。两个类型声明了转换的目标类型和源类型,闭包则实现具体转换逻辑。 + +举个例子,如果你想要把一个 JSON 字符串转成 Int ,你可以像这样使用 ```TransformOf``` : + +```swift +let transform = TransformOf(fromJSON: { (value: String?) -> Int? in + // 把值从 String? 转成 Int? + return Int(value!) +}, toJSON: { (value: Int?) -> String? in + // 把值从 Int? 转成 String? + if let value = value { + return String(value) + } + return nil +}) + +id <- (map["id"], transform) +``` +这是一种更省略的写法: + +```swift +id <- (map["id"], TransformOf(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } })) +``` +# 继承 + +实现了 ```Mappable``` 协议的类可以容易的被继承。当继承一个 mappable 的类时,使用这样的结构: + +```swift +class Base: Mappable { + var base: String? + + required init?(map: Map) { + + } + + func mapping(map: Map) { + base <- map["base"] + } +} + +class Subclass: Base { + var sub: String? + + required init?(map: Map) { + super.init(map) + } + + override func mapping(map: Map) { + super.mapping(map) + + sub <- map["sub"] + } +} +``` + +注意确认子类中的实现调用了父类中正确的初始化器和映射函数。 + +# 泛型对象 + +ObjectMapper 可以处理泛型只要这个泛型也实现了`Mappable`协议。看这个例子: + +```swift +class Result: Mappable { + var result: T? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + result <- map["result"] + } +} + +let result = Mapper>().map(JSON) +``` +# 映射时的上下文对象 + +`Map` 是在映射时传入的对象,带有一个 optional `MapContext` 对象,开发者可以通过使用这个对象在映射时传入一些信息。 + +为了使用这个特性,需要先创建一个对象实现了 `MapContext` 协议(这个协议是空的),然后在初始化时传入 `Mapper` 中。 + +```swift +struct Context: MapContext { + var importantMappingInfo = "映射时需要知道的额外信息" +} + +class User: Mappable { + var name: String? + + required init?(map: Map){ + + } + + func mapping(map: Map){ + if let context = map.context as? Context { + // 获取到额外的信息 + } + } +} + +let context = Context() +let user = Mapper(context: context).map(JSONString) +``` + +# ObjectMapper + Alamofire + +如果网络层你使用的是 [Alamofire](https://github.com/Alamofire/Alamofire) ,并且你希望把返回的结果转换成 Swift 对象,你可以使用 [AlamofireObjectMapper](https://github.com/tristanhimmelman/AlamofireObjectMapper) 。这是一个使用 ObjectMapper 实现的把返回的 JSON 自动转成 Swift 对象的 Alamofire 的扩展。 + + +# ObjectMapper + Realm + +ObjectMapper 可以和 Realm 一起配合使用。使用下面的声明结构就可以使用 ObjectMapper 生成 Realm 对象: + +```swift +class Model: Object, Mappable { + dynamic var name = "" + + required convenience init?(map: Map) { + self.init() + } + + func mapping(map: Map) { + name <- map["name"] + } +} +``` + +如果你想要序列化相关联的 RealmObject,你可以使用 [ObjectMapper+Realm](https://github.com/jakenberg/ObjectMapper-Realm)。这是一个简单的 Realm 扩展,用于把任意的 JSON 序列化成 Realm 的类(ealm's List class。) + +注意:使用 ObjectMappers 的 `toJSON` 函数来生成 JSON 字符串只在 Realm 的写事务中有效(write transaction)。这是因为 ObjectMapper 在解析和生成时在映射函数( `<-` )中使用 `inout` 作为标记( flag )。Realm 会检测到标记并且强制要求 `toJSON` 函数只能在一个写的事务中调用,即使这个对象并没有被修改。 + +# 待完成 +- 改善错误的处理。可能使用 `throws` 来处理。 +- 相关类的文档完善 + +# 安装 +### Cocoapods +如果你的项目使用 [CocoaPods 0.36 及以上](http://blog.cocoapods.org/Pod-Authors-Guide-to-CocoaPods-Frameworks/) 的版本,你可以把下面内容添加到在 `Podfile` 中,将 ObjectMapper 添加到你的项目中: + +```ruby +pod 'ObjectMapper', '~> 2.2' +``` + +### Carthage +如果你的项目使用 [Carthage](https://github.com/Carthage/Carthage) ,你可以把下面的内容添加到 `Cartfile` 中,将 ObjectMapper 的依赖到你的项目中: + +``` +github "Hearst-DD/ObjectMapper" ~> 2.2 +``` + +### Swift Package Manager +如果你的项目使用 [Swift Package Manager](https://swift.org/package-manager/) ,那么你可以把下面内容添加到 `Package.swift` 中的 `dependencies` 数组中,将 ObjectMapper 的依赖到你的项目中: + +```swift +.Package(url: "https://github.com/Hearst-DD/ObjectMapper.git", majorVersion: 2, minor: 2), +``` + + +### Submodule +此外,ObjectMapper 也可以作为一个 submodule 添加到项目中: + +1. 打开终端,使用 `cd` 命令进入项目文件的根目录下,然后在终端中输入 `git submodule add https://github.com/Hearst-DD/ObjectMapper.git` ,把 ObjectMapper 作为项目的一个 [submodule](http://git-scm.com/docs/git-submodule) 添加进来。 +2. 打开 `ObjectMapper` 文件,并将 `ObjectMapper.xcodeproj` 拖进你 app 项目的文件导航中。 +3. 在 Xcode 中,文件导航中点击蓝色项目图标进入到 target 配置界面,在侧边栏的 "TARGETS" 下选择主工程对应的target。 +4. 确保 `ObjectMapper.framework` 的部署版本( deployment target )和主工程的部署版本保持一致。 +5. 在配置界面的顶部选项栏中,打开 "Build Phases" 面板。 +6. 展开 "Target Dependencies" 组,并添加 `ObjectMapper.framework` 。 +7. 点击面板左上角的 `+` 按钮,选择 "New Copy Files Phase"。将这个阶段重命名为 "Copy Frameworks",设置 "Destination" 为 "Frameworks",最后添加 `ObjectMapper.framework` 。 + + diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/CodableTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/CodableTransform.swift new file mode 100644 index 0000000..4cb72d5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/CodableTransform.swift @@ -0,0 +1,73 @@ +// +// CodableTransform.swift +// ObjectMapper +// +// Created by Jari Kalinainen on 10/10/2018. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +/// Transforms JSON dictionary to Codable type T and back +open class CodableTransform: TransformType { + + public typealias Object = T + public typealias JSON = Any + + public init() {} + + open func transformFromJSON(_ value: Any?) -> Object? { + var _data: Data? = nil + switch value { + case let dict as [String : Any]: + _data = try? JSONSerialization.data(withJSONObject: dict, options: []) + case let array as [[String : Any]]: + _data = try? JSONSerialization.data(withJSONObject: array, options: []) + default: + _data = nil + } + guard let data = _data else { return nil } + + do { + let decoder = JSONDecoder() + let item = try decoder.decode(T.self, from: data) + return item + } catch { + return nil + } + } + + open func transformToJSON(_ value: T?) -> JSON? { + guard let item = value else { + return nil + } + do { + let encoder = JSONEncoder() + let data = try encoder.encode(item) + let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) + return dictionary + } catch { + return nil + } + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift new file mode 100644 index 0000000..f7b8c54 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift @@ -0,0 +1,40 @@ +// +// CustomDateFormatTransform.swift +// ObjectMapper +// +// Created by Dan McCracken on 3/8/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +open class CustomDateFormatTransform: DateFormatterTransform { + + public init(formatString: String) { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = formatString + + super.init(dateFormatter: formatter) + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DataTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DataTransform.swift new file mode 100644 index 0000000..87cb25c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DataTransform.swift @@ -0,0 +1,50 @@ +// +// DataTransform.swift +// ObjectMapper +// +// Created by Yagrushkin, Evgeny on 8/30/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +open class DataTransform: TransformType { + public typealias Object = Data + public typealias JSON = String + + public init() {} + + open func transformFromJSON(_ value: Any?) -> Data? { + guard let string = value as? String else{ + return nil + } + return Data(base64Encoded: string) + } + + open func transformToJSON(_ value: Data?) -> String? { + guard let data = value else{ + return nil + } + return data.base64EncodedString() + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DateFormatterTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DateFormatterTransform.swift new file mode 100644 index 0000000..9828e2d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DateFormatterTransform.swift @@ -0,0 +1,54 @@ +// +// DateFormatterTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-03-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +open class DateFormatterTransform: TransformType { + public typealias Object = Date + public typealias JSON = String + + public let dateFormatter: DateFormatter + + public init(dateFormatter: DateFormatter) { + self.dateFormatter = dateFormatter + } + + open func transformFromJSON(_ value: Any?) -> Date? { + if let dateString = value as? String { + return dateFormatter.date(from: dateString) + } + return nil + } + + open func transformToJSON(_ value: Date?) -> String? { + if let date = value { + return dateFormatter.string(from: date) + } + return nil + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DateTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DateTransform.swift new file mode 100644 index 0000000..f55c87f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DateTransform.swift @@ -0,0 +1,75 @@ +// +// DateTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-13. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +open class DateTransform: TransformType { + public typealias Object = Date + public typealias JSON = Double + + public enum Unit: TimeInterval { + case seconds = 1 + case milliseconds = 1_000 + + func addScale(to interval: TimeInterval) -> TimeInterval { + return interval * rawValue + } + + func removeScale(from interval: TimeInterval) -> TimeInterval { + return interval / rawValue + } + } + + private let unit: Unit + + public init(unit: Unit = .seconds) { + self.unit = unit + } + + open func transformFromJSON(_ value: Any?) -> Date? { + var timeInterval: TimeInterval? + if let timeInt = value as? Double { + timeInterval = TimeInterval(timeInt) + } + + if let timeStr = value as? String { + timeInterval = TimeInterval(atof(timeStr)) + } + + return timeInterval.flatMap { + return Date(timeIntervalSince1970: unit.removeScale(from: $0)) + } + } + + open func transformToJSON(_ value: Date?) -> Double? { + if let date = value { + return Double(unit.addScale(to: date.timeIntervalSince1970)) + } + return nil + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DictionaryTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DictionaryTransform.swift new file mode 100644 index 0000000..35a1e6f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/DictionaryTransform.swift @@ -0,0 +1,76 @@ +// +// DictionaryTransform.swift +// ObjectMapper +// +// Created by Milen Halachev on 7/20/16. +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +///Transforms [String: AnyObject] <-> [Key: Value] where Key is RawRepresentable as String, Value is Mappable +public struct DictionaryTransform: TransformType where Key: Hashable, Key: RawRepresentable, Key.RawValue == String, Value: Mappable { + + public init() { + + } + + public func transformFromJSON(_ value: Any?) -> [Key: Value]? { + + guard let json = value as? [String: Any] else { + + return nil + } + + let result = json.reduce([:]) { (result, element) -> [Key: Value] in + + guard + let key = Key(rawValue: element.0), + let valueJSON = element.1 as? [String: Any], + let value = Value(JSON: valueJSON) + else { + + return result + } + + var result = result + result[key] = value + return result + } + + return result + } + + public func transformToJSON(_ value: [Key: Value]?) -> Any? { + + let result = value?.reduce([:]) { (result, element) -> [String: Any] in + + let key = element.0.rawValue + let value = element.1.toJSON() + + var result = result + result[key] = value + return result + } + + return result + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/EnumOperators.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/EnumOperators.swift new file mode 100644 index 0000000..3693a1d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/EnumOperators.swift @@ -0,0 +1,120 @@ +// +// EnumOperators.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2016-09-26. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + + +// MARK:- Raw Representable types + +/// Object of Raw Representable type +public func <- (left: inout T, right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: T, right: Map) { + left >>> (right, EnumTransform()) +} + + +/// Optional Object of Raw Representable type +public func <- (left: inout T?, right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: T?, right: Map) { + left >>> (right, EnumTransform()) +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly Unwrapped Optional Object of Raw Representable type +public func <- (left: inout T!, right: Map) { + left <- (right, EnumTransform()) +} +#endif + +// MARK:- Arrays of Raw Representable type + +/// Array of Raw Representable object +public func <- (left: inout [T], right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: [T], right: Map) { + left >>> (right, EnumTransform()) +} + + +/// Array of Raw Representable object +public func <- (left: inout [T]?, right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: [T]?, right: Map) { + left >>> (right, EnumTransform()) +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Array of Raw Representable object +public func <- (left: inout [T]!, right: Map) { + left <- (right, EnumTransform()) +} +#endif + +// MARK:- Dictionaries of Raw Representable type + +/// Dictionary of Raw Representable object +public func <- (left: inout [String: T], right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: [String: T], right: Map) { + left >>> (right, EnumTransform()) +} + + +/// Dictionary of Raw Representable object +public func <- (left: inout [String: T]?, right: Map) { + left <- (right, EnumTransform()) +} + +public func >>> (left: [String: T]?, right: Map) { + left >>> (right, EnumTransform()) +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Dictionary of Raw Representable object +public func <- (left: inout [String: T]!, right: Map) { + left <- (right, EnumTransform()) +} +#endif diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/EnumTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/EnumTransform.swift new file mode 100644 index 0000000..f63d3ad --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/EnumTransform.swift @@ -0,0 +1,50 @@ +// +// EnumTransform.swift +// ObjectMapper +// +// Created by Kaan Dedeoglu on 3/20/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +open class EnumTransform: TransformType { + public typealias Object = T + public typealias JSON = T.RawValue + + public init() {} + + open func transformFromJSON(_ value: Any?) -> T? { + if let raw = value as? T.RawValue { + return T(rawValue: raw) + } + return nil + } + + open func transformToJSON(_ value: T?) -> T.RawValue? { + if let obj = value { + return obj.rawValue + } + return nil + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/FromJSON.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/FromJSON.swift new file mode 100755 index 0000000..78268de --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/FromJSON.swift @@ -0,0 +1,202 @@ +// +// FromJSON.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Tristan Himmelman +// +// 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. + +internal final class FromJSON { + + /// Basic type + class func basicType(_ field: inout FieldType, object: FieldType?) { + if let value = object { + field = value + } + } + + /// optional basic type + class func optionalBasicType(_ field: inout FieldType?, object: FieldType?) { + field = object + } + + // Code targeting the Swift 4.1 compiler and below. + #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) + /// Implicitly unwrapped optional basic type + class func optionalBasicType(_ field: inout FieldType!, object: FieldType?) { + field = object + } + #endif + + /// Mappable object + class func object(_ field: inout N, map: Map) { + if map.toObject { + field = Mapper(context: map.context).map(JSONObject: map.currentValue, toObject: field) + } else if let value: N = Mapper(context: map.context).map(JSONObject: map.currentValue) { + field = value + } + } + + /// Optional Mappable Object + + class func optionalObject(_ field: inout N?, map: Map) { + if let f = field , map.toObject && map.currentValue != nil { + field = Mapper(context: map.context).map(JSONObject: map.currentValue, toObject: f) + } else { + field = Mapper(context: map.context).map(JSONObject: map.currentValue) + } + } + + // Code targeting the Swift 4.1 compiler and below. + #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) + /// Implicitly unwrapped Optional Mappable Object + class func optionalObject(_ field: inout N!, map: Map) { + if let f = field , map.toObject && map.currentValue != nil { + field = Mapper(context: map.context).map(JSONObject: map.currentValue, toObject: f) + } else { + field = Mapper(context: map.context).map(JSONObject: map.currentValue) + } + } + #endif + + /// mappable object array + class func objectArray(_ field: inout Array, map: Map) { + if let objects = Mapper(context: map.context).mapArray(JSONObject: map.currentValue) { + field = objects + } + } + + /// optional mappable object array + + class func optionalObjectArray(_ field: inout Array?, map: Map) { + if let objects: Array = Mapper(context: map.context).mapArray(JSONObject: map.currentValue) { + field = objects + } else { + field = nil + } + } + + // Code targeting the Swift 4.1 compiler and below. + #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) + /// Implicitly unwrapped optional mappable object array + class func optionalObjectArray(_ field: inout Array!, map: Map) { + if let objects: Array = Mapper(context: map.context).mapArray(JSONObject: map.currentValue) { + field = objects + } else { + field = nil + } + } + #endif + + /// mappable object array + class func twoDimensionalObjectArray(_ field: inout Array>, map: Map) { + if let objects = Mapper(context: map.context).mapArrayOfArrays(JSONObject: map.currentValue) { + field = objects + } + } + + /// optional mappable 2 dimentional object array + class func optionalTwoDimensionalObjectArray(_ field: inout Array>?, map: Map) { + field = Mapper(context: map.context).mapArrayOfArrays(JSONObject: map.currentValue) + } + + // Code targeting the Swift 4.1 compiler and below. + #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) + /// Implicitly unwrapped optional 2 dimentional mappable object array + class func optionalTwoDimensionalObjectArray(_ field: inout Array>!, map: Map) { + field = Mapper(context: map.context).mapArrayOfArrays(JSONObject: map.currentValue) + } + #endif + + /// Dctionary containing Mappable objects + class func objectDictionary(_ field: inout Dictionary, map: Map) { + if map.toObject { + field = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue, toDictionary: field) + } else { + if let objects = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue) { + field = objects + } + } + } + + /// Optional dictionary containing Mappable objects + class func optionalObjectDictionary(_ field: inout Dictionary?, map: Map) { + if let f = field , map.toObject && map.currentValue != nil { + field = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue, toDictionary: f) + } else { + field = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue) + } + } + + // Code targeting the Swift 4.1 compiler and below. + #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) + /// Implicitly unwrapped Dictionary containing Mappable objects + class func optionalObjectDictionary(_ field: inout Dictionary!, map: Map) { + if let f = field , map.toObject && map.currentValue != nil { + field = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue, toDictionary: f) + } else { + field = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue) + } + } + #endif + + /// Dictionary containing Array of Mappable objects + class func objectDictionaryOfArrays(_ field: inout Dictionary, map: Map) { + if let objects = Mapper(context: map.context).mapDictionaryOfArrays(JSONObject: map.currentValue) { + field = objects + } + } + + /// Optional Dictionary containing Array of Mappable objects + class func optionalObjectDictionaryOfArrays(_ field: inout Dictionary?, map: Map) { + field = Mapper(context: map.context).mapDictionaryOfArrays(JSONObject: map.currentValue) + } + + // Code targeting the Swift 4.1 compiler and below. + #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) + /// Implicitly unwrapped Dictionary containing Array of Mappable objects + class func optionalObjectDictionaryOfArrays(_ field: inout Dictionary!, map: Map) { + field = Mapper(context: map.context).mapDictionaryOfArrays(JSONObject: map.currentValue) + } + #endif + + /// mappable object Set + class func objectSet(_ field: inout Set, map: Map) { + if let objects = Mapper(context: map.context).mapSet(JSONObject: map.currentValue) { + field = objects + } + } + + /// optional mappable object array + class func optionalObjectSet(_ field: inout Set?, map: Map) { + field = Mapper(context: map.context).mapSet(JSONObject: map.currentValue) + } + + // Code targeting the Swift 4.1 compiler and below. + #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) + /// Implicitly unwrapped optional mappable object array + class func optionalObjectSet(_ field: inout Set!, map: Map) { + field = Mapper(context: map.context).mapSet(JSONObject: map.currentValue) + } + #endif +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/HexColorTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/HexColorTransform.swift new file mode 100644 index 0000000..1f02289 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/HexColorTransform.swift @@ -0,0 +1,144 @@ +// +// HexColorTransform.swift +// ObjectMapper +// +// Created by Vitaliy Kuzmenko on 10/10/16. +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(iOS) || os(tvOS) || os(watchOS) +import UIKit +#elseif os(macOS) +import Cocoa +#endif + +#if os(iOS) || os(tvOS) || os(watchOS) || os(macOS) +open class HexColorTransform: TransformType { + + #if os(iOS) || os(tvOS) || os(watchOS) + public typealias Object = UIColor + #else + public typealias Object = NSColor + #endif + + public typealias JSON = String + + var prefix: Bool = false + + var alpha: Bool = false + + public init(prefixToJSON: Bool = false, alphaToJSON: Bool = false) { + alpha = alphaToJSON + prefix = prefixToJSON + } + + open func transformFromJSON(_ value: Any?) -> Object? { + if let rgba = value as? String { + if rgba.hasPrefix("#") { + let index = rgba.index(rgba.startIndex, offsetBy: 1) + let hex = String(rgba[index...]) + return getColor(hex: hex) + } else { + return getColor(hex: rgba) + } + } + return nil + } + + open func transformToJSON(_ value: Object?) -> JSON? { + if let value = value { + return hexString(color: value) + } + return nil + } + + fileprivate func hexString(color: Object) -> String { + let comps = color.cgColor.components! + let compsCount = color.cgColor.numberOfComponents + let r: Int + let g: Int + var b: Int + let a = Int(comps[compsCount - 1] * 255) + if compsCount == 4 { // RGBA + r = Int(comps[0] * 255) + g = Int(comps[1] * 255) + b = Int(comps[2] * 255) + } else { // Grayscale + r = Int(comps[0] * 255) + g = Int(comps[0] * 255) + b = Int(comps[0] * 255) + } + var hexString: String = "" + if prefix { + hexString = "#" + } + hexString += String(format: "%02X%02X%02X", r, g, b) + + if alpha { + hexString += String(format: "%02X", a) + } + return hexString + } + + fileprivate func getColor(hex: String) -> Object? { + var red: CGFloat = 0.0 + var green: CGFloat = 0.0 + var blue: CGFloat = 0.0 + var alpha: CGFloat = 1.0 + + let scanner = Scanner(string: hex) + var hexValue: CUnsignedLongLong = 0 + if scanner.scanHexInt64(&hexValue) { + switch (hex.count) { + case 3: + red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 + green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 + blue = CGFloat(hexValue & 0x00F) / 15.0 + case 4: + red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 + green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 + blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 + alpha = CGFloat(hexValue & 0x000F) / 15.0 + case 6: + red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 + green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 + blue = CGFloat(hexValue & 0x0000FF) / 255.0 + case 8: + red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 + green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 + blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 + alpha = CGFloat(hexValue & 0x000000FF) / 255.0 + default: + // Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8 + return nil + } + } else { + // "Scan hex error + return nil + } + #if os(iOS) || os(tvOS) || os(watchOS) + return UIColor(red: red, green: green, blue: blue, alpha: alpha) + #else + return NSColor(red: red, green: green, blue: blue, alpha: alpha) + #endif + } +} +#endif diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift new file mode 100644 index 0000000..1f256ea --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift @@ -0,0 +1,47 @@ +// +// ISO8601DateTransform.swift +// ObjectMapper +// +// Created by Jean-Pierre Mouilleseaux on 21 Nov 2014. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +public extension DateFormatter { + convenience init(withFormat format : String, locale : String) { + self.init() + self.locale = Locale(identifier: locale) + dateFormat = format + } +} + +open class ISO8601DateTransform: DateFormatterTransform { + + static let reusableISODateFormatter = DateFormatter(withFormat: "yyyy-MM-dd'T'HH:mm:ssZZZZZ", locale: "en_US_POSIX") + + public init() { + super.init(dateFormatter: ISO8601DateTransform.reusableISODateFormatter) + } +} + diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ImmutableMappable.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ImmutableMappable.swift new file mode 100644 index 0000000..1f67824 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ImmutableMappable.swift @@ -0,0 +1,376 @@ +// +// ImmutableMappble.swift +// ObjectMapper +// +// Created by Suyeol Jeon on 23/09/2016. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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. + +public protocol ImmutableMappable: BaseMappable { + init(map: Map) throws +} + +public extension ImmutableMappable { + + /// Implement this method to support object -> JSON transform. + func mapping(map: Map) {} + + /// Initializes object from a JSON String + init(JSONString: String, context: MapContext? = nil) throws { + self = try Mapper(context: context).map(JSONString: JSONString) + } + + /// Initializes object from a JSON Dictionary + init(JSON: [String: Any], context: MapContext? = nil) throws { + self = try Mapper(context: context).map(JSON: JSON) + } + + /// Initializes object from a JSONObject + init(JSONObject: Any, context: MapContext? = nil) throws { + self = try Mapper(context: context).map(JSONObject: JSONObject) + } + +} + +public extension Map { + + fileprivate func currentValue(for key: String, nested: Bool? = nil, delimiter: String = ".") -> Any? { + let isNested = nested ?? key.contains(delimiter) + return self[key, nested: isNested, delimiter: delimiter].currentValue + } + + // MARK: Basic + + /// Returns a value or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let value = currentValue as? T else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '\(T.self)'", file: file, function: function, line: line) + } + return value + } + + /// Returns a transformed value or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> Transform.Object { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let value = transform.transformFromJSON(currentValue) else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) + } + return value + } + + /// Returns a RawRepresentable type or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { + return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line) + } + + /// Returns a RawRepresentable type or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T? { + return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line) + } + + /// Returns a `[RawRepresentable]` type or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] { + return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line) + } + + /// Returns a `[RawRepresentable]` type or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T]? { + return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line) + } + + // MARK: BaseMappable + + /// Returns a `BaseMappable` object or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let JSONObject = currentValue else { + throw MapError(key: key, currentValue: currentValue, reason: "Found unexpected nil value", file: file, function: function, line: line) + } + return try Mapper(context: context).mapOrFail(JSONObject: JSONObject) + } + + /// Returns a `BaseMappable` object boxed in `Optional` or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T? { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let JSONObject = currentValue else { + throw MapError(key: key, currentValue: currentValue, reason: "Found unexpected nil value", file: file, function: function, line: line) + } + return try Mapper(context: context).mapOrFail(JSONObject: JSONObject) + } + + // MARK: [BaseMappable] + + /// Returns a `[BaseMappable]` or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonArray = currentValue as? [Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) + } + + return try jsonArray.map { JSONObject -> T in + return try Mapper(context: context).mapOrFail(JSONObject: JSONObject) + } + } + + /// Returns a `[BaseMappable]` boxed in `Optional` or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T]? { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonArray = currentValue as? [Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) + } + + return try jsonArray.map { JSONObject -> T in + return try Mapper(context: context).mapOrFail(JSONObject: JSONObject) + } + } + + /// Returns a `[BaseMappable]` using transform or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [Transform.Object] { + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonArray = currentValue as? [Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) + } + + return try jsonArray.map { json -> Transform.Object in + guard let object = transform.transformFromJSON(json) else { + throw MapError(key: "\(key)", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) + } + return object + } + } + + // MARK: [String: BaseMappable] + + /// Returns a `[String: BaseMappable]` or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: T] { + + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonDictionary = currentValue as? [String: Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) + } + return try jsonDictionary.mapValues { json in + return try Mapper(context: context).mapOrFail(JSONObject: json) + } + } + + /// Returns a `[String: BaseMappable]` boxed in `Optional` or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: T]? { + + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonDictionary = currentValue as? [String: Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) + } + var value: [String: T] = [:] + for (key, json) in jsonDictionary { + value[key] = try Mapper(context: context).mapOrFail(JSONObject: json) + } + return value + } + + /// Returns a `[String: BaseMappable]` using transform or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: Transform.Object] { + + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let jsonDictionary = currentValue as? [String: Any] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) + } + return try jsonDictionary.mapValues { json in + guard let object = transform.transformFromJSON(json) else { + throw MapError(key: key, currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) + } + return object + } + } + + /// Returns a `[String: BaseMappable]` using transform or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [[T]]? { + + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let json2DArray = currentValue as? [[Any]] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'", file: file, function: function, line: line) + } + return try json2DArray.map { jsonArray in + try jsonArray.map { jsonObject -> T in + return try Mapper(context: context).mapOrFail(JSONObject: jsonObject) + } + } + } + + // MARK: [[BaseMappable]] + /// Returns a `[[BaseMappable]]` or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [[T]] { + + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let json2DArray = currentValue as? [[Any]] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'", file: file, function: function, line: line) + } + return try json2DArray.map { jsonArray in + try jsonArray.map { jsonObject -> T in + return try Mapper(context: context).mapOrFail(JSONObject: jsonObject) + } + } + } + + /// Returns a `[[BaseMappable]]` using transform or throws an error. + func value(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [[Transform.Object]] { + + let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) + guard let json2DArray = currentValue as? [[Any]] else { + throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'", + file: file, function: function, line: line) + } + + return try json2DArray.map { jsonArray in + try jsonArray.map { json -> Transform.Object in + guard let object = transform.transformFromJSON(json) else { + throw MapError(key: "\(key)", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) + } + return object + } + } + } +} + +public extension Mapper where N: ImmutableMappable { + + func map(JSON: [String: Any]) throws -> N { + return try self.mapOrFail(JSON: JSON) + } + + func map(JSONString: String) throws -> N { + return try mapOrFail(JSONString: JSONString) + } + + func map(JSONObject: Any) throws -> N { + return try mapOrFail(JSONObject: JSONObject) + } + + // MARK: Array mapping functions + + func mapArray(JSONArray: [[String: Any]]) throws -> [N] { + #if swift(>=4.1) + return try JSONArray.compactMap(mapOrFail) + #else + return try JSONArray.flatMap(mapOrFail) + #endif + } + + func mapArray(JSONString: String) throws -> [N] { + guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { + throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") + } + + return try mapArray(JSONObject: JSONObject) + } + + func mapArray(JSONObject: Any) throws -> [N] { + guard let JSONArray = JSONObject as? [[String: Any]] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[String: Any]]'") + } + + return try mapArray(JSONArray: JSONArray) + } + + // MARK: Dictionary mapping functions + + func mapDictionary(JSONString: String) throws -> [String: N] { + guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { + throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") + } + + return try mapDictionary(JSONObject: JSONObject) + } + + func mapDictionary(JSONObject: Any?) throws -> [String: N] { + guard let JSON = JSONObject as? [String: [String: Any]] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") + } + + return try mapDictionary(JSON: JSON) + } + + func mapDictionary(JSON: [String: [String: Any]]) throws -> [String: N] { + return try JSON.filterMap(mapOrFail) + } + + // MARK: Dictinoary of arrays mapping functions + + func mapDictionaryOfArrays(JSONObject: Any?) throws -> [String: [N]] { + guard let JSON = JSONObject as? [String: [[String: Any]]] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") + } + return try mapDictionaryOfArrays(JSON: JSON) + } + + func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) throws -> [String: [N]] { + return try JSON.filterMap { array -> [N] in + try mapArray(JSONArray: array) + } + } + + // MARK: 2 dimentional array mapping functions + + func mapArrayOfArrays(JSONObject: Any?) throws -> [[N]] { + guard let JSONArray = JSONObject as? [[[String: Any]]] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[[String: Any]]]''") + } + return try JSONArray.map(mapArray) + } + +} + +internal extension Mapper { + + func mapOrFail(JSON: [String: Any]) throws -> N { + let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues) + + // Check if object is ImmutableMappable, if so use ImmutableMappable protocol for mapping + if let klass = N.self as? ImmutableMappable.Type, + var object = try klass.init(map: map) as? N { + object.mapping(map: map) + return object + } + + // If not, map the object the standard way + guard let value = self.map(JSON: JSON) else { + throw MapError(key: nil, currentValue: JSON, reason: "Cannot map to '\(N.self)'") + } + return value + } + + func mapOrFail(JSONString: String) throws -> N { + guard let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) else { + throw MapError(key: nil, currentValue: JSONString, reason: "Cannot parse into '[String: Any]'") + } + return try mapOrFail(JSON: JSON) + } + + func mapOrFail(JSONObject: Any) throws -> N { + guard let JSON = JSONObject as? [String: Any] else { + throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: Any]'") + } + return try mapOrFail(JSON: JSON) + } + +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/IntegerOperators.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/IntegerOperators.swift new file mode 100644 index 0000000..6e548d4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/IntegerOperators.swift @@ -0,0 +1,171 @@ +// +// IntegerOperators.swift +// ObjectMapper +// +// Created by Suyeol Jeon on 17/02/2017. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// MARK: - Signed Integer + +/// SignedInteger mapping +public func <- (left: inout T, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + let value: T = toSignedInteger(right.currentValue) ?? 0 + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +/// Optional SignedInteger mapping +public func <- (left: inout T?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + let value: T? = toSignedInteger(right.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// ImplicitlyUnwrappedOptional SignedInteger mapping +public func <- (left: inout T!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + let value: T! = toSignedInteger(right.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} +#endif + + +// MARK: - Unsigned Integer + +/// UnsignedInteger mapping +public func <- (left: inout T, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + let value: T = toUnsignedInteger(right.currentValue) ?? 0 + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + + +/// Optional UnsignedInteger mapping +public func <- (left: inout T?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + let value: T? = toUnsignedInteger(right.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// ImplicitlyUnwrappedOptional UnsignedInteger mapping +public func <- (left: inout T!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + let value: T! = toUnsignedInteger(right.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} +#endif + +// MARK: - Casting Utils + +/// Convert any value to `SignedInteger`. +private func toSignedInteger(_ value: Any?) -> T? { + guard + let value = value, + case let number as NSNumber = value + else { + return nil + } + + if T.self == Int.self, let x = Int(exactly: number.int64Value) { + return T.init(x) + } + if T.self == Int8.self, let x = Int8(exactly: number.int64Value) { + return T.init(x) + } + if T.self == Int16.self, let x = Int16(exactly: number.int64Value) { + return T.init(x) + } + if T.self == Int32.self, let x = Int32(exactly: number.int64Value) { + return T.init(x) + } + if T.self == Int64.self, let x = Int64(exactly: number.int64Value) { + return T.init(x) + } + + return nil +} + +/// Convert any value to `UnsignedInteger`. +private func toUnsignedInteger(_ value: Any?) -> T? { + guard + let value = value, + case let number as NSNumber = value + else { + return nil + } + + if T.self == UInt.self, let x = UInt(exactly: number.uint64Value) { + return T.init(x) + } + if T.self == UInt8.self, let x = UInt8(exactly: number.uint64Value) { + return T.init(x) + } + if T.self == UInt16.self, let x = UInt16(exactly: number.uint64Value) { + return T.init(x) + } + if T.self == UInt32.self, let x = UInt32(exactly: number.uint64Value) { + return T.init(x) + } + if T.self == UInt64.self, let x = UInt64(exactly: number.uint64Value) { + return T.init(x) + } + + return nil +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Map.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Map.swift new file mode 100644 index 0000000..38dc2a3 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Map.swift @@ -0,0 +1,204 @@ +// +// Map.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +/// MapContext is available for developers who wish to pass information around during the mapping process. +public protocol MapContext { + +} + +/// A class used for holding mapping data +public final class Map { + public let mappingType: MappingType + + public internal(set) var JSON: [String: Any] = [:] + public internal(set) var isKeyPresent = false + public internal(set) var currentValue: Any? + public internal(set) var currentKey: String? + var keyIsNested = false + public internal(set) var nestedKeyDelimiter: String = "." + public var context: MapContext? + public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set. + + public let toObject: Bool // indicates whether the mapping is being applied to an existing object + + public init(mappingType: MappingType, JSON: [String: Any], toObject: Bool = false, context: MapContext? = nil, shouldIncludeNilValues: Bool = false) { + + self.mappingType = mappingType + self.JSON = JSON + self.toObject = toObject + self.context = context + self.shouldIncludeNilValues = shouldIncludeNilValues + } + + /// Sets the current mapper value and key. + /// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects. + public subscript(key: String) -> Map { + // save key and value associated to it + return self.subscript(key: key) + } + + public subscript(key: String, delimiter delimiter: String) -> Map { + return self.subscript(key: key, delimiter: delimiter) + } + + public subscript(key: String, nested nested: Bool) -> Map { + return self.subscript(key: key, nested: nested) + } + + public subscript(key: String, nested nested: Bool, delimiter delimiter: String) -> Map { + return self.subscript(key: key, nested: nested, delimiter: delimiter) + } + + public subscript(key: String, ignoreNil ignoreNil: Bool) -> Map { + return self.subscript(key: key, ignoreNil: ignoreNil) + } + + public subscript(key: String, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> Map { + return self.subscript(key: key, delimiter: delimiter, ignoreNil: ignoreNil) + } + + public subscript(key: String, nested nested: Bool, ignoreNil ignoreNil: Bool) -> Map { + return self.subscript(key: key, nested: nested, ignoreNil: ignoreNil) + } + + public subscript(key: String, nested nested: Bool?, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> Map { + return self.subscript(key: key, nested: nested, delimiter: delimiter, ignoreNil: ignoreNil) + } + + private func `subscript`(key: String, nested: Bool? = nil, delimiter: String = ".", ignoreNil: Bool = false) -> Map { + // save key and value associated to it + currentKey = key + keyIsNested = nested ?? key.contains(delimiter) + nestedKeyDelimiter = delimiter + + if mappingType == .fromJSON { + // check if a value exists for the current key + // do this pre-check for performance reasons + if keyIsNested { + // break down the components of the key that are separated by delimiter + (isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: delimiter)), dictionary: JSON) + } else { + let object = JSON[key] + let isNSNull = object is NSNull + isKeyPresent = isNSNull ? true : object != nil + currentValue = isNSNull ? nil : object + } + + // update isKeyPresent if ignoreNil is true + if ignoreNil && currentValue == nil { + isKeyPresent = false + } + } + + return self + } + + public func value() -> T? { + let value = currentValue as? T + + // Swift 4.1 breaks Float casting from `NSNumber`. So Added extra checks for `Float` `[Float]` and `[String:Float]` + if value == nil && T.self == Float.self { + if let v = currentValue as? NSNumber { + return v.floatValue as? T + } + } else if value == nil && T.self == [Float].self { + if let v = currentValue as? [Double] { + #if swift(>=4.1) + return v.compactMap{ Float($0) } as? T + #else + return v.flatMap{ Float($0) } as? T + #endif + } + } else if value == nil && T.self == [String:Float].self { + if let v = currentValue as? [String:Double] { + return v.mapValues{ Float($0) } as? T + } + } + return value + } +} + +/// Fetch value from JSON dictionary, loop through keyPathComponents until we reach the desired object +private func valueFor(_ keyPathComponents: ArraySlice, dictionary: [String: Any]) -> (Bool, Any?) { + // Implement it as a tail recursive function. + if keyPathComponents.isEmpty { + return (false, nil) + } + + if let keyPath = keyPathComponents.first { + let isTail = keyPathComponents.count == 1 + let object = dictionary[keyPath] + if object is NSNull { + return (isTail, nil) + } else if keyPathComponents.count > 1, let dict = object as? [String: Any] { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, dictionary: dict) + } else if keyPathComponents.count > 1, let array = object as? [Any] { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, array: array) + } else { + return (isTail && object != nil, object) + } + } + + return (false, nil) +} + +/// Fetch value from JSON Array, loop through keyPathComponents them until we reach the desired object +private func valueFor(_ keyPathComponents: ArraySlice, array: [Any]) -> (Bool, Any?) { + // Implement it as a tail recursive function. + + if keyPathComponents.isEmpty { + return (false, nil) + } + + //Try to convert keypath to Int as index + if let keyPath = keyPathComponents.first, + let index = Int(keyPath) , index >= 0 && index < array.count { + + let isTail = keyPathComponents.count == 1 + let object = array[index] + + if object is NSNull { + return (isTail, nil) + } else if keyPathComponents.count > 1, let array = object as? [Any] { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, array: array) + } else if keyPathComponents.count > 1, let dict = object as? [String: Any] { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, dictionary: dict) + } else { + return (isTail, object) + } + } + + return (false, nil) +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/MapError.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/MapError.swift new file mode 100644 index 0000000..9e9736b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/MapError.swift @@ -0,0 +1,68 @@ +// +// MapError.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2016-09-26. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +public struct MapError: Error { + public var key: String? + public var currentValue: Any? + public var reason: String? + public var file: StaticString? + public var function: StaticString? + public var line: UInt? + + public init(key: String?, currentValue: Any?, reason: String?, file: StaticString? = nil, function: StaticString? = nil, line: UInt? = nil) { + self.key = key + self.currentValue = currentValue + self.reason = reason + self.file = file + self.function = function + self.line = line + } +} + +extension MapError: CustomStringConvertible { + + private var location: String? { + guard let file = file, let function = function, let line = line else { return nil } + let fileName = ((String(describing: file).components(separatedBy: "/").last ?? "").components(separatedBy: ".").first ?? "") + return "\(fileName).\(function):\(line)" + } + + public var description: String { + let info: [(String, Any?)] = [ + ("- reason", reason), + ("- location", location), + ("- key", key), + ("- currentValue", currentValue), + ] + let infoString = info.map { "\($0.0): \($0.1 ?? "nil")" }.joined(separator: "\n") + return "Got an error while mapping.\n\(infoString)" + } + +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Mappable.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Mappable.swift new file mode 100644 index 0000000..3be7fc1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Mappable.swift @@ -0,0 +1,136 @@ +// +// Mappable.swift +// ObjectMapper +// +// Created by Scott Hoyt on 10/25/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +/// BaseMappable should not be implemented directly. Mappable or StaticMappable should be used instead +public protocol BaseMappable { + /// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process. + mutating func mapping(map: Map) +} + +public protocol Mappable: BaseMappable { + /// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point + init?(map: Map) +} + +public protocol StaticMappable: BaseMappable { + /// This is function that can be used to: + /// 1) provide an existing cached object to be used for mapping + /// 2) return an object of another class (which conforms to BaseMappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for any given mapping + static func objectForMapping(map: Map) -> BaseMappable? +} + +public extension BaseMappable { + + /// Initializes object from a JSON String + init?(JSONString: String, context: MapContext? = nil) { + if let obj: Self = Mapper(context: context).map(JSONString: JSONString) { + self = obj + } else { + return nil + } + } + + /// Initializes object from a JSON Dictionary + init?(JSON: [String: Any], context: MapContext? = nil) { + if let obj: Self = Mapper(context: context).map(JSON: JSON) { + self = obj + } else { + return nil + } + } + + /// Returns the JSON Dictionary for the object + func toJSON() -> [String: Any] { + return Mapper().toJSON(self) + } + + /// Returns the JSON String for the object + func toJSONString(prettyPrint: Bool = false) -> String? { + return Mapper().toJSONString(self, prettyPrint: prettyPrint) + } +} + +public extension Array where Element: BaseMappable { + + /// Initialize Array from a JSON String + init?(JSONString: String, context: MapContext? = nil) { + if let obj: [Element] = Mapper(context: context).mapArray(JSONString: JSONString) { + self = obj + } else { + return nil + } + } + + /// Initialize Array from a JSON Array + init(JSONArray: [[String: Any]], context: MapContext? = nil) { + let obj: [Element] = Mapper(context: context).mapArray(JSONArray: JSONArray) + self = obj + } + + /// Returns the JSON Array + func toJSON() -> [[String: Any]] { + return Mapper().toJSONArray(self) + } + + /// Returns the JSON String for the object + func toJSONString(prettyPrint: Bool = false) -> String? { + return Mapper().toJSONString(self, prettyPrint: prettyPrint) + } +} + +public extension Set where Element: BaseMappable { + + /// Initializes a set from a JSON String + init?(JSONString: String, context: MapContext? = nil) { + if let obj: Set = Mapper(context: context).mapSet(JSONString: JSONString) { + self = obj + } else { + return nil + } + } + + /// Initializes a set from JSON + init?(JSONArray: [[String: Any]], context: MapContext? = nil) { + guard let obj = Mapper(context: context).mapSet(JSONArray: JSONArray) as Set? else { + return nil + } + self = obj + } + + /// Returns the JSON Set + func toJSON() -> [[String: Any]] { + return Mapper().toJSONSet(self) + } + + /// Returns the JSON String for the object + func toJSONString(prettyPrint: Bool = false) -> String? { + return Mapper().toJSONString(self, prettyPrint: prettyPrint) + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Mapper.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Mapper.swift new file mode 100755 index 0000000..cccbdce --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Mapper.swift @@ -0,0 +1,491 @@ +// +// Mapper.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +public enum MappingType { + case fromJSON + case toJSON +} + +/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects +public final class Mapper { + + public var context: MapContext? + public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set. + + public init(context: MapContext? = nil, shouldIncludeNilValues: Bool = false){ + self.context = context + self.shouldIncludeNilValues = shouldIncludeNilValues + } + + // MARK: Mapping functions that map to an existing object toObject + + /// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is + public func map(JSONObject: Any?, toObject object: N) -> N { + if let JSON = JSONObject as? [String: Any] { + return map(JSON: JSON, toObject: object) + } + + return object + } + + /// Map a JSON string onto an existing object + public func map(JSONString: String, toObject object: N) -> N { + if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { + return map(JSON: JSON, toObject: object) + } + return object + } + + /// Maps a JSON dictionary to an existing object that conforms to Mappable. + /// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject + public func map(JSON: [String: Any], toObject object: N) -> N { + var mutableObject = object + let map = Map(mappingType: .fromJSON, JSON: JSON, toObject: true, context: context, shouldIncludeNilValues: shouldIncludeNilValues) + mutableObject.mapping(map: map) + return mutableObject + } + + //MARK: Mapping functions that create an object + + /// Map a JSON string to an object that conforms to Mappable + public func map(JSONString: String) -> N? { + if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { + return map(JSON: JSON) + } + + return nil + } + + /// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil. + public func map(JSONObject: Any?) -> N? { + if let JSON = JSONObject as? [String: Any] { + return map(JSON: JSON) + } + + return nil + } + + /// Maps a JSON dictionary to an object that conforms to Mappable + public func map(JSON: [String: Any]) -> N? { + let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues) + + if let klass = N.self as? StaticMappable.Type { // Check if object is StaticMappable + if var object = klass.objectForMapping(map: map) as? N { + object.mapping(map: map) + return object + } + } else if let klass = N.self as? Mappable.Type { // Check if object is Mappable + if var object = klass.init(map: map) as? N { + object.mapping(map: map) + return object + } + } else if let klass = N.self as? ImmutableMappable.Type { // Check if object is ImmutableMappable + do { + if var object = try klass.init(map: map) as? N { + object.mapping(map: map) + return object + } + } catch let error { + #if DEBUG + let exception: NSException + if let mapError = error as? MapError { + exception = NSException(name: .init(rawValue: "MapError"), reason: mapError.description, userInfo: nil) + } else { + exception = NSException(name: .init(rawValue: "ImmutableMappableError"), reason: error.localizedDescription, userInfo: nil) + } + exception.raise() + #endif + } + } else { + // Ensure BaseMappable is not implemented directly + assert(false, "BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable") + } + + return nil + } + + // MARK: Mapping functions for Arrays and Dictionaries + + /// Maps a JSON array to an object that conforms to Mappable + public func mapArray(JSONString: String) -> [N]? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + + if let objectArray = mapArray(JSONObject: parsedJSON) { + return objectArray + } + + // failed to parse JSON into array form + // try to parse it into a dictionary and then wrap it in an array + if let object = map(JSONObject: parsedJSON) { + return [object] + } + + return nil + } + + /// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil. + public func mapArray(JSONObject: Any?) -> [N]? { + if let JSONArray = JSONObject as? [[String: Any]] { + return mapArray(JSONArray: JSONArray) + } + + return nil + } + + /// Maps an array of JSON dictionary to an array of Mappable objects + public func mapArray(JSONArray: [[String: Any]]) -> [N] { + // map every element in JSON array to type N + #if swift(>=4.1) + let result = JSONArray.compactMap(map) + #else + let result = JSONArray.flatMap(map) + #endif + return result + } + + /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. + public func mapDictionary(JSONString: String) -> [String: N]? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + return mapDictionary(JSONObject: parsedJSON) + } + + /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. + public func mapDictionary(JSONObject: Any?) -> [String: N]? { + if let JSON = JSONObject as? [String: [String: Any]] { + return mapDictionary(JSON: JSON) + } + + return nil + } + + /// Maps a JSON dictionary of dictionaries to a dictionary of Mappable objects + public func mapDictionary(JSON: [String: [String: Any]]) -> [String: N]? { + // map every value in dictionary to type N + let result = JSON.filterMap(map) + if !result.isEmpty { + return result + } + + return nil + } + + /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. + public func mapDictionary(JSONObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] { + if let JSON = JSONObject as? [String : [String : Any]] { + return mapDictionary(JSON: JSON, toDictionary: dictionary) + } + + return dictionary + } + + /// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappable objects + public func mapDictionary(JSON: [String: [String: Any]], toDictionary dictionary: [String: N]) -> [String: N] { + var mutableDictionary = dictionary + for (key, value) in JSON { + if let object = dictionary[key] { + _ = map(JSON: value, toObject: object) + } else { + mutableDictionary[key] = map(JSON: value) + } + } + + return mutableDictionary + } + + /// Maps a JSON object to a dictionary of arrays of Mappable objects + public func mapDictionaryOfArrays(JSONObject: Any?) -> [String: [N]]? { + if let JSON = JSONObject as? [String: [[String: Any]]] { + return mapDictionaryOfArrays(JSON: JSON) + } + + return nil + } + + ///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects + public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) -> [String: [N]]? { + // map every value in dictionary to type N + let result = JSON.filterMap { + mapArray(JSONArray: $0) + } + + if !result.isEmpty { + return result + } + + return nil + } + + /// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects + public func mapArrayOfArrays(JSONObject: Any?) -> [[N]]? { + if let JSONArray = JSONObject as? [[[String: Any]]] { + let objectArray = JSONArray.map { innerJSONArray in + return mapArray(JSONArray: innerJSONArray) + } + + if !objectArray.isEmpty { + return objectArray + } + } + + return nil + } + + // MARK: Utility functions for converting strings to JSON objects + + /// Convert a JSON String into a Dictionary using NSJSONSerialization + public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + return parsedJSON as? [String: Any] + } + + /// Convert a JSON String into an Object using NSJSONSerialization + public static func parseJSONString(JSONString: String) -> Any? { + let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true) + if let data = data { + let parsedJSON: Any? + do { + parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) + } catch let error { + print(error) + parsedJSON = nil + } + return parsedJSON + } + + return nil + } +} + +extension Mapper { + // MARK: Functions that create model from JSON file + + /// JSON file to Mappable object + /// - parameter JSONfile: Filename + /// - Returns: Mappable object + public func map(JSONfile: String) -> N? { + if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) { + do { + let JSONString = try String(contentsOfFile: path) + do { + return self.map(JSONString: JSONString) + } + } catch { + return nil + } + } + return nil + } + + /// JSON file to Mappable object array + /// - parameter JSONfile: Filename + /// - Returns: Mappable object array + public func mapArray(JSONfile: String) -> [N]? { + if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) { + do { + let JSONString = try String(contentsOfFile: path) + do { + return self.mapArray(JSONString: JSONString) + } + } catch { + return nil + } + } + return nil + } +} + +extension Mapper { + + // MARK: Functions that create JSON from objects + + ///Maps an object that conforms to Mappable to a JSON dictionary + public func toJSON(_ object: N) -> [String: Any] { + var mutableObject = object + let map = Map(mappingType: .toJSON, JSON: [:], context: context, shouldIncludeNilValues: shouldIncludeNilValues) + mutableObject.mapping(map: map) + return map.JSON + } + + ///Maps an array of Objects to an array of JSON dictionaries [[String: Any]] + public func toJSONArray(_ array: [N]) -> [[String: Any]] { + return array.map { + // convert every element in array to JSON dictionary equivalent + self.toJSON($0) + } + } + + ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. + public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] { + return dictionary.map { (arg: (key: String, value: N)) in + // convert every value in dictionary to its JSON dictionary equivalent + return (arg.key, self.toJSON(arg.value)) + } + } + + ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. + public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] { + return dictionary.map { (arg: (key: String, value: [N])) in + // convert every value (array) in dictionary to its JSON dictionary equivalent + return (arg.key, self.toJSONArray(arg.value)) + } + } + + /// Maps an Object to a JSON string with option of pretty formatting + public func toJSONString(_ object: N, prettyPrint: Bool = false) -> String? { + let JSONDict = toJSON(object) + + return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) + } + + /// Maps an array of Objects to a JSON string with option of pretty formatting + public func toJSONString(_ array: [N], prettyPrint: Bool = false) -> String? { + let JSONDict = toJSONArray(array) + + return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) + } + + /// Converts an Object to a JSON string with option of pretty formatting + public static func toJSONString(_ JSONObject: Any, prettyPrint: Bool) -> String? { + let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : [] + if let JSON = Mapper.toJSONData(JSONObject, options: options) { + return String(data: JSON, encoding: String.Encoding.utf8) + } + + return nil + } + + /// Converts an Object to JSON data with options + public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? { + if JSONSerialization.isValidJSONObject(JSONObject) { + let JSONData: Data? + do { + JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options) + } catch let error { + print(error) + JSONData = nil + } + + return JSONData + } + + return nil + } +} + +extension Mapper where N: Hashable { + + /// Maps a JSON array to an object that conforms to Mappable + public func mapSet(JSONString: String) -> Set? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + + if let objectArray = mapArray(JSONObject: parsedJSON) { + return Set(objectArray) + } + + // failed to parse JSON into array form + // try to parse it into a dictionary and then wrap it in an array + if let object = map(JSONObject: parsedJSON) { + return Set([object]) + } + + return nil + } + + /// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil. + public func mapSet(JSONObject: Any?) -> Set? { + if let JSONArray = JSONObject as? [[String: Any]] { + return mapSet(JSONArray: JSONArray) + } + + return nil + } + + /// Maps an Set of JSON dictionary to an array of Mappable objects + public func mapSet(JSONArray: [[String: Any]]) -> Set { + // map every element in JSON array to type N + #if swift(>=4.1) + return Set(JSONArray.compactMap(map)) + #else + return Set(JSONArray.flatMap(map)) + #endif + } + + ///Maps a Set of Objects to a Set of JSON dictionaries [[String : Any]] + public func toJSONSet(_ set: Set) -> [[String: Any]] { + return set.map { + // convert every element in set to JSON dictionary equivalent + self.toJSON($0) + } + } + + /// Maps a set of Objects to a JSON string with option of pretty formatting + public func toJSONString(_ set: Set, prettyPrint: Bool = false) -> String? { + let JSONDict = toJSONSet(set) + + return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) + } +} + +extension Dictionary { + internal func map(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] { + var mapped = [K: V]() + + for element in self { + let newElement = try f(element) + mapped[newElement.0] = newElement.1 + } + + return mapped + } + + internal func map(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] { + var mapped = [K: [V]]() + + for element in self { + let newElement = try f(element) + mapped[newElement.0] = newElement.1 + } + + return mapped + } + + + internal func filterMap(_ f: (Value) throws -> U?) rethrows -> [Key: U] { + var mapped = [Key: U]() + + for (key, value) in self { + if let newValue = try f(value) { + mapped[key] = newValue + } + } + + return mapped + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift new file mode 100644 index 0000000..d06a4b9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift @@ -0,0 +1,52 @@ +// +// TransformOf.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 8/22/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +open class NSDecimalNumberTransform: TransformType { + public typealias Object = NSDecimalNumber + public typealias JSON = String + + public init() {} + + open func transformFromJSON(_ value: Any?) -> NSDecimalNumber? { + if let string = value as? String { + return NSDecimalNumber(string: string) + } else if let number = value as? NSNumber { + return NSDecimalNumber(decimal: number.decimalValue) + } else if let double = value as? Double { + return NSDecimalNumber(floatLiteral: double) + } + return nil + } + + open func transformToJSON(_ value: NSDecimalNumber?) -> String? { + guard let value = value else { return nil } + return value.description + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Operators.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Operators.swift new file mode 100755 index 0000000..2c12c52 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/Operators.swift @@ -0,0 +1,398 @@ +// +// Operators.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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. + +/** +* This file defines a new operator which is used to create a mapping between an object and a JSON key value. +* There is an overloaded operator definition for each type of object that is supported in ObjectMapper. +* This provides a way to add custom logic to handle specific types of objects +*/ + +/// Operator used for defining mappings to and from JSON +infix operator <- + +/// Operator used to define mappings to JSON +infix operator >>> + +// MARK:- Objects with Basic types + +/// Object of Basic type +public func <- (left: inout T, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.basicType(&left, object: right.value()) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: T, right: Map) { + if right.mappingType == .toJSON { + ToJSON.basicType(left, map: right) + } +} + + +/// Optional object of basic type +public func <- (left: inout T?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalBasicType(&left, object: right.value()) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: T?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalBasicType(left, map: right) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped optional object of basic type +public func <- (left: inout T!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalBasicType(&left, object: right.value()) + case .toJSON: + left >>> right + default: () + } +} +#endif + +// MARK:- Mappable Objects - + +/// Object conforming to Mappable +public func <- (left: inout T, right: Map) { + switch right.mappingType { + case .fromJSON: + FromJSON.object(&left, map: right) + case .toJSON: + left >>> right + } +} + +public func >>> (left: T, right: Map) { + if right.mappingType == .toJSON { + ToJSON.object(left, map: right) + } +} + + +/// Optional Mappable objects +public func <- (left: inout T?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObject(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: T?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalObject(left, map: right) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped optional Mappable objects +public func <- (left: inout T!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObject(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} +#endif + +// MARK:- Dictionary of Mappable objects - Dictionary + +/// Dictionary of Mappable objects +public func <- (left: inout Dictionary, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectDictionary(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Dictionary, right: Map) { + if right.mappingType == .toJSON { + ToJSON.objectDictionary(left, map: right) + } +} + + +/// Optional Dictionary of Mappable object +public func <- (left: inout Dictionary?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionary(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Dictionary?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalObjectDictionary(left, map: right) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional Dictionary of Mappable object +public func <- (left: inout Dictionary!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionary(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} +#endif + +/// Dictionary of Mappable objects +public func <- (left: inout Dictionary, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectDictionaryOfArrays(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Dictionary, right: Map) { + if right.mappingType == .toJSON { + ToJSON.objectDictionaryOfArrays(left, map: right) + } +} + +/// Optional Dictionary of Mappable object +public func <- (left: inout Dictionary?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Dictionary?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalObjectDictionaryOfArrays(left, map: right) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional Dictionary of Mappable object +public func <- (left: inout Dictionary!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} +#endif + +// MARK:- Array of Mappable objects - Array + +/// Array of Mappable objects +public func <- (left: inout Array, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array, right: Map) { + if right.mappingType == .toJSON { + ToJSON.objectArray(left, map: right) + } +} + +/// Optional array of Mappable objects +public func <- (left: inout Array?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalObjectArray(left, map: right) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional array of Mappable objects +public func <- (left: inout Array!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} +#endif + +// MARK:- Array of Array of Mappable objects - Array> + +/// Array of Array Mappable objects +public func <- (left: inout Array>, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.twoDimensionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array>, right: Map) { + if right.mappingType == .toJSON { + ToJSON.twoDimensionalObjectArray(left, map: right) + } +} + + +/// Optional array of Mappable objects +public func <- (left:inout Array>?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array>?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalTwoDimensionalObjectArray(left, map: right) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional array of Mappable objects +public func <- (left: inout Array>!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} +#endif + +// MARK:- Set of Mappable objects - Set + +/// Set of Mappable objects +public func <- (left: inout Set, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectSet(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Set, right: Map) { + if right.mappingType == .toJSON { + ToJSON.objectSet(left, map: right) + } +} + + +/// Optional Set of Mappable objects +public func <- (left: inout Set?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectSet(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Set?, right: Map) { + if right.mappingType == .toJSON { + ToJSON.optionalObjectSet(left, map: right) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional Set of Mappable objects +public func <- (left: inout Set!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectSet(&left, map: right) + case .toJSON: + left >>> right + default: () + } +} +#endif diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ToJSON.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ToJSON.swift new file mode 100644 index 0000000..674db27 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/ToJSON.swift @@ -0,0 +1,177 @@ +// +// ToJSON.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-13. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +private func setValue(_ value: Any, map: Map) { + setValue(value, key: map.currentKey!, checkForNestedKeys: map.keyIsNested, delimiter: map.nestedKeyDelimiter, dictionary: &map.JSON) +} + +private func setValue(_ value: Any, key: String, checkForNestedKeys: Bool, delimiter: String, dictionary: inout [String : Any]) { + if checkForNestedKeys { + let keyComponents = ArraySlice(key.components(separatedBy: delimiter).filter { !$0.isEmpty }.map { $0 }) + setValue(value, forKeyPathComponents: keyComponents, dictionary: &dictionary) + } else { + dictionary[key] = value + } +} + +private func setValue(_ value: Any, forKeyPathComponents components: ArraySlice, dictionary: inout [String : Any]) { + guard let head = components.first else { + return + } + + let headAsString = String(head) + if components.count == 1 { + dictionary[headAsString] = value + } else { + var child = dictionary[headAsString] as? [String : Any] ?? [:] + + let tail = components.dropFirst() + setValue(value, forKeyPathComponents: tail, dictionary: &child) + + dictionary[headAsString] = child + } +} + +internal final class ToJSON { + + class func basicType(_ field: N, map: Map) { + if let x = field as Any? , false + || x is NSNumber // Basic types + || x is Bool + || x is Int + || x is Double + || x is Float + || x is String + || x is NSNull + || x is Array // Arrays + || x is Array + || x is Array + || x is Array + || x is Array + || x is Array + || x is Array + || x is Array> + || x is Dictionary // Dictionaries + || x is Dictionary + || x is Dictionary + || x is Dictionary + || x is Dictionary + || x is Dictionary + || x is Dictionary + { + setValue(x, map: map) + } + } + + class func optionalBasicType(_ field: N?, map: Map) { + if let field = field { + basicType(field, map: map) + } else if map.shouldIncludeNilValues { + basicType(NSNull(), map: map) //If BasicType is nil, emit NSNull into the JSON output + } + } + + class func object(_ field: N, map: Map) { + if let result = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSON(field) as Any? { + setValue(result, map: map) + } + } + + class func optionalObject(_ field: N?, map: Map) { + if let field = field { + object(field, map: map) + } else if map.shouldIncludeNilValues { + basicType(NSNull(), map: map) //If field is nil, emit NSNull into the JSON output + } + } + + class func objectArray(_ field: Array, map: Map) { + let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONArray(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectArray(_ field: Array?, map: Map) { + if let field = field { + objectArray(field, map: map) + } + } + + class func twoDimensionalObjectArray(_ field: Array>, map: Map) { + var array = [[[String: Any]]]() + for innerArray in field { + let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONArray(innerArray) + array.append(JSONObjects) + } + setValue(array, map: map) + } + + class func optionalTwoDimensionalObjectArray(_ field: Array>?, map: Map) { + if let field = field { + twoDimensionalObjectArray(field, map: map) + } + } + + class func objectSet(_ field: Set, map: Map) { + let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONSet(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectSet(_ field: Set?, map: Map) { + if let field = field { + objectSet(field, map: map) + } + } + + class func objectDictionary(_ field: Dictionary, map: Map) { + let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONDictionary(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectDictionary(_ field: Dictionary?, map: Map) { + if let field = field { + objectDictionary(field, map: map) + } + } + + class func objectDictionaryOfArrays(_ field: Dictionary, map: Map) { + let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONDictionaryOfArrays(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectDictionaryOfArrays(_ field: Dictionary?, map: Map) { + if let field = field { + objectDictionaryOfArrays(field, map: map) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformOf.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformOf.swift new file mode 100644 index 0000000..6012260 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformOf.swift @@ -0,0 +1,48 @@ +// +// TransformOf.swift +// ObjectMapper +// +// Created by Syo Ikeda on 1/23/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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. + +open class TransformOf: TransformType { + public typealias Object = ObjectType + public typealias JSON = JSONType + + private let fromJSON: (JSONType?) -> ObjectType? + private let toJSON: (ObjectType?) -> JSONType? + + public init(fromJSON: @escaping(JSONType?) -> ObjectType?, toJSON: @escaping(ObjectType?) -> JSONType?) { + self.fromJSON = fromJSON + self.toJSON = toJSON + } + + open func transformFromJSON(_ value: Any?) -> ObjectType? { + return fromJSON(value as? JSONType) + } + + open func transformToJSON(_ value: ObjectType?) -> JSONType? { + return toJSON(value) + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformOperators.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformOperators.swift new file mode 100644 index 0000000..1c55f9b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformOperators.swift @@ -0,0 +1,709 @@ +// +// TransformOperators.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2016-09-26. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// MARK:- Transforms + +/// Object of Basic type with Transform +public func <- (left: inout Transform.Object, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value = transform.transformFromJSON(map.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Transform.Object, right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON { + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + } +} + + +/// Optional object of basic type with Transform +public func <- (left: inout Transform.Object?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Transform.Object?, right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON { + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped optional object of basic type with Transform +public func <- (left: inout Transform.Object!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} +#endif + +/// Array of Basic type with Transform +public func <- (left: inout [Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.basicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: [Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON{ + let values = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + } +} + + +/// Optional array of Basic type with Transform +public func <- (left: inout [Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: [Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON { + let values = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped optional array of Basic type with Transform +public func <- (left: inout [Transform.Object]!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} +#endif + +/// Dictionary of Basic type with Transform +public func <- (left: inout [String: Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) + FromJSON.basicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: [String: Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == . toJSON { + let values = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + } +} + + +/// Optional dictionary of Basic type with Transform +public func <- (left: inout [String: Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: [String: Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON { + let values = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped optional dictionary of Basic type with Transform +public func <- (left: inout [String: Transform.Object]!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + left >>> right + default: () + } +} +#endif + +// MARK:- Transforms of Mappable Objects - + +/// Object conforming to Mappable that have transforms +public func <- (left: inout Transform.Object, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value: Transform.Object? = transform.transformFromJSON(map.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Transform.Object, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + } +} + + +/// Optional Mappable objects that have transforms +public func <- (left: inout Transform.Object?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value: Transform.Object? = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Transform.Object?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON{ + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped optional Mappable objects that have transforms +public func <- (left: inout Transform.Object!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value: Transform.Object? = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + left >>> right + default: () + } +} +#endif + + +// MARK:- Dictionary of Mappable objects with a transform - Dictionary + +/// Dictionary of Mappable objects with a transform +public func <- (left: inout Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, + let object = map.currentValue as? [String: Any] { + let value = fromJSONDictionaryWithTransform(object as Any?, transform: transform) ?? left + FromJSON.basicType(&left, object: value) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let value = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.basicType(value, map: map) + } +} + + +/// Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let object = map.currentValue as? [String : Any]{ + let value = fromJSONDictionaryWithTransform(object as Any?, transform: transform) ?? left + FromJSON.optionalBasicType(&left, object: value) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let value = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(value, map: map) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let dictionary = map.currentValue as? [String : Any]{ + let transformedDictionary = fromJSONDictionaryWithTransform(dictionary as Any?, transform: transform) ?? left + FromJSON.optionalBasicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + left >>> right + } +} +#endif + +/// Dictionary of Mappable objects with a transform +public func <- (left: inout Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if let dictionary = map.currentValue as? [String : [Any]], map.mappingType == .fromJSON && map.isKeyPresent { + let transformedDictionary = dictionary.map { (arg: (key: String, values: [Any])) -> (String, [Transform.Object]) in + let (key, values) = arg + if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { + return (key, jsonArray) + } + if let leftValue = left[key] { + return (key, leftValue) + } + return (key, []) + } + + FromJSON.basicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if map.mappingType == .toJSON { + + let transformedDictionary = left.map { (arg: (key: String, value: [Transform.Object])) in + return (arg.key, toJSONArrayWithTransform(arg.value, transform: transform) ?? []) + } + + ToJSON.basicType(transformedDictionary, map: map) + } +} + + +/// Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if let dictionary = map.currentValue as? [String : [Any]], map.mappingType == .fromJSON && map.isKeyPresent { + + let transformedDictionary = dictionary.map { (arg: (key: String, values: [Any])) -> (String, [Transform.Object]) in + let (key, values) = arg + if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { + return (key, jsonArray) + } + if let leftValue = left?[key] { + return (key, leftValue) + } + return (key, []) + } + + FromJSON.optionalBasicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + left >>> right + } +} + +public func >>> (left: Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if map.mappingType == .toJSON { + let transformedDictionary = left?.map { (arg: (key: String, values: [Transform.Object])) in + return (arg.key, toJSONArrayWithTransform(arg.values, transform: transform) ?? []) + } + + ToJSON.optionalBasicType(transformedDictionary, map: map) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if let dictionary = map.currentValue as? [String : [Any]], map.mappingType == .fromJSON && map.isKeyPresent { + let transformedDictionary = dictionary.map { (arg: (key: String, values: [Any])) -> (String, [Transform.Object]) in + let (key, values) = arg + if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { + return (key, jsonArray) + } + if let leftValue = left?[key] { + return (key, leftValue) + } + return (key, []) + } + FromJSON.optionalBasicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + left >>> right + } +} +#endif + +// MARK:- Array of Mappable objects with transforms - Array + +/// Array of Mappable objects +public func <- (left: inout Array, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: transformedValues) + } + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let transformedValues = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } +} + + +/// Optional array of Mappable objects +public func <- (left: inout Array?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: transformedValues) + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Array?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let transformedValues = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional array of Mappable objects +public func <- (left: inout Array!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: transformedValues) + case .toJSON: + left >>> right + default: () + } +} +#endif + +// MARK:- Array of Array of objects - Array>> with transforms + +/// Array of Array of objects with transform +public func <- (left: inout [[Transform.Object]], right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .toJSON: + left >>> right + case .fromJSON where map.isKeyPresent: + guard let original2DArray = map.currentValue as? [[Any]] else { break } + #if swift(>=4.1) + let transformed2DArray = original2DArray.compactMap { values in + fromJSONArrayWithTransform(values as Any?, transform: transform) + } + #else + let transformed2DArray = original2DArray.flatMap { values in + fromJSONArrayWithTransform(values as Any?, transform: transform) + } + #endif + FromJSON.basicType(&left, object: transformed2DArray) + default: + break + } +} + +public func >>> (left: [[Transform.Object]], right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON{ + #if swift(>=4.1) + let transformed2DArray = left.compactMap { values in + toJSONArrayWithTransform(values, transform: transform) + } + #else + let transformed2DArray = left.flatMap { values in + toJSONArrayWithTransform(values, transform: transform) + } + #endif + ToJSON.basicType(transformed2DArray, map: map) + } +} + +/// Optional array of array of objects with transform +public func <- (left: inout [[Transform.Object]]?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .toJSON: + left >>> right + case .fromJSON where map.isKeyPresent: + guard let original2DArray = map.currentValue as? [[Any]] else { break } + #if swift(>=4.1) + let transformed2DArray = original2DArray.compactMap { values in + fromJSONArrayWithTransform(values as Any?, transform: transform) + } + #else + let transformed2DArray = original2DArray.flatMap { values in + fromJSONArrayWithTransform(values as Any?, transform: transform) + } + #endif + FromJSON.optionalBasicType(&left, object: transformed2DArray) + default: + break + } +} + +public func >>> (left: [[Transform.Object]]?, right: (Map, Transform)) { + let (map, transform) = right + if map.mappingType == .toJSON { + #if swift(>=4.1) + let transformed2DArray = left?.compactMap { values in + toJSONArrayWithTransform(values, transform: transform) + } + #else + let transformed2DArray = left?.flatMap { values in + toJSONArrayWithTransform(values, transform: transform) + } + #endif + ToJSON.optionalBasicType(transformed2DArray, map: map) + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional array of array of objects with transform +public func <- (left: inout [[Transform.Object]]!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .toJSON: + left >>> right + case .fromJSON where map.isKeyPresent: + guard let original2DArray = map.currentValue as? [[Any]] else { break } + #if swift(>=4.1) + let transformed2DArray = original2DArray.compactMap { values in + fromJSONArrayWithTransform(values as Any?, transform: transform) + } + #else + let transformed2DArray = original2DArray.flatMap { values in + fromJSONArrayWithTransform(values as Any?, transform: transform) + } + #endif + FromJSON.optionalBasicType(&left, object: transformed2DArray) + default: + break + } +} +#endif + +// MARK:- Set of Mappable objects with a transform - Set + +/// Set of Mappable objects with transform +public func <- (left: inout Set, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: Set(transformedValues)) + } + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Set, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + let transformedValues = toJSONArrayWithTransform(Array(left), transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } +} + + +/// Optional Set of Mappable objects with transform +public func <- (left: inout Set?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: Set(transformedValues)) + } + case .toJSON: + left >>> right + default: () + } +} + +public func >>> (left: Set?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .toJSON { + if let values = left { + let transformedValues = toJSONArrayWithTransform(Array(values), transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } + } +} + + +// Code targeting the Swift 4.1 compiler and below. +#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) +/// Implicitly unwrapped Optional set of Mappable objects with transform +public func <- (left: inout Set!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: Set(transformedValues)) + } + case .toJSON: + left >>> right + default: () + } +} +#endif + + +private func fromJSONArrayWithTransform(_ input: Any?, transform: Transform) -> [Transform.Object]? { + if let values = input as? [Any] { + #if swift(>=4.1) + return values.compactMap { value in + return transform.transformFromJSON(value) + } + #else + return values.flatMap { value in + return transform.transformFromJSON(value) + } + #endif + } else { + return nil + } +} + +private func fromJSONDictionaryWithTransform(_ input: Any?, transform: Transform) -> [String: Transform.Object]? { + if let values = input as? [String: Any] { + return values.filterMap { value in + return transform.transformFromJSON(value) + } + } else { + return nil + } +} + +private func toJSONArrayWithTransform(_ input: [Transform.Object]?, transform: Transform) -> [Transform.JSON]? { + #if swift(>=4.1) + return input?.compactMap { value in + return transform.transformToJSON(value) + } + #else + return input?.flatMap { value in + return transform.transformToJSON(value) + } + #endif +} + +private func toJSONDictionaryWithTransform(_ input: [String: Transform.Object]?, transform: Transform) -> [String: Transform.JSON]? { + return input?.filterMap { value in + return transform.transformToJSON(value) + } +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformType.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformType.swift new file mode 100644 index 0000000..5daf0d3 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/TransformType.swift @@ -0,0 +1,35 @@ +// +// TransformType.swift +// ObjectMapper +// +// Created by Syo Ikeda on 2/4/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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. + +public protocol TransformType { + associatedtype Object + associatedtype JSON + + func transformFromJSON(_ value: Any?) -> Object? + func transformToJSON(_ value: Object?) -> JSON? +} diff --git a/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/URLTransform.swift b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/URLTransform.swift new file mode 100644 index 0000000..1e8bbb2 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/ObjectMapper/Sources/URLTransform.swift @@ -0,0 +1,67 @@ +// +// URLTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-27. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2018 Tristan Himmelman +// +// 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 + +open class URLTransform: TransformType { + public typealias Object = URL + public typealias JSON = String + private let shouldEncodeURLString: Bool + private let allowedCharacterSet: CharacterSet + + /** + Initializes the URLTransform with an option to encode URL strings before converting them to an NSURL + - parameter shouldEncodeUrlString: when true (the default) the string is encoded before passing + to `NSURL(string:)` + - returns: an initialized transformer + */ + public init(shouldEncodeURLString: Bool = false, allowedCharacterSet: CharacterSet = .urlQueryAllowed) { + self.shouldEncodeURLString = shouldEncodeURLString + self.allowedCharacterSet = allowedCharacterSet + } + + open func transformFromJSON(_ value: Any?) -> URL? { + guard let URLString = value as? String else { return nil } + + if !shouldEncodeURLString { + return URL(string: URLString) + } + + guard let escapedURLString = URLString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) else { + return nil + } + return URL(string: escapedURLString) + } + + open func transformToJSON(_ value: URL?) -> String? { + if let URL = value { + return URL.absoluteString + } + return nil + } +} diff --git a/TesteArenaFelipePerius/Pods/Pods.xcodeproj/project.pbxproj b/TesteArenaFelipePerius/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..f5aa852 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,2178 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 00FA97D56201027AEB1C7692A2C3CF8B /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 132F425C710D251AD251DAD2B49759D7 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 01583BA662A9872D48D28C751D55B24B /* AnyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05630551B1C47397F0F57B7D15F2B2D3 /* AnyObserver.swift */; }; + 029C9E6FF8FC37DF72685033033C31D3 /* BooleanDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8540404B74066C770241ACDF8ED6A38 /* BooleanDisposable.swift */; }; + 02E11AACB509E00F07FC45B073374310 /* EnumTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EA7019CA96E290ECCEC08377988EFD6 /* EnumTransform.swift */; }; + 03B41652C8E7BE6ABBF7A931C33A81D0 /* Single.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9F8E1D25A3D17A41F7BE27BF3AA6D1E /* Single.swift */; }; + 0419772A87B16DB7DCF405A9E77D671F /* Protector.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBDDD5766D916E0F6E7618A8DB9548D3 /* Protector.swift */; }; + 04B703D2FC0FFFAD0115D801C676ABB1 /* DefaultIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = B018235D0A956F9925D1C437EFD00C60 /* DefaultIfEmpty.swift */; }; + 06507A26118BA5ACFBBC8C225776920E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 065597E2268C23FF7EDF2D1246DC8479 /* Validation.swift */; }; + 06FA813F2102B86983243F467562DD9A /* CurrentThreadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE188BD0F74495486CB135BF4AA51CB3 /* CurrentThreadScheduler.swift */; }; + 09844EAB842B1D906B98799F642926D9 /* GroupBy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 790BE6FDA25B6A09CD30D499C6156E3A /* GroupBy.swift */; }; + 0AE06C3AEA6CA45342BA703230ABD2CB /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF19B4632D4A8440CB9D2328E56E9EC1 /* CachedResponseHandler.swift */; }; + 0BF18101F110A610E932C09478C19996 /* CombineLatest.swift in Sources */ = {isa = PBXBuildFile; fileRef = B65E461AC3B3BB42745296F08770B390 /* CombineLatest.swift */; }; + 0C9FD48191A4E68417C886A9BA356C76 /* ISO8601DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5464B189C41224895EFE999411F45595 /* ISO8601DateTransform.swift */; }; + 0CC43FF0E31AA320ACFEB0FE6239DF34 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C4680CD4891286D154A006117883AF0 /* ServerTrustEvaluation.swift */; }; + 0D7A41095DB4717F69E83EB8D9829FD2 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A894C23B148F4B4BA6E517C8E779A4 /* PriorityQueue.swift */; }; + 0E478FF7AD49149E802261DB853A2837 /* DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 732AB1DDEBF13E99AC3F9315786D2716 /* DateTransform.swift */; }; + 0F37E729175217A2CB24F1A8C0B09450 /* InvocableScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96BF26D13245C6034705A668CD49A99 /* InvocableScheduledItem.swift */; }; + 100F129E754B7CB6CF69874F744FB8BC /* Enumerated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FC2AA62D014AF3DE7B108B2DFB9AFF2 /* Enumerated.swift */; }; + 12C557905671AAC56D2DE2477F0F195F /* ObserverType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A14CEE9B85ACC6B27F8780736D7C827 /* ObserverType.swift */; }; + 13183BCA9B70617DE557EC035283629B /* SynchronizedOnType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6DA81C2DED81823F164C621DAF7E481 /* SynchronizedOnType.swift */; }; + 13457FE4E607509A3B9527B0711033D5 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99D90428D3C69D1ADC59A83C946DD77D /* ResponseSerialization.swift */; }; + 13B45E0BEF5335984AF500EDB444E960 /* Throttle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09F157FD187A7931F9B019BB27EFC183 /* Throttle.swift */; }; + 14989A83765C3E0A66D54CBFD69E1FBD /* Delay.swift in Sources */ = {isa = PBXBuildFile; fileRef = A24B2C6BABDA54CFBB2307B84E80E3E4 /* Delay.swift */; }; + 14AB7976E100075ADEA0AB1DB833E72D /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01E6D8652C3829DEF7E8C9EE70D6489C /* ParameterEncoding.swift */; }; + 1614F9A6C8856359C7575D3B2FC46636 /* DeprecationWarner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A6B542FC2EE5DF3C874F2E099CD4004 /* DeprecationWarner.swift */; }; + 1758B42B3C615677A6E694DD81370024 /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81D6453A6D8A1D0614A3A31F412C7C58 /* Queue.swift */; }; + 17953A9CF2E354B3E69B9ABC2F367AD9 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B83491D8D14A60D7BA4DFB5C1190B48 /* AFError.swift */; }; + 19D39D44150CEDA538ADA8F7A2155DE1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + 1A4947A8F9B05CF36DBA9624D34E5401 /* SchedulerServices+Emulation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33F426213A879BAB4E0C792C7D7CB344 /* SchedulerServices+Emulation.swift */; }; + 1BA583010A01C3A7BB60E9D93BDDE18A /* NopDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08F4F9DD3669BC94AE94F621FFB1AC54 /* NopDisposable.swift */; }; + 1C86F4B6C026B119DFA54B3BCC1BCEF3 /* First.swift in Sources */ = {isa = PBXBuildFile; fileRef = 599E942DDCB1E8143E3B313C7AFF4D84 /* First.swift */; }; + 204C11BBCF868CB47451E165BBB8F09E /* Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0BC19FFA55660A72110E94AAABAEEA4 /* Rx.swift */; }; + 217B9CCB60A28B253D351F5F74AFF385 /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C6671CC833F0ECFBA97604500D1304C /* RecursiveLock.swift */; }; + 23A4066ECE04C81C35E644EFADA9E603 /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00904047A0B6B5F5C5618F5DFB73620F /* Producer.swift */; }; + 23AF54AD1F0D53DF49F324BEAB4AE536 /* HistoricalScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E4533C6B8B12FB313D29AA77537EE7C /* HistoricalScheduler.swift */; }; + 255EA947703D90486B8457C4795F71C8 /* StartWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B42D224B226072B630A73517F31CFEE /* StartWith.swift */; }; + 25FBC375CF8486550BC18F88226B494D /* Completable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D871D153D40F1C0A6DE030288D37CC1 /* Completable.swift */; }; + 269449A9477302B3E8929B89D0B6CE6E /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39CC7F0C167EBC05E762AE300A288998 /* Error.swift */; }; + 2D0B12C1BFC22097EFFE1FD784D35D99 /* ObserverBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EC9976069E18F2DB9E07D3FC2D5E32E /* ObserverBase.swift */; }; + 2D417D7B258F09BDFAF9E0B7A9010CB3 /* Repeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDDE738F741A10BC3C028A9163AAA7D7 /* Repeat.swift */; }; + 2F8D6B77C3CF5941C1548FF10CB98FC2 /* AtomicInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = E757C1718FABCBFE69CE45B12E95FD38 /* AtomicInt.swift */; }; + 30B5DB10E2ECBBF929AAA24796A4A4A3 /* ToArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45B1BF11749644F187F48C6CF13E6F3E /* ToArray.swift */; }; + 32497A7570F8F1E079F54D79A4F09C5D /* Concat.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBA3F5031FCFFF645585DC7AB54893E8 /* Concat.swift */; }; + 33E59ADD313BF01CADE082F171772353 /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3D5B0A797F39D4E69264A482C5A008E /* ConnectableObservableType.swift */; }; + 33EC05F4BA313C6C66BC76BD41368178 /* Pods-TesteArenaFelipePeriusTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 1A9C3649B03B036850F3DB4254A9C499 /* Pods-TesteArenaFelipePeriusTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3556C30029720A3AF9CDBF70BE28281C /* FromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEDDC5222BA9C96C2EB140358CD5B191 /* FromJSON.swift */; }; + 35779FE4EBB531F83C97750B228BAC6C /* Materialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4061B34DAE49A1D00275B9BECDAD0CD /* Materialize.swift */; }; + 362A02F50D4398E8645F8247F380A55D /* ObservableConvertibleType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A5C0ECCA57DCF8B449B7BFEB25C4AF /* ObservableConvertibleType.swift */; }; + 375AFA552D7C3CF1014A6A06E13B2FD6 /* Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3A650E4486A1A194EB61292D811F3FF /* Create.swift */; }; + 379123DB108E9E446FA6C4B01CB7E807 /* GroupedObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7A06BD6F2838BB3EBF8AA49D3AB4EFA /* GroupedObservable.swift */; }; + 3C92BA90E647087175525C54F04D66A2 /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9E38172127C8C3307E0F8374AA97FFF /* TailRecursiveSink.swift */; }; + 3D1AFEF6601D082C6044491ECC6AB7DE /* RxSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = DC73DC6D4BB6AFF08661DE40132155A6 /* RxSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3E2F878AB013408C80610FA5201B9364 /* RxMutableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4189A5C33433E4AC00DF0B51BAA060A /* RxMutableBox.swift */; }; + 3F3377FE0D4247A5D9EF803F23B1AC90 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57B4B8E1EAE295EE0E584E53100A3E74 /* Map.swift */; }; + 3F4ED7110D968DE73EA7602071A6135F /* Observable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55DE979328AFFC5F6AFC466F5578F1BB /* Observable.swift */; }; + 3FBC333A1E8AD0550775062381566EBD /* VirtualTimeScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 903BA82990CDCC3ADE2630D8C453BF40 /* VirtualTimeScheduler.swift */; }; + 4082513A35C682F2193D002C80F72B79 /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39C9D76993253B5F0CEBFAB404FB789D /* Result+Alamofire.swift */; }; + 4272E36E41C4EB360E99140A3B296E6D /* Pods-TesteArenaFelipePerius-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7A41162F8C3C8FA29AF02A02EA24EE6E /* Pods-TesteArenaFelipePerius-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 42CDB5C986C78BBC8E5C0185F746CABF /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = CBAAA404AAD7C1FB100BA9BC72AB5ADB /* SessionDelegate.swift */; }; + 4307469BDE7273054C15E2DF200E5EF9 /* Sample.swift in Sources */ = {isa = PBXBuildFile; fileRef = E31807D395D50BEA4B29E9678C4968F3 /* Sample.swift */; }; + 43D34BE64EDEF11DB411C336BB81FE26 /* ConcurrentMainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = A818587F3B438998D75C3206B6FA5060 /* ConcurrentMainScheduler.swift */; }; + 44127C4B989C9CC6A90D78B66A929A5E /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BEFAE140A2E819BD4BFDA6C633869E2 /* AlamofireExtended.swift */; }; + 45EF41171CA52C2B9E61E1CCD69DDAB6 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DFB4157C65F8B387F6D0EEA584B7DAF /* Map.swift */; }; + 4624014FCD87250548822907886E6EE0 /* TakeUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2816CEBAB68E6D7FB5A1D5E3082F6633 /* TakeUntil.swift */; }; + 4627D0E643B7324883728859F3BE00DA /* Switch.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC5B5849E1B70B9D88E89D99C0F70450 /* Switch.swift */; }; + 46A164FD210C579419A49C8C3A5D6E85 /* ShareReplayScope.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B7D504EDF0355844420E2017637EC31 /* ShareReplayScope.swift */; }; + 4893C8F3929377C85421EFBF81F0836B /* AnonymousObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 027B064B6BD670A541E4EEA8C52989B8 /* AnonymousObserver.swift */; }; + 48A99A67AF357300AB3FDEDE730A3CDE /* SwitchIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB94BD0848118D7B40B21DF34217C833 /* SwitchIfEmpty.swift */; }; + 48D97BE7D5CAED273BD2341C239CC934 /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 796ACE5A3DF864A1BD17633C81D84220 /* RequestTaskMap.swift */; }; + 49E6A4598830CE43A67733A511A4562E /* SchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 692333012F46D8ACF7F13618B00574EE /* SchedulerType.swift */; }; + 4B1B70B9BFF1DFF9A3827A62DE72E007 /* SubjectType.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAF72AA1C52553F0770C1B5E10CFBA6B /* SubjectType.swift */; }; + 505B0F0C90CB5F50C87275AFB3A1C505 /* RecursiveScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CDC02B5A7AF49285AE8446C2192F735 /* RecursiveScheduler.swift */; }; + 553A4CA64B6F1A2F3035369860834F6E /* ScheduledDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D9DAC6BE28EF775D686F17F09B31E3C /* ScheduledDisposable.swift */; }; + 553CF23D91DC8777B26191C77938004A /* NSDecimalNumberTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26B57589686C7AC8C1DE9A3AF8331BED /* NSDecimalNumberTransform.swift */; }; + 56EC8ED1535DAB987F3D2B71D4C05773 /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = FED34C56E8E494491B950FDD0415226A /* HTTPHeaders.swift */; }; + 59F8A559BC4FA908AD167B8FAB6BF03E /* String+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AE36D7530CCF0CC0DFFC2C92A070BDF /* String+Rx.swift */; }; + 5A69133161C31B32CE262348245F5185 /* Lock.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF3D62DB66E0AC668845FE27CED20FB1 /* Lock.swift */; }; + 5B44856C3CE5247C723F6DC3C36BEA9B /* Do.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46952D92F910168CA86D53E171AFF6F9 /* Do.swift */; }; + 5BBF8DB12A216FCEDECFDC44B35ED69A /* Catch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79FD2271F0FAA50AC1F7D7ADF072FEB5 /* Catch.swift */; }; + 5BF4C747A56403BA9A8C8CDBB38FDC2E /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09227FBF929065990990D9EB0BF01E1F /* Errors.swift */; }; + 5C4A0685B5A201436AB52EF25829B333 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 582D9D34CF51F6013B76B2784AC01DDD /* MultipartFormData.swift */; }; + 5CED4B1037FE7BF72AD9B1309FB8FCE0 /* Buffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6930208477EB57B0DA3DF041A64EDABB /* Buffer.swift */; }; + 5D12235D061AEE7459279AAF8C348DFE /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = E98D65119505E958C1F3AFF6CB579E2D /* URLEncodedFormEncoder.swift */; }; + 5D61C8ED0DDCC9F8B576B6514B19EE50 /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F384D1CC35F636C57BA266F5FBAF379 /* ParameterEncoder.swift */; }; + 5D7854CB3BAF89CB56DC2FA6FA0F1D7F /* Maybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD4D30752CAAD247C60AB5093038FB02 /* Maybe.swift */; }; + 627FDF2DF14521C18D4F96B9F6026425 /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1DD0CFEB17B0C62B52F56F96B5EB28D /* Scan.swift */; }; + 644BABA965DD85C4049544C4CD1E2C2D /* SerialDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 691AA8A8E6AB1AACFCE481D89EC544FD /* SerialDisposable.swift */; }; + 64C60112E347C8B0F4B70760861FA125 /* EnumOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48EB0B672BB6C6CF7753FD5F271746D7 /* EnumOperators.swift */; }; + 6546BD2ABC8273186A919CFCED10F7D7 /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ACFACFE85EA2C4424C4AA86A47507EF /* Window.swift */; }; + 65F3F57891C3534229655745DB094F1B /* TransformOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A04DDA234877712C9F0762C6458DD6B /* TransformOf.swift */; }; + 664B70329CC935DB023416ADE2F203DC /* DictionaryTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C1F1EAF75944B4DC06D8FBA81B8D3E8 /* DictionaryTransform.swift */; }; + 66FA53FB8682C7667B27C6A7D05AF59B /* Never.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC52318E88738159541DB8D2C9BA753C /* Never.swift */; }; + 69ACE4EEE5A8C1C618B22CC1F7B8EF01 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F44ECA99BF514A9F6C0FD081EC3CC5B /* Session.swift */; }; + 69C532B1143A3F9F849278F81AE995BE /* SynchronizedUnsubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00C6581C996B84EB78C88C2D56364DCC /* SynchronizedUnsubscribeType.swift */; }; + 6A22C46CB1EDE471794D9AB2AC10327F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B453B450B8B7885F02E897CA25DE053 /* Request.swift */; }; + 6B60A21C62A7A0825956F48DADC9B1F7 /* SingleAssignmentDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5516C9C3A8AEE60A4D1095326174EB7A /* SingleAssignmentDisposable.swift */; }; + 6C77ADD177D4C2044395C41F7EC88B0D /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B5136421E833587654400F307680D87 /* Zip.swift */; }; + 6CAEF7E0ECDC028227CFBAB36C77BBD2 /* AsSingle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0533E6E1708F41B39016681E23F6E45D /* AsSingle.swift */; }; + 6DE50875734CBFD27A31861B9A75DB78 /* AsyncSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CF06FED22B98894BE913211374631D8 /* AsyncSubject.swift */; }; + 70517C3BAC2D6614347DEAC15299EB84 /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = A903BB49E3C08E8AFD971367D7309791 /* URLConvertible+URLRequestConvertible.swift */; }; + 706078C52F15B826E0A6271861CACACA /* DispatchQueueConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2F8768D1FAE8DC3C03C6841BF33A4A9 /* DispatchQueueConfiguration.swift */; }; + 72A8589BDBF13A150E97686672A13F7C /* MainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = F54D1DC109571924BB93B9F654959463 /* MainScheduler.swift */; }; + 751F0B27EAFEA469964C97E637FB5207 /* WithLatestFrom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70B8D724F9D3CC76FB194B48D7A16E4E /* WithLatestFrom.swift */; }; + 78BB4BFABCB498A10A06C02661795CDB /* ObjectMapper-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F87F786C32AF9EFCFA59FAFE64254A51 /* ObjectMapper-dummy.m */; }; + 78DF56F844DD301803BA5B2B83807C70 /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55937B8294241DA99AC6F4C9D0F4B74B /* Bag.swift */; }; + 7908F4065CB1E8A38293CE28F4936941 /* Mapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B4DBCA33668769DBB9524E32ABA25CF /* Mapper.swift */; }; + 79664C5564F47E2FEDBE3BB373D6465F /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FA1B497A90ED57D2267B21587D537B5 /* LockOwnerType.swift */; }; + 79C90FE708909D3BCF611A937D9617A8 /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3E0BE15BF87AC678E7C321C6BB49D6C /* ConcurrentDispatchQueueScheduler.swift */; }; + 7B8DD8F89C26F047BECB9B33D593CBB6 /* ObservableType+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F01F6C9F2FDB69AC7AB41530CF26855 /* ObservableType+Extensions.swift */; }; + 7CF8362BA31492053F5CB165637AE117 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A7A3BEBCA40325A9DB81D5DAA02F357 /* NetworkReachabilityManager.swift */; }; + 7DDD4D07E90C163EF747703B7EC692E5 /* TakeWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4989E1CC689571AA7963C048E171CF97 /* TakeWhile.swift */; }; + 817ED2243443BD343BDC1AB8D5FBC2F1 /* AnonymousDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C236D47F7784E793CBE71358D119006 /* AnonymousDisposable.swift */; }; + 83ADD0310D235BAF1EF73EBFCFCBBB50 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + 86D61ED9E92755CAA98639EF12E90D65 /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 674D74EEE8893DA4E5848B2C68943133 /* Operators.swift */; }; + 877DED3B7D9A8F69418663543A063C82 /* BinaryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14BAC6021CA72C08A99A9D2772B154A8 /* BinaryDisposable.swift */; }; + 88D07CE931E093D37F12E8621664B79F /* ObserveOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 409273AACA9F5B31BB8D055343AAD223 /* ObserveOn.swift */; }; + 891A009970AF42E416E8EF1B4A37A4D1 /* Pods-TesteArenaFelipePerius-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A0F6A23D3C138A29DF8BC2E5613ADE5F /* Pods-TesteArenaFelipePerius-dummy.m */; }; + 8A9188BD8F2C0151543C83C1478766DC /* Empty.swift in Sources */ = {isa = PBXBuildFile; fileRef = B576551E0278A4412BD0A7F30D46149B /* Empty.swift */; }; + 8DA5B74F96053B88D81B4C81C4D42C64 /* ToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EF943B51A4C7BBCCF6F35C973EA32B9 /* ToJSON.swift */; }; + 8F41E28B8975B0B1321B110DD3B91ABC /* SkipWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 022008893BA814D48459824C8D7DFC3B /* SkipWhile.swift */; }; + 92811AC5CD9A5004116AE43C4E8FD955 /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3245E0AC2B90CF7AB4B58428AE115158 /* OperationQueue+Alamofire.swift */; }; + 9360D62F6B93BE806FC527217E88C377 /* SkipUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9505124EAAFCA1E0204A3D69DE20E935 /* SkipUntil.swift */; }; + 93C870B6E5F3F8FF3F1E20938F097D3E /* Skip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9986B41980C382CD4C8AE87A739A98F6 /* Skip.swift */; }; + 9436C6A5D04E902A2BC07F12F5B93074 /* OperationQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4052D1C12993269502196752C9861E26 /* OperationQueueScheduler.swift */; }; + 959337D036DC6106477095D6A01F7DB5 /* BehaviorSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = A43CACA05645A0CFABAB493A8EC348DF /* BehaviorSubject.swift */; }; + 96DBFE11AAE27CA46A220B4FB06C355B /* IntegerOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40F5642A9872100F7677F4451F052B11 /* IntegerOperators.swift */; }; + 96EC2785BABA625338A08217F7D7C612 /* Multicast.swift in Sources */ = {isa = PBXBuildFile; fileRef = A31D421772347EE967A949388F5968B7 /* Multicast.swift */; }; + 97A168DFB6DB61770CE2DBF4FD39AA8D /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8B079F294DA5D9A879E6D53A91F51A1E /* CFNetwork.framework */; }; + 9A172E50D23699806F98D5B4DB8452C3 /* ElementAt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E9C68E5EED40E4F454A3FCA2EB3CA61 /* ElementAt.swift */; }; + 9A2E1EA1F0F8F4FA13589FEFC4D712B0 /* HexColorTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C531725F7D4F118D3FBD286BB11F4EA /* HexColorTransform.swift */; }; + 9BDBDE47C9E56453E7DA76F530FDAF4C /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F2DD4F18E82C2C328B3CA26AF8D04C57 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-dummy.m */; }; + 9CF79BEB6FAA6608FEE07BD6EA4C0980 /* SynchronizedDisposeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4BAD7F0792CE98805FDCB1622D610CB /* SynchronizedDisposeType.swift */; }; + 9ECECA1B41F18CE45A4D20709F9A5487 /* AsMaybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8161C450990FCB062E85415DB8A36D0E /* AsMaybe.swift */; }; + 9F73038C5D5809B9C54A4D5455C0CA91 /* MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFE1D1F824F55E0466A6D3C65D84EA94 /* MapError.swift */; }; + A04DFFBEA2D3249F2611754AA265656B /* RetryWhen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 817CE16450B6CAC8BE63A00FE9E84DC0 /* RetryWhen.swift */; }; + A0CC0B62A8116013F2AC5A3B5B426FC8 /* ImmediateSchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02B5E897F0CB63D3297CEA55248FE2B8 /* ImmediateSchedulerType.swift */; }; + A13555F3AEEFACB76A0399A0DF2D9437 /* Take.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C16718DE3239BD8C23495725023BE81 /* Take.swift */; }; + A23B1618251C3B92A365B5669F513796 /* CodableTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBA37BDB12E5A5F00C1D336DAC4F100E /* CodableTransform.swift */; }; + A2BE21A0FE2E363877D5C0F99AA016EE /* SingleAsync.swift in Sources */ = {isa = PBXBuildFile; fileRef = C76A9E7A003958D35B2CA22F341C5054 /* SingleAsync.swift */; }; + A2C4396DDD4292AD59649AD2CD1F1CC0 /* AsyncLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41894FF0368E390C85AE88A5F1D9570F /* AsyncLock.swift */; }; + A35CB412DFB6E16F962F7D2A5E792D5D /* TransformType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07F27815C986A3BE2EDFEE240D71151B /* TransformType.swift */; }; + A57F5F585A08486FA53EEA0EA430FF6F /* DelaySubscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = A773C41F5B970076F9FA23272307FE4B /* DelaySubscription.swift */; }; + A72CEDDB5F5C89EBB49F25267D47FD63 /* CompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B5B8A75FF598B81AD4CF67C2F5FE05E /* CompositeDisposable.swift */; }; + A93F251CEF0CF3B502CEB0D676B91D64 /* Cancelable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FBDBBAF7A0C75EA3CA6943BF73D0E56 /* Cancelable.swift */; }; + A94F4467C6AF8C300477F2EFD03EF690 /* Using.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB6E53D977F6C1371466A03ADCC5CABD /* Using.swift */; }; + AAAD38EB32589BE4DCD548F9C9104993 /* Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FF972698FDFE796BFED7D1405325D36 /* Deprecated.swift */; }; + AB9E672AF3538B811BC7336A1E90659F /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D32E6BE23D99ADB8234E2489F607F65 /* DispatchQueue+Extensions.swift */; }; + ABE620144FCB1B1FD36136A228523714 /* CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7A75F924719AA27A4B299C9697D202B /* CombineLatest+arity.swift */; }; + AC44B54E0896D07BB51B02001C6A7D8D /* Completable+AndThen.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF6A118AC9CBE4E7040B27D37AD55FB2 /* Completable+AndThen.swift */; }; + ACD89BDA0B2CEEB7F7827129B0D8B0CC /* Dematerialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76364568619BB5F3B496E40ED1B023F5 /* Dematerialize.swift */; }; + AD9899986955B2EC1EC20818C860C971 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C47C6E5A4DB55A1DE4ED28144FA37C2C /* RequestInterceptor.swift */; }; + AF92602937CA016548022C600B8CDC16 /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1EFD62A67FF699D1F7E0C308B78F133 /* URLSessionConfiguration+Alamofire.swift */; }; + B025A5FFBDEB6AC4ED3B081EDA03CCA9 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + B1C58F6CED7B3E45170711D9ADF878AF /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 679E7E083A0DF92827FF3A30B0990FA9 /* Alamofire-dummy.m */; }; + B23E9A5CDA31534491226F4C2EE8F8E6 /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E6DB19C9B36871C0CCF5AC9552C1845 /* HTTPMethod.swift */; }; + B2BA9BD5B4D7BA8C1843F756B78D9498 /* SerialDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27DC088C384CBF07DFF7C1F511699937 /* SerialDispatchQueueScheduler.swift */; }; + B2F8BA3DCA0EFF1C69932408402BC0CF /* Pods-TesteArenaFelipePeriusTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = E38F677CA57D2BE0A899DA12A898AEE7 /* Pods-TesteArenaFelipePeriusTests-dummy.m */; }; + B4A09A31159DC4BBD705B24893E7AC38 /* ObjectMapper-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = BD4A9D9A449CE940DF10A0BA19A75320 /* ObjectMapper-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B5EF8C417B25E730F773ADB61221363B /* HistoricalSchedulerTimeConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = D44EB4484EC8CF7EB69AB550530425E4 /* HistoricalSchedulerTimeConverter.swift */; }; + B788B3354CCEBE56DFDB963CAFD7F6C2 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46C546D0A547541B2BBB90FBF9E28361 /* Alamofire.swift */; }; + B8467DE1690C9BE8F1CDFE82E795B10A /* Disposables.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2731D07F74F7CC84230423987D1D9676 /* Disposables.swift */; }; + B899AA8ACE377B6CAF904ECEFE9BA81D /* Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA1C6B6C8EE757807ECE831DD4DC5C70 /* Debug.swift */; }; + B9011BFC91920A46CA122F85720C44EE /* SubscriptionDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3736659527C50D97B6E9F378D721450A /* SubscriptionDisposable.swift */; }; + B94F0C9DD64FFE4C479B3F866B22D879 /* Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7ECB7D39AB45262BEC04CD34738238D6 /* Timeout.swift */; }; + BA2A816A2CDE195F83BBC03AB4671980 /* TransformOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = D303D7C8B44000AD2DAF980BABE1C5DD /* TransformOperators.swift */; }; + BD8BC6D483502E11120900CD34A00632 /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0CE5B9E7B1DD8160EB1F96F53363B76 /* Platform.Linux.swift */; }; + BDD81CA3D510127F62A71ACDB0C59B36 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + BE77AF28ABBCD1A186B56195290331D8 /* Mappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F3DC84FEC32EC10587D6E7AF2FA6DED /* Mappable.swift */; }; + BE82AE980F8C7EE28A6448959194F93A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + BEDA4F82D1D68F7D8ADA400D67C3EAAE /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5BB7D0C25AFFFE678DF279C91688DE9 /* InfiniteSequence.swift */; }; + BF0BC56DB1191B96B14A7E85C762EBD2 /* Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = B06C16E508CD772D68DC2C43DF123865 /* Zip+arity.swift */; }; + BF89CD237E2186816E39AA80FD8AB05D /* DisposeBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65DAFD456DA21256346E561098DD8102 /* DisposeBag.swift */; }; + C51A3EBD74ED98E219BAEA9C5CD6C350 /* DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 968E3B01C04164A6C646FD39FD71060C /* DistinctUntilChanged.swift */; }; + C64AF152F7928CDB59385528DB65FE19 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7C9D422C2A9151F4332BD06ED2415B2 /* RedirectHandler.swift */; }; + C7369563F6946D8984124E1A546B6425 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B2C91000EDE72FA96AADE69DECA0E99 /* Notifications.swift */; }; + C755AA51D790ADF7ABFDC4B1A5417337 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */; }; + C968A9E89E27647D34CFDFCA1BDD65CC /* Range.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDF399874771CD4A3CF72DA907A4B579 /* Range.swift */; }; + C9D795BFFA7E9C3C8D0AEAD6D8919B20 /* PublishSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45ED378E7DE3C601CCA5E72BEC1000CA /* PublishSubject.swift */; }; + CACBD166E573774FB5613C34AA6DA7A7 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38A04CB00C5B9F343A421AE91AD85161 /* EventMonitor.swift */; }; + CC1F3E44843601482FE0BE51EBB2EB77 /* Zip+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BEE1F39CBA1EB1BAAA9321EA31AC88D /* Zip+Collection.swift */; }; + CC2EA5B0EECDC8026FD81FB3612DA3D3 /* Reactive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60597222B888642B62814CB79FDC43D4 /* Reactive.swift */; }; + CC4E41F3DE4EE1DD1FE4874DECC84A1D /* Amb.swift in Sources */ = {isa = PBXBuildFile; fileRef = 935863FF9D4680ED9CDA3E6C9F7C8AB4 /* Amb.swift */; }; + CC55AAEFDD8CD4E969A877137A705316 /* Bag+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFC4027DDCF7D2865261C0C5B10407A1 /* Bag+Rx.swift */; }; + CCFAC36949B2C8DFC1C2C214ED3290F1 /* InvocableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2F6B71C1CE5C52EF6238C2C6E13AFB1 /* InvocableType.swift */; }; + CE7DDCBF7C04B230C8DACC7041151064 /* ObservableType+PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = D76D117F97C7C0FAF41E99829FD48B08 /* ObservableType+PrimitiveSequence.swift */; }; + D196E5F5F8D5565116984ECBD138F28E /* PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD6EFF9C8F9E29739CB011722D97E610 /* PrimitiveSequence.swift */; }; + D206A5C308CA2B0DDCD09429B0036E3B /* Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2881205359308BB68FE148FDC08D9B4 /* Sequence.swift */; }; + D2872BEFA1DCE5EF6F70B768570AE78C /* ReplaySubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CA9411B0831063C70625D754B4918FD /* ReplaySubject.swift */; }; + D29659285A04FF140EA4ED20342CF62D /* RefCountDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31020F43573BCFEC379D55631688F4ED /* RefCountDisposable.swift */; }; + D534CEA49AB76E0432965963395D0C25 /* Deferred.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4C1D1D9CBA7932E3ECFF1AA1BDEE6C8 /* Deferred.swift */; }; + D6B2983389480F48F27A0704EEB5DC81 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 414487C576DA387BEEDAF09970D03458 /* RetryPolicy.swift */; }; + D6E7F973C8A561ADA044C0FFE052FA1B /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8690EF8A2CD143E8A869D8A89C2B0C10 /* Platform.Darwin.swift */; }; + D78C9A5F2CB1916E38F9B4F12073D465 /* CombineLatest+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2AC3CD5257A8791A2965A1E98BD7E50 /* CombineLatest+Collection.swift */; }; + D8E2A362C1777E5DDE88297B7F04A02D /* Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C5F866D63DAF6917AC5D38F74CF5F24 /* Reduce.swift */; }; + DB34CB2BAD36A15A2DD37261D3916E57 /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1909ACFAAEC1EA873AEAF254E101F56C /* Timer.swift */; }; + DD9A097C36C3873144EA020049CF4F96 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 42F33AEDBA4FA13CC573232F8EC7241C /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DEC346A5B91D097E6226E81CD5454D42 /* VirtualTimeConverterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52B63C781391EC69A5BA9191594634EC /* VirtualTimeConverterType.swift */; }; + DF1B93A09C32A648C5FEA29F04BBEB35 /* Generate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8724F43767BBBA66EFB90F21A154B1CA /* Generate.swift */; }; + E07BD425C4EA9ADF15DDFCDB10D0B2FB /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2945668794E05C643879F7DBC20A4DA /* MultipartUpload.swift */; }; + E34BC8E5000420228B970B7E2C1D3E10 /* ScheduledItemType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B0B0A09DCF2F8286D9627662951535A /* ScheduledItemType.swift */; }; + E3CCA9E0385E9002C620F447E376EC7B /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 740A5CC58B2602CE3DB35BDCDA67EC5F /* Sink.swift */; }; + E4E12208D5246E64B7E6CCAE987ADB03 /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F70625D7742C9748020E1CADB9B9760A /* URLRequest+Alamofire.swift */; }; + E51871737E176D0F5174853EC7496C7E /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C9058C31F712D8D4374186649CA91EB /* Filter.swift */; }; + E6EAE8A2A8AEF8E4D3A826EB3DFDEDF0 /* DisposeBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF974B707B8856787A86858D8961A163 /* DisposeBase.swift */; }; + E7522A2CA21238B3F43E11CA85CB0824 /* TakeLast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2158C38A5A19AF81CCB3ED036F3ABEFA /* TakeLast.swift */; }; + E85C75B6E6D960ABF56E2010726A9B22 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D6A4BA05C1099F4CF270927BCBB72B7 /* Optional.swift */; }; + E89448038F1372265827DA3C69762228 /* Event.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FB0557BA1CE18DF5C9902469D09217E /* Event.swift */; }; + E9A5AC2F471699CCA516952A5FEB990B /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3EA162FEFA4906591F1C8EA25EB57AE /* DispatchQueue+Alamofire.swift */; }; + EB2E92AFE8E36A23EE6D311736B88B67 /* DataTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B47E95A235609E280F072BC3291023F /* DataTransform.swift */; }; + EC403B493DA9E0F0531C3270D32DA78C /* SwiftSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = C952B8243DC3C84AA149D14F8D7898E9 /* SwiftSupport.swift */; }; + EEBEFFF677DA6233893B89A14D78CC7A /* PrimitiveSequence+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = B75C56715E3260866E5BF0FEBBFED28F /* PrimitiveSequence+Zip+arity.swift */; }; + F000D6CA12F7C477EC63335B91707775 /* URLTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E247EF10108B6DACEA3E0A15CBCCA98 /* URLTransform.swift */; }; + F0F964DC2104A764E6E3B5CA0C2DC31E /* RxSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7164490DADD9AA8811854DBFBBAEEAEA /* RxSwift-dummy.m */; }; + F1BE6785A54BCB788F60491011A8DCD6 /* Disposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D66D82F0346E1BF9EEB8702CE38C0B5 /* Disposable.swift */; }; + F215D3929BDA35D18695E2BA2230A644 /* ScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE92B26C78050C12F31F4D5E482C6402 /* ScheduledItem.swift */; }; + F230322D5145458A896ED7D641D19E64 /* AddRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE8D4760E6677D810C691228146DB07D /* AddRef.swift */; }; + F2597F9634495618EAD07B49183CA90E /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1734BC5F355FB8FD60403932BE56BD2 /* Merge.swift */; }; + F2CA9FD6E3A7EFBB13BCEF662D06524B /* CustomDateFormatTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A15E924662B8326AEA62629DF948340 /* CustomDateFormatTransform.swift */; }; + F43AE958AC1430231576F1D88BBF7D56 /* Debounce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77044C5E67A4BFF8C81DA6AE7BA0C24F /* Debounce.swift */; }; + F60975556A37AD5647ED82DC76E9CF6F /* DateFormatterTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D55FFB7C4CA782689A14B7246C98F22 /* DateFormatterTransform.swift */; }; + F6E5DFA17B33C90BB4B73B8E83E12A3D /* ObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8CC8D54B78433348E75EC56A9861B2B /* ObservableType.swift */; }; + F70AB95F5AF01EBE987FADC4CECBAD9B /* SubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1850B8DA95E3B70153244A58914A5A9 /* SubscribeOn.swift */; }; + F71789DC91A75033EFB79DB828676451 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19FC3485EA64DD83DC858125494D728D /* Response.swift */; }; + F749D5A6764A29C5C6614B3DEE95CD3A /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6F9F164C5F49586D3C447374D1AA6DD /* Just.swift */; }; + F9B31EED95B0E98A057B6012F9883DCF /* ImmutableMappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F35157C78A40E0B855565E46643C35C1 /* ImmutableMappable.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 13CD5DF3EAF6E05DC555C1C3A436AD21 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 162E649F50FEC62B61BDD87D1BD422B4; + remoteInfo = ObjectMapper; + }; + 215A64B1AF5EC90AF2ECB0294BA26BE1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + 2C7C3C60706C1FC2B104266E6FDE8F81 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + 47FB802B4F6F8C7DC36269145B9EFA52 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + 756B3B9D4245827E7CDADF93DFE9EBAE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + BF2CD561EC320D8224A3824ECF4E71E1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 162E649F50FEC62B61BDD87D1BD422B4; + remoteInfo = ObjectMapper; + }; + C8A2EAC0144968ED0493F92679375379 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9EADA57C421A18B89B0E0CBCDBF2E9A7; + remoteInfo = "Pods-TesteArenaFelipePerius"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 00904047A0B6B5F5C5618F5DFB73620F /* Producer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Producer.swift; path = RxSwift/Observables/Producer.swift; sourceTree = ""; }; + 00C6581C996B84EB78C88C2D56364DCC /* SynchronizedUnsubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedUnsubscribeType.swift; path = RxSwift/Concurrency/SynchronizedUnsubscribeType.swift; sourceTree = ""; }; + 01E6D8652C3829DEF7E8C9EE70D6489C /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 022008893BA814D48459824C8D7DFC3B /* SkipWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipWhile.swift; path = RxSwift/Observables/SkipWhile.swift; sourceTree = ""; }; + 027B064B6BD670A541E4EEA8C52989B8 /* AnonymousObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObserver.swift; path = RxSwift/Observers/AnonymousObserver.swift; sourceTree = ""; }; + 02B5E897F0CB63D3297CEA55248FE2B8 /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateSchedulerType.swift; path = RxSwift/ImmediateSchedulerType.swift; sourceTree = ""; }; + 0533E6E1708F41B39016681E23F6E45D /* AsSingle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsSingle.swift; path = RxSwift/Observables/AsSingle.swift; sourceTree = ""; }; + 05630551B1C47397F0F57B7D15F2B2D3 /* AnyObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyObserver.swift; path = RxSwift/AnyObserver.swift; sourceTree = ""; }; + 065597E2268C23FF7EDF2D1246DC8479 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 07F27815C986A3BE2EDFEE240D71151B /* TransformType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformType.swift; path = Sources/TransformType.swift; sourceTree = ""; }; + 08F4F9DD3669BC94AE94F621FFB1AC54 /* NopDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NopDisposable.swift; path = RxSwift/Disposables/NopDisposable.swift; sourceTree = ""; }; + 09227FBF929065990990D9EB0BF01E1F /* Errors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Errors.swift; path = RxSwift/Errors.swift; sourceTree = ""; }; + 09F157FD187A7931F9B019BB27EFC183 /* Throttle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Throttle.swift; path = RxSwift/Observables/Throttle.swift; sourceTree = ""; }; + 0C5F866D63DAF6917AC5D38F74CF5F24 /* Reduce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reduce.swift; path = RxSwift/Observables/Reduce.swift; sourceTree = ""; }; + 0FBDBBAF7A0C75EA3CA6943BF73D0E56 /* Cancelable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancelable.swift; path = RxSwift/Cancelable.swift; sourceTree = ""; }; + 132F425C710D251AD251DAD2B49759D7 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 14BAC6021CA72C08A99A9D2772B154A8 /* BinaryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BinaryDisposable.swift; path = RxSwift/Disposables/BinaryDisposable.swift; sourceTree = ""; }; + 15A5C0ECCA57DCF8B449B7BFEB25C4AF /* ObservableConvertibleType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableConvertibleType.swift; path = RxSwift/ObservableConvertibleType.swift; sourceTree = ""; }; + 1909ACFAAEC1EA873AEAF254E101F56C /* Timer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timer.swift; path = RxSwift/Observables/Timer.swift; sourceTree = ""; }; + 19FC3485EA64DD83DC858125494D728D /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 1A6B542FC2EE5DF3C874F2E099CD4004 /* DeprecationWarner.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DeprecationWarner.swift; path = Platform/DeprecationWarner.swift; sourceTree = ""; }; + 1A9C3649B03B036850F3DB4254A9C499 /* Pods-TesteArenaFelipePeriusTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-TesteArenaFelipePeriusTests-umbrella.h"; sourceTree = ""; }; + 1B42D224B226072B630A73517F31CFEE /* StartWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StartWith.swift; path = RxSwift/Observables/StartWith.swift; sourceTree = ""; }; + 1D55FFB7C4CA782689A14B7246C98F22 /* DateFormatterTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DateFormatterTransform.swift; path = Sources/DateFormatterTransform.swift; sourceTree = ""; }; + 2158C38A5A19AF81CCB3ED036F3ABEFA /* TakeLast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeLast.swift; path = RxSwift/Observables/TakeLast.swift; sourceTree = ""; }; + 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 23C9A9A7C17F31975331A93988967881 /* Pods-TesteArenaFelipePeriusTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TesteArenaFelipePeriusTests-acknowledgements.plist"; sourceTree = ""; }; + 25696832ECA3AF6FBA021162CD9DC53E /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 26B57589686C7AC8C1DE9A3AF8331BED /* NSDecimalNumberTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NSDecimalNumberTransform.swift; path = Sources/NSDecimalNumberTransform.swift; sourceTree = ""; }; + 2731D07F74F7CC84230423987D1D9676 /* Disposables.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposables.swift; path = RxSwift/Disposables/Disposables.swift; sourceTree = ""; }; + 27DC088C384CBF07DFF7C1F511699937 /* SerialDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDispatchQueueScheduler.swift; path = RxSwift/Schedulers/SerialDispatchQueueScheduler.swift; sourceTree = ""; }; + 2816CEBAB68E6D7FB5A1D5E3082F6633 /* TakeUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeUntil.swift; path = RxSwift/Observables/TakeUntil.swift; sourceTree = ""; }; + 2A14CEE9B85ACC6B27F8780736D7C827 /* ObserverType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverType.swift; path = RxSwift/ObserverType.swift; sourceTree = ""; }; + 2B453B450B8B7885F02E897CA25DE053 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 2B47E95A235609E280F072BC3291023F /* DataTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataTransform.swift; path = Sources/DataTransform.swift; sourceTree = ""; }; + 2C7FE134A06BB710C0240058346388D2 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig"; sourceTree = ""; }; + 2E4533C6B8B12FB313D29AA77537EE7C /* HistoricalScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalScheduler.swift; path = RxSwift/Schedulers/HistoricalScheduler.swift; sourceTree = ""; }; + 301FB963ABEB224516EDC5C6B6507417 /* ObjectMapper.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = ObjectMapper.modulemap; sourceTree = ""; }; + 302E410C85087CA7C26E35FD48A1E509 /* Pods-TesteArenaFelipePerius-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-TesteArenaFelipePerius-acknowledgements.markdown"; sourceTree = ""; }; + 31020F43573BCFEC379D55631688F4ED /* RefCountDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCountDisposable.swift; path = RxSwift/Disposables/RefCountDisposable.swift; sourceTree = ""; }; + 3245E0AC2B90CF7AB4B58428AE115158 /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "OperationQueue+Alamofire.swift"; path = "Source/OperationQueue+Alamofire.swift"; sourceTree = ""; }; + 33F426213A879BAB4E0C792C7D7CB344 /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerServices+Emulation.swift"; path = "RxSwift/Schedulers/SchedulerServices+Emulation.swift"; sourceTree = ""; }; + 3736659527C50D97B6E9F378D721450A /* SubscriptionDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscriptionDisposable.swift; path = RxSwift/Disposables/SubscriptionDisposable.swift; sourceTree = ""; }; + 38A04CB00C5B9F343A421AE91AD85161 /* EventMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventMonitor.swift; path = Source/EventMonitor.swift; sourceTree = ""; }; + 39C9D76993253B5F0CEBFAB404FB789D /* Result+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Result+Alamofire.swift"; path = "Source/Result+Alamofire.swift"; sourceTree = ""; }; + 39CC7F0C167EBC05E762AE300A288998 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RxSwift/Observables/Error.swift; sourceTree = ""; }; + 3A04DDA234877712C9F0762C6458DD6B /* TransformOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformOf.swift; path = Sources/TransformOf.swift; sourceTree = ""; }; + 3ACFACFE85EA2C4424C4AA86A47507EF /* Window.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Window.swift; path = RxSwift/Observables/Window.swift; sourceTree = ""; }; + 3AE36D7530CCF0CC0DFFC2C92A070BDF /* String+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Rx.swift"; path = "RxSwift/Extensions/String+Rx.swift"; sourceTree = ""; }; + 3C4680CD4891286D154A006117883AF0 /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustEvaluation.swift; path = Source/ServerTrustEvaluation.swift; sourceTree = ""; }; + 3CF06FED22B98894BE913211374631D8 /* AsyncSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncSubject.swift; path = RxSwift/Subjects/AsyncSubject.swift; sourceTree = ""; }; + 3FF972698FDFE796BFED7D1405325D36 /* Deprecated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deprecated.swift; path = RxSwift/Deprecated.swift; sourceTree = ""; }; + 4052D1C12993269502196752C9861E26 /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OperationQueueScheduler.swift; path = RxSwift/Schedulers/OperationQueueScheduler.swift; sourceTree = ""; }; + 409273AACA9F5B31BB8D055343AAD223 /* ObserveOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOn.swift; path = RxSwift/Observables/ObserveOn.swift; sourceTree = ""; }; + 40F5642A9872100F7677F4451F052B11 /* IntegerOperators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = IntegerOperators.swift; path = Sources/IntegerOperators.swift; sourceTree = ""; }; + 414487C576DA387BEEDAF09970D03458 /* RetryPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryPolicy.swift; path = Source/RetryPolicy.swift; sourceTree = ""; }; + 41894FF0368E390C85AE88A5F1D9570F /* AsyncLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncLock.swift; path = RxSwift/Concurrency/AsyncLock.swift; sourceTree = ""; }; + 42F33AEDBA4FA13CC573232F8EC7241C /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-umbrella.h"; sourceTree = ""; }; + 43A85B5D792CC4BF1B54B76B0F8C90DB /* ObjectMapper-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ObjectMapper-Info.plist"; sourceTree = ""; }; + 45B1BF11749644F187F48C6CF13E6F3E /* ToArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToArray.swift; path = RxSwift/Observables/ToArray.swift; sourceTree = ""; }; + 45ED378E7DE3C601CCA5E72BEC1000CA /* PublishSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishSubject.swift; path = RxSwift/Subjects/PublishSubject.swift; sourceTree = ""; }; + 46952D92F910168CA86D53E171AFF6F9 /* Do.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Do.swift; path = RxSwift/Observables/Do.swift; sourceTree = ""; }; + 46C546D0A547541B2BBB90FBF9E28361 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 48EB0B672BB6C6CF7753FD5F271746D7 /* EnumOperators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EnumOperators.swift; path = Sources/EnumOperators.swift; sourceTree = ""; }; + 4989E1CC689571AA7963C048E171CF97 /* TakeWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeWhile.swift; path = RxSwift/Observables/TakeWhile.swift; sourceTree = ""; }; + 4A7A3BEBCA40325A9DB81D5DAA02F357 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 4B2C91000EDE72FA96AADE69DECA0E99 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 4E23D83A1B3AF9552D60EAE3F2D3B295 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.release.xcconfig"; sourceTree = ""; }; + 4E247EF10108B6DACEA3E0A15CBCCA98 /* URLTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLTransform.swift; path = Sources/URLTransform.swift; sourceTree = ""; }; + 4EF943B51A4C7BBCCF6F35C973EA32B9 /* ToJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToJSON.swift; path = Sources/ToJSON.swift; sourceTree = ""; }; + 4F44ECA99BF514A9F6C0FD081EC3CC5B /* Session.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Session.swift; path = Source/Session.swift; sourceTree = ""; }; + 52B63C781391EC69A5BA9191594634EC /* VirtualTimeConverterType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeConverterType.swift; path = RxSwift/Schedulers/VirtualTimeConverterType.swift; sourceTree = ""; }; + 5464B189C41224895EFE999411F45595 /* ISO8601DateTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ISO8601DateTransform.swift; path = Sources/ISO8601DateTransform.swift; sourceTree = ""; }; + 5516C9C3A8AEE60A4D1095326174EB7A /* SingleAssignmentDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAssignmentDisposable.swift; path = RxSwift/Disposables/SingleAssignmentDisposable.swift; sourceTree = ""; }; + 55937B8294241DA99AC6F4C9D0F4B74B /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + 55DE979328AFFC5F6AFC466F5578F1BB /* Observable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Observable.swift; path = RxSwift/Observable.swift; sourceTree = ""; }; + 57B4B8E1EAE295EE0E584E53100A3E74 /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = RxSwift/Observables/Map.swift; sourceTree = ""; }; + 582D9D34CF51F6013B76B2784AC01DDD /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 58FDC708B22982364157B9397EA526EA /* Pods-TesteArenaFelipePeriusTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TesteArenaFelipePeriusTests-Info.plist"; sourceTree = ""; }; + 599E942DDCB1E8143E3B313C7AFF4D84 /* First.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = First.swift; path = RxSwift/Observables/First.swift; sourceTree = ""; }; + 5B0B0A09DCF2F8286D9627662951535A /* ScheduledItemType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItemType.swift; path = RxSwift/Schedulers/Internal/ScheduledItemType.swift; sourceTree = ""; }; + 5B5B8A75FF598B81AD4CF67C2F5FE05E /* CompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositeDisposable.swift; path = RxSwift/Disposables/CompositeDisposable.swift; sourceTree = ""; }; + 5B83491D8D14A60D7BA4DFB5C1190B48 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + 5C6671CC833F0ECFBA97604500D1304C /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5E77241F9605B8A7F83DF2DB34F77071 /* Pods-TesteArenaFelipePerius-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TesteArenaFelipePerius-acknowledgements.plist"; sourceTree = ""; }; + 5F384D1CC35F636C57BA266F5FBAF379 /* ParameterEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoder.swift; path = Source/ParameterEncoder.swift; sourceTree = ""; }; + 5F3DC84FEC32EC10587D6E7AF2FA6DED /* Mappable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Mappable.swift; path = Sources/Mappable.swift; sourceTree = ""; }; + 5FB0557BA1CE18DF5C9902469D09217E /* Event.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Event.swift; path = RxSwift/Event.swift; sourceTree = ""; }; + 5FC2AA62D014AF3DE7B108B2DFB9AFF2 /* Enumerated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Enumerated.swift; path = RxSwift/Observables/Enumerated.swift; sourceTree = ""; }; + 60597222B888642B62814CB79FDC43D4 /* Reactive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reactive.swift; path = RxSwift/Reactive.swift; sourceTree = ""; }; + 65DAFD456DA21256346E561098DD8102 /* DisposeBag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBag.swift; path = RxSwift/Disposables/DisposeBag.swift; sourceTree = ""; }; + 674D74EEE8893DA4E5848B2C68943133 /* Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Operators.swift; path = Sources/Operators.swift; sourceTree = ""; }; + 679E7E083A0DF92827FF3A30B0990FA9 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 684127AE06A9196946D34747A4DF3EE6 /* Pods-TesteArenaFelipePerius.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TesteArenaFelipePerius.debug.xcconfig"; sourceTree = ""; }; + 691AA8A8E6AB1AACFCE481D89EC544FD /* SerialDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDisposable.swift; path = RxSwift/Disposables/SerialDisposable.swift; sourceTree = ""; }; + 692333012F46D8ACF7F13618B00574EE /* SchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SchedulerType.swift; path = RxSwift/SchedulerType.swift; sourceTree = ""; }; + 6930208477EB57B0DA3DF041A64EDABB /* Buffer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Buffer.swift; path = RxSwift/Observables/Buffer.swift; sourceTree = ""; }; + 6B41D078EEA17D635B974F06337C94AB /* Pods-TesteArenaFelipePeriusTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TesteArenaFelipePeriusTests.release.xcconfig"; sourceTree = ""; }; + 6BEE1F39CBA1EB1BAAA9321EA31AC88D /* Zip+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+Collection.swift"; path = "RxSwift/Observables/Zip+Collection.swift"; sourceTree = ""; }; + 6C236D47F7784E793CBE71358D119006 /* AnonymousDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousDisposable.swift; path = RxSwift/Disposables/AnonymousDisposable.swift; sourceTree = ""; }; + 6C531725F7D4F118D3FBD286BB11F4EA /* HexColorTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HexColorTransform.swift; path = Sources/HexColorTransform.swift; sourceTree = ""; }; + 6D66D82F0346E1BF9EEB8702CE38C0B5 /* Disposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposable.swift; path = RxSwift/Disposable.swift; sourceTree = ""; }; + 6D6A4BA05C1099F4CF270927BCBB72B7 /* Optional.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Optional.swift; path = RxSwift/Observables/Optional.swift; sourceTree = ""; }; + 6E9C68E5EED40E4F454A3FCA2EB3CA61 /* ElementAt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ElementAt.swift; path = RxSwift/Observables/ElementAt.swift; sourceTree = ""; }; + 6EC9976069E18F2DB9E07D3FC2D5E32E /* ObserverBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverBase.swift; path = RxSwift/Observers/ObserverBase.swift; sourceTree = ""; }; + 6FA1B497A90ED57D2267B21587D537B5 /* LockOwnerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LockOwnerType.swift; path = RxSwift/Concurrency/LockOwnerType.swift; sourceTree = ""; }; + 70B8D724F9D3CC76FB194B48D7A16E4E /* WithLatestFrom.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithLatestFrom.swift; path = RxSwift/Observables/WithLatestFrom.swift; sourceTree = ""; }; + 7164490DADD9AA8811854DBFBBAEEAEA /* RxSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxSwift-dummy.m"; sourceTree = ""; }; + 732AB1DDEBF13E99AC3F9315786D2716 /* DateTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DateTransform.swift; path = Sources/DateTransform.swift; sourceTree = ""; }; + 740A5CC58B2602CE3DB35BDCDA67EC5F /* Sink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sink.swift; path = RxSwift/Observables/Sink.swift; sourceTree = ""; }; + 76364568619BB5F3B496E40ED1B023F5 /* Dematerialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Dematerialize.swift; path = RxSwift/Observables/Dematerialize.swift; sourceTree = ""; }; + 77044C5E67A4BFF8C81DA6AE7BA0C24F /* Debounce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debounce.swift; path = RxSwift/Observables/Debounce.swift; sourceTree = ""; }; + 790BE6FDA25B6A09CD30D499C6156E3A /* GroupBy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupBy.swift; path = RxSwift/Observables/GroupBy.swift; sourceTree = ""; }; + 796ACE5A3DF864A1BD17633C81D84220 /* RequestTaskMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTaskMap.swift; path = Source/RequestTaskMap.swift; sourceTree = ""; }; + 79FD2271F0FAA50AC1F7D7ADF072FEB5 /* Catch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catch.swift; path = RxSwift/Observables/Catch.swift; sourceTree = ""; }; + 7A41162F8C3C8FA29AF02A02EA24EE6E /* Pods-TesteArenaFelipePerius-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-TesteArenaFelipePerius-umbrella.h"; sourceTree = ""; }; + 7B5136421E833587654400F307680D87 /* Zip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zip.swift; path = RxSwift/Observables/Zip.swift; sourceTree = ""; }; + 7C7B176505F1DDC75AD4F887EF2440ED /* Pods-TesteArenaFelipePerius.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TesteArenaFelipePerius.release.xcconfig"; sourceTree = ""; }; + 7CDC02B5A7AF49285AE8446C2192F735 /* RecursiveScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveScheduler.swift; path = RxSwift/Schedulers/RecursiveScheduler.swift; sourceTree = ""; }; + 7E68DF55DEB7CD02DE5158370E9FA864 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.modulemap"; sourceTree = ""; }; + 7ECB7D39AB45262BEC04CD34738238D6 /* Timeout.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeout.swift; path = RxSwift/Observables/Timeout.swift; sourceTree = ""; }; + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxSwift.framework; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8161C450990FCB062E85415DB8A36D0E /* AsMaybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsMaybe.swift; path = RxSwift/Observables/AsMaybe.swift; sourceTree = ""; }; + 817CE16450B6CAC8BE63A00FE9E84DC0 /* RetryWhen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryWhen.swift; path = RxSwift/Observables/RetryWhen.swift; sourceTree = ""; }; + 81D6453A6D8A1D0614A3A31F412C7C58 /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + 8690EF8A2CD143E8A869D8A89C2B0C10 /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + 8724F43767BBBA66EFB90F21A154B1CA /* Generate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generate.swift; path = RxSwift/Observables/Generate.swift; sourceTree = ""; }; + 8A15E924662B8326AEA62629DF948340 /* CustomDateFormatTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CustomDateFormatTransform.swift; path = Sources/CustomDateFormatTransform.swift; sourceTree = ""; }; + 8AFCBD306E5CF9543EEC032CE7CFAF68 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 8B079F294DA5D9A879E6D53A91F51A1E /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + 8C16718DE3239BD8C23495725023BE81 /* Take.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Take.swift; path = RxSwift/Observables/Take.swift; sourceTree = ""; }; + 8CA9411B0831063C70625D754B4918FD /* ReplaySubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplaySubject.swift; path = RxSwift/Subjects/ReplaySubject.swift; sourceTree = ""; }; + 8D871D153D40F1C0A6DE030288D37CC1 /* Completable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Completable.swift; path = RxSwift/Traits/Completable.swift; sourceTree = ""; }; + 8D9DAC6BE28EF775D686F17F09B31E3C /* ScheduledDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledDisposable.swift; path = RxSwift/Disposables/ScheduledDisposable.swift; sourceTree = ""; }; + 8DFB4157C65F8B387F6D0EEA584B7DAF /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = Sources/Map.swift; sourceTree = ""; }; + 8F01F6C9F2FDB69AC7AB41530CF26855 /* ObservableType+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+Extensions.swift"; path = "RxSwift/ObservableType+Extensions.swift"; sourceTree = ""; }; + 903BA82990CDCC3ADE2630D8C453BF40 /* VirtualTimeScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeScheduler.swift; path = RxSwift/Schedulers/VirtualTimeScheduler.swift; sourceTree = ""; }; + 9181BBD326CCF68240582BCA379CC275 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + 935863FF9D4680ED9CDA3E6C9F7C8AB4 /* Amb.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Amb.swift; path = RxSwift/Observables/Amb.swift; sourceTree = ""; }; + 9505124EAAFCA1E0204A3D69DE20E935 /* SkipUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipUntil.swift; path = RxSwift/Observables/SkipUntil.swift; sourceTree = ""; }; + 968E3B01C04164A6C646FD39FD71060C /* DistinctUntilChanged.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DistinctUntilChanged.swift; path = RxSwift/Observables/DistinctUntilChanged.swift; sourceTree = ""; }; + 98DCACDA85E1B8B543CDA7CA7ABCD893 /* ObjectMapper.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = ObjectMapper.xcconfig; sourceTree = ""; }; + 9986B41980C382CD4C8AE87A739A98F6 /* Skip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Skip.swift; path = RxSwift/Observables/Skip.swift; sourceTree = ""; }; + 99D90428D3C69D1ADC59A83C946DD77D /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 9B4DBCA33668769DBB9524E32ABA25CF /* Mapper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Mapper.swift; path = Sources/Mapper.swift; sourceTree = ""; }; + 9B7D504EDF0355844420E2017637EC31 /* ShareReplayScope.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplayScope.swift; path = RxSwift/Observables/ShareReplayScope.swift; sourceTree = ""; }; + 9BEFAE140A2E819BD4BFDA6C633869E2 /* AlamofireExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireExtended.swift; path = Source/AlamofireExtended.swift; sourceTree = ""; }; + 9C1F1EAF75944B4DC06D8FBA81B8D3E8 /* DictionaryTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DictionaryTransform.swift; path = Sources/DictionaryTransform.swift; sourceTree = ""; }; + 9C9058C31F712D8D4374186649CA91EB /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = RxSwift/Observables/Filter.swift; sourceTree = ""; }; + 9D32E6BE23D99ADB8234E2489F607F65 /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9D980CF62CE0957F1A84246BDB2CF5E1 /* ObjectMapper-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ObjectMapper-prefix.pch"; sourceTree = ""; }; + 9E6DB19C9B36871C0CCF5AC9552C1845 /* HTTPMethod.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPMethod.swift; path = Source/HTTPMethod.swift; sourceTree = ""; }; + 9EA7019CA96E290ECCEC08377988EFD6 /* EnumTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EnumTransform.swift; path = Sources/EnumTransform.swift; sourceTree = ""; }; + 9F679050B0FD7100AECF1EF118B1A023 /* RxSwift.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.xcconfig; sourceTree = ""; }; + A0F6A23D3C138A29DF8BC2E5613ADE5F /* Pods-TesteArenaFelipePerius-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-TesteArenaFelipePerius-dummy.m"; sourceTree = ""; }; + A1DD0CFEB17B0C62B52F56F96B5EB28D /* Scan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scan.swift; path = RxSwift/Observables/Scan.swift; sourceTree = ""; }; + A1EFD62A67FF699D1F7E0C308B78F133 /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSessionConfiguration+Alamofire.swift"; path = "Source/URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; + A24B2C6BABDA54CFBB2307B84E80E3E4 /* Delay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Delay.swift; path = RxSwift/Observables/Delay.swift; sourceTree = ""; }; + A2AC3CD5257A8791A2965A1E98BD7E50 /* CombineLatest+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+Collection.swift"; path = "RxSwift/Observables/CombineLatest+Collection.swift"; sourceTree = ""; }; + A31D421772347EE967A949388F5968B7 /* Multicast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multicast.swift; path = RxSwift/Observables/Multicast.swift; sourceTree = ""; }; + A3E0BE15BF87AC678E7C321C6BB49D6C /* ConcurrentDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentDispatchQueueScheduler.swift; path = RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift; sourceTree = ""; }; + A43CACA05645A0CFABAB493A8EC348DF /* BehaviorSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorSubject.swift; path = RxSwift/Subjects/BehaviorSubject.swift; sourceTree = ""; }; + A6DA81C2DED81823F164C621DAF7E481 /* SynchronizedOnType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedOnType.swift; path = RxSwift/Concurrency/SynchronizedOnType.swift; sourceTree = ""; }; + A773C41F5B970076F9FA23272307FE4B /* DelaySubscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelaySubscription.swift; path = RxSwift/Observables/DelaySubscription.swift; sourceTree = ""; }; + A818587F3B438998D75C3206B6FA5060 /* ConcurrentMainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentMainScheduler.swift; path = RxSwift/Schedulers/ConcurrentMainScheduler.swift; sourceTree = ""; }; + A8540404B74066C770241ACDF8ED6A38 /* BooleanDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BooleanDisposable.swift; path = RxSwift/Disposables/BooleanDisposable.swift; sourceTree = ""; }; + A8CC8D54B78433348E75EC56A9861B2B /* ObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableType.swift; path = RxSwift/ObservableType.swift; sourceTree = ""; }; + A903BB49E3C08E8AFD971367D7309791 /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLConvertible+URLRequestConvertible.swift"; path = "Source/URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; + A96BF26D13245C6034705A668CD49A99 /* InvocableScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableScheduledItem.swift; path = RxSwift/Schedulers/Internal/InvocableScheduledItem.swift; sourceTree = ""; }; + AD6EFF9C8F9E29739CB011722D97E610 /* PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrimitiveSequence.swift; path = RxSwift/Traits/PrimitiveSequence.swift; sourceTree = ""; }; + AD700F9E5F4ED3FA7A81D9BEF399B024 /* RxSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-prefix.pch"; sourceTree = ""; }; + B018235D0A956F9925D1C437EFD00C60 /* DefaultIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DefaultIfEmpty.swift; path = RxSwift/Observables/DefaultIfEmpty.swift; sourceTree = ""; }; + B06C16E508CD772D68DC2C43DF123865 /* Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+arity.swift"; path = "RxSwift/Observables/Zip+arity.swift"; sourceTree = ""; }; + B0AE8C5112E46BD4BD070D2375AEF3F7 /* Pods-TesteArenaFelipePeriusTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-TesteArenaFelipePeriusTests.modulemap"; sourceTree = ""; }; + B3D5B0A797F39D4E69264A482C5A008E /* ConnectableObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservableType.swift; path = RxSwift/ConnectableObservableType.swift; sourceTree = ""; }; + B4189A5C33433E4AC00DF0B51BAA060A /* RxMutableBox.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxMutableBox.swift; path = RxSwift/RxMutableBox.swift; sourceTree = ""; }; + B576551E0278A4412BD0A7F30D46149B /* Empty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Empty.swift; path = RxSwift/Observables/Empty.swift; sourceTree = ""; }; + B65E461AC3B3BB42745296F08770B390 /* CombineLatest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CombineLatest.swift; path = RxSwift/Observables/CombineLatest.swift; sourceTree = ""; }; + B66304FC05BAE44E6A8D8BCA6E01CF0A /* Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + B75C56715E3260866E5BF0FEBBFED28F /* PrimitiveSequence+Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PrimitiveSequence+Zip+arity.swift"; path = "RxSwift/Traits/PrimitiveSequence+Zip+arity.swift"; sourceTree = ""; }; + B9084FE779702931E8DF1D00A2D725FB /* ObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = ObjectMapper.framework; path = ObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + B9E38172127C8C3307E0F8374AA97FFF /* TailRecursiveSink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TailRecursiveSink.swift; path = RxSwift/Observers/TailRecursiveSink.swift; sourceTree = ""; }; + BA51C0542663CDE5D4F2E74FAB7E90DE /* Pods-TesteArenaFelipePerius-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TesteArenaFelipePerius-Info.plist"; sourceTree = ""; }; + BBA3F5031FCFFF645585DC7AB54893E8 /* Concat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concat.swift; path = RxSwift/Observables/Concat.swift; sourceTree = ""; }; + BC32A04C153C7C7BF0C3BDB20655BCEF /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.markdown"; sourceTree = ""; }; + BD4A9D9A449CE940DF10A0BA19A75320 /* ObjectMapper-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ObjectMapper-umbrella.h"; sourceTree = ""; }; + BD4D30752CAAD247C60AB5093038FB02 /* Maybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Maybe.swift; path = RxSwift/Traits/Maybe.swift; sourceTree = ""; }; + C0BC19FFA55660A72110E94AAABAEEA4 /* Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rx.swift; path = RxSwift/Rx.swift; sourceTree = ""; }; + C1A894C23B148F4B4BA6E517C8E779A4 /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + C2945668794E05C643879F7DBC20A4DA /* MultipartUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartUpload.swift; path = Source/MultipartUpload.swift; sourceTree = ""; }; + C3EA162FEFA4906591F1C8EA25EB57AE /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + C47C6E5A4DB55A1DE4ED28144FA37C2C /* RequestInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestInterceptor.swift; path = Source/RequestInterceptor.swift; sourceTree = ""; }; + C4BAD7F0792CE98805FDCB1622D610CB /* SynchronizedDisposeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedDisposeType.swift; path = RxSwift/Concurrency/SynchronizedDisposeType.swift; sourceTree = ""; }; + C5BB7D0C25AFFFE678DF279C91688DE9 /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + C6F25BBEC57F8C0BCBA311348977D317 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.plist"; sourceTree = ""; }; + C733267DB36BA7634B1C013704DDE71B /* Pods-TesteArenaFelipePeriusTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TesteArenaFelipePeriusTests.debug.xcconfig"; sourceTree = ""; }; + C76A9E7A003958D35B2CA22F341C5054 /* SingleAsync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAsync.swift; path = RxSwift/Observables/SingleAsync.swift; sourceTree = ""; }; + C7C9D422C2A9151F4332BD06ED2415B2 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Source/RedirectHandler.swift; sourceTree = ""; }; + C952B8243DC3C84AA149D14F8D7898E9 /* SwiftSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftSupport.swift; path = RxSwift/SwiftSupport/SwiftSupport.swift; sourceTree = ""; }; + C9F8E1D25A3D17A41F7BE27BF3AA6D1E /* Single.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Single.swift; path = RxSwift/Traits/Single.swift; sourceTree = ""; }; + CAD1B28227AB07744424DB8AD255D247 /* Pods-TesteArenaFelipePerius-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-TesteArenaFelipePerius-frameworks.sh"; sourceTree = ""; }; + CAF72AA1C52553F0770C1B5E10CFBA6B /* SubjectType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubjectType.swift; path = RxSwift/Subjects/SubjectType.swift; sourceTree = ""; }; + CAF8329E0E80AB8B68ACBCB76BF771A4 /* RxSwift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxSwift-Info.plist"; sourceTree = ""; }; + CB512A2C06D80DE1C223486D5735785C /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh"; sourceTree = ""; }; + CBAAA404AAD7C1FB100BA9BC72AB5ADB /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + CC52318E88738159541DB8D2C9BA753C /* Never.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Never.swift; path = RxSwift/Observables/Never.swift; sourceTree = ""; }; + CDF399874771CD4A3CF72DA907A4B579 /* Range.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Range.swift; path = RxSwift/Observables/Range.swift; sourceTree = ""; }; + CF6A118AC9CBE4E7040B27D37AD55FB2 /* Completable+AndThen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Completable+AndThen.swift"; path = "RxSwift/Traits/Completable+AndThen.swift"; sourceTree = ""; }; + CF974B707B8856787A86858D8961A163 /* DisposeBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBase.swift; path = RxSwift/Disposables/DisposeBase.swift; sourceTree = ""; }; + CFC4027DDCF7D2865261C0C5B10407A1 /* Bag+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bag+Rx.swift"; path = "RxSwift/Extensions/Bag+Rx.swift"; sourceTree = ""; }; + D1850B8DA95E3B70153244A58914A5A9 /* SubscribeOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscribeOn.swift; path = RxSwift/Observables/SubscribeOn.swift; sourceTree = ""; }; + D303D7C8B44000AD2DAF980BABE1C5DD /* TransformOperators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformOperators.swift; path = Sources/TransformOperators.swift; sourceTree = ""; }; + D3A650E4486A1A194EB61292D811F3FF /* Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Create.swift; path = RxSwift/Observables/Create.swift; sourceTree = ""; }; + D44EB4484EC8CF7EB69AB550530425E4 /* HistoricalSchedulerTimeConverter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalSchedulerTimeConverter.swift; path = RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift; sourceTree = ""; }; + D6F9F164C5F49586D3C447374D1AA6DD /* Just.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Just.swift; path = RxSwift/Observables/Just.swift; sourceTree = ""; }; + D76D117F97C7C0FAF41E99829FD48B08 /* ObservableType+PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+PrimitiveSequence.swift"; path = "RxSwift/Traits/ObservableType+PrimitiveSequence.swift"; sourceTree = ""; }; + D7A06BD6F2838BB3EBF8AA49D3AB4EFA /* GroupedObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupedObservable.swift; path = RxSwift/GroupedObservable.swift; sourceTree = ""; }; + D8811E1913260F048DE79BDAF377AFA7 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-Info.plist"; sourceTree = ""; }; + D8D69D0FA018D470D48DFA902F11BAE0 /* RxSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxSwift.modulemap; sourceTree = ""; }; + DA1C6B6C8EE757807ECE831DD4DC5C70 /* Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debug.swift; path = RxSwift/Observables/Debug.swift; sourceTree = ""; }; + DB63C417A576811C402CA1C821250F09 /* Pods-TesteArenaFelipePeriusTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-TesteArenaFelipePeriusTests-acknowledgements.markdown"; sourceTree = ""; }; + DB94BD0848118D7B40B21DF34217C833 /* SwitchIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwitchIfEmpty.swift; path = RxSwift/Observables/SwitchIfEmpty.swift; sourceTree = ""; }; + DBA37BDB12E5A5F00C1D336DAC4F100E /* CodableTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CodableTransform.swift; path = Sources/CodableTransform.swift; sourceTree = ""; }; + DC5B5849E1B70B9D88E89D99C0F70450 /* Switch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Switch.swift; path = RxSwift/Observables/Switch.swift; sourceTree = ""; }; + DC73DC6D4BB6AFF08661DE40132155A6 /* RxSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-umbrella.h"; sourceTree = ""; }; + DD9220B67AC9D2D96B57F728460F5F0E /* Pods_TesteArenaFelipePerius.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_TesteArenaFelipePerius.framework; path = "Pods-TesteArenaFelipePerius.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + DDDE738F741A10BC3C028A9163AAA7D7 /* Repeat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Repeat.swift; path = RxSwift/Observables/Repeat.swift; sourceTree = ""; }; + DE188BD0F74495486CB135BF4AA51CB3 /* CurrentThreadScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CurrentThreadScheduler.swift; path = RxSwift/Schedulers/CurrentThreadScheduler.swift; sourceTree = ""; }; + DFE1D1F824F55E0466A6D3C65D84EA94 /* MapError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MapError.swift; path = Sources/MapError.swift; sourceTree = ""; }; + E0CE5B9E7B1DD8160EB1F96F53363B76 /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + E1734BC5F355FB8FD60403932BE56BD2 /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = RxSwift/Observables/Merge.swift; sourceTree = ""; }; + E31807D395D50BEA4B29E9678C4968F3 /* Sample.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sample.swift; path = RxSwift/Observables/Sample.swift; sourceTree = ""; }; + E38F677CA57D2BE0A899DA12A898AEE7 /* Pods-TesteArenaFelipePeriusTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-TesteArenaFelipePeriusTests-dummy.m"; sourceTree = ""; }; + E4061B34DAE49A1D00275B9BECDAD0CD /* Materialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Materialize.swift; path = RxSwift/Observables/Materialize.swift; sourceTree = ""; }; + E45B8D14F6F0760A64824904F8B607FF /* Pods_TesteArenaFelipePeriusTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_TesteArenaFelipePeriusTests.framework; path = "Pods-TesteArenaFelipePeriusTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + E4C1D1D9CBA7932E3ECFF1AA1BDEE6C8 /* Deferred.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deferred.swift; path = RxSwift/Observables/Deferred.swift; sourceTree = ""; }; + E757C1718FABCBFE69CE45B12E95FD38 /* AtomicInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AtomicInt.swift; path = Platform/AtomicInt.swift; sourceTree = ""; }; + E98D65119505E958C1F3AFF6CB579E2D /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLEncodedFormEncoder.swift; path = Source/URLEncodedFormEncoder.swift; sourceTree = ""; }; + EB6E53D977F6C1371466A03ADCC5CABD /* Using.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Using.swift; path = RxSwift/Observables/Using.swift; sourceTree = ""; }; + EE8D4760E6677D810C691228146DB07D /* AddRef.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AddRef.swift; path = RxSwift/Observables/AddRef.swift; sourceTree = ""; }; + EE92B26C78050C12F31F4D5E482C6402 /* ScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItem.swift; path = RxSwift/Schedulers/Internal/ScheduledItem.swift; sourceTree = ""; }; + EF3D62DB66E0AC668845FE27CED20FB1 /* Lock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Lock.swift; path = RxSwift/Concurrency/Lock.swift; sourceTree = ""; }; + F2881205359308BB68FE148FDC08D9B4 /* Sequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sequence.swift; path = RxSwift/Observables/Sequence.swift; sourceTree = ""; }; + F2DD4F18E82C2C328B3CA26AF8D04C57 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-dummy.m"; sourceTree = ""; }; + F2F6B71C1CE5C52EF6238C2C6E13AFB1 /* InvocableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableType.swift; path = RxSwift/Schedulers/Internal/InvocableType.swift; sourceTree = ""; }; + F2F8768D1FAE8DC3C03C6841BF33A4A9 /* DispatchQueueConfiguration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DispatchQueueConfiguration.swift; path = RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift; sourceTree = ""; }; + F35157C78A40E0B855565E46643C35C1 /* ImmutableMappable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmutableMappable.swift; path = Sources/ImmutableMappable.swift; sourceTree = ""; }; + F54D1DC109571924BB93B9F654959463 /* MainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MainScheduler.swift; path = RxSwift/Schedulers/MainScheduler.swift; sourceTree = ""; }; + F70625D7742C9748020E1CADB9B9760A /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Alamofire.swift"; path = "Source/URLRequest+Alamofire.swift"; sourceTree = ""; }; + F795E34A2B46F6A518CBC464BEA75A2A /* Pods-TesteArenaFelipePerius.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-TesteArenaFelipePerius.modulemap"; sourceTree = ""; }; + F7A75F924719AA27A4B299C9697D202B /* CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+arity.swift"; path = "RxSwift/Observables/CombineLatest+arity.swift"; sourceTree = ""; }; + F7C71CEAD4B9231D2866A6AAECF86D0B /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; + F87F786C32AF9EFCFA59FAFE64254A51 /* ObjectMapper-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "ObjectMapper-dummy.m"; sourceTree = ""; }; + FBDDD5766D916E0F6E7618A8DB9548D3 /* Protector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Protector.swift; path = Source/Protector.swift; sourceTree = ""; }; + FED34C56E8E494491B950FDD0415226A /* HTTPHeaders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHeaders.swift; path = Source/HTTPHeaders.swift; sourceTree = ""; }; + FEDDC5222BA9C96C2EB140358CD5B191 /* FromJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FromJSON.swift; path = Sources/FromJSON.swift; sourceTree = ""; }; + FF19B4632D4A8440CB9D2328E56E9EC1 /* CachedResponseHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CachedResponseHandler.swift; path = Source/CachedResponseHandler.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 15F9D6A1AC1EB5534CAB12B718BC8D6A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 19D39D44150CEDA538ADA8F7A2155DE1 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 632D47EB662A2CDDA94BF8DB4967588E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C755AA51D790ADF7ABFDC4B1A5417337 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 86D44ED0C44E607770A522CB2F9D6DBC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + B025A5FFBDEB6AC4ED3B081EDA03CCA9 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8B0D8633F410345F93419B8C3D7B6916 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 97A168DFB6DB61770CE2DBF4FD39AA8D /* CFNetwork.framework in Frameworks */, + BE82AE980F8C7EE28A6448959194F93A /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ED1637C96BF54A5D16D10C9E2A6FEA60 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 83ADD0310D235BAF1EF73EBFCFCBBB50 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FC1418521A50C9E2BCB487656F55920C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BDD81CA3D510127F62A71ACDB0C59B36 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 00756DEBC8F284E06DCEE65A525F1405 /* Pods-TesteArenaFelipePeriusTests */ = { + isa = PBXGroup; + children = ( + B0AE8C5112E46BD4BD070D2375AEF3F7 /* Pods-TesteArenaFelipePeriusTests.modulemap */, + DB63C417A576811C402CA1C821250F09 /* Pods-TesteArenaFelipePeriusTests-acknowledgements.markdown */, + 23C9A9A7C17F31975331A93988967881 /* Pods-TesteArenaFelipePeriusTests-acknowledgements.plist */, + E38F677CA57D2BE0A899DA12A898AEE7 /* Pods-TesteArenaFelipePeriusTests-dummy.m */, + 58FDC708B22982364157B9397EA526EA /* Pods-TesteArenaFelipePeriusTests-Info.plist */, + 1A9C3649B03B036850F3DB4254A9C499 /* Pods-TesteArenaFelipePeriusTests-umbrella.h */, + C733267DB36BA7634B1C013704DDE71B /* Pods-TesteArenaFelipePeriusTests.debug.xcconfig */, + 6B41D078EEA17D635B974F06337C94AB /* Pods-TesteArenaFelipePeriusTests.release.xcconfig */, + ); + name = "Pods-TesteArenaFelipePeriusTests"; + path = "Target Support Files/Pods-TesteArenaFelipePeriusTests"; + sourceTree = ""; + }; + 10E5B41DBE74A62D0B0BA4D2D60D9DE0 /* Support Files */ = { + isa = PBXGroup; + children = ( + D8D69D0FA018D470D48DFA902F11BAE0 /* RxSwift.modulemap */, + 9F679050B0FD7100AECF1EF118B1A023 /* RxSwift.xcconfig */, + 7164490DADD9AA8811854DBFBBAEEAEA /* RxSwift-dummy.m */, + CAF8329E0E80AB8B68ACBCB76BF771A4 /* RxSwift-Info.plist */, + AD700F9E5F4ED3FA7A81D9BEF399B024 /* RxSwift-prefix.pch */, + DC73DC6D4BB6AFF08661DE40132155A6 /* RxSwift-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/RxSwift"; + sourceTree = ""; + }; + 12DBBEA06433DA6962631C79D15BA125 /* RxSwift */ = { + isa = PBXGroup; + children = ( + EE8D4760E6677D810C691228146DB07D /* AddRef.swift */, + 935863FF9D4680ED9CDA3E6C9F7C8AB4 /* Amb.swift */, + 6C236D47F7784E793CBE71358D119006 /* AnonymousDisposable.swift */, + 027B064B6BD670A541E4EEA8C52989B8 /* AnonymousObserver.swift */, + 05630551B1C47397F0F57B7D15F2B2D3 /* AnyObserver.swift */, + 8161C450990FCB062E85415DB8A36D0E /* AsMaybe.swift */, + 0533E6E1708F41B39016681E23F6E45D /* AsSingle.swift */, + 41894FF0368E390C85AE88A5F1D9570F /* AsyncLock.swift */, + 3CF06FED22B98894BE913211374631D8 /* AsyncSubject.swift */, + E757C1718FABCBFE69CE45B12E95FD38 /* AtomicInt.swift */, + 55937B8294241DA99AC6F4C9D0F4B74B /* Bag.swift */, + CFC4027DDCF7D2865261C0C5B10407A1 /* Bag+Rx.swift */, + A43CACA05645A0CFABAB493A8EC348DF /* BehaviorSubject.swift */, + 14BAC6021CA72C08A99A9D2772B154A8 /* BinaryDisposable.swift */, + A8540404B74066C770241ACDF8ED6A38 /* BooleanDisposable.swift */, + 6930208477EB57B0DA3DF041A64EDABB /* Buffer.swift */, + 0FBDBBAF7A0C75EA3CA6943BF73D0E56 /* Cancelable.swift */, + 79FD2271F0FAA50AC1F7D7ADF072FEB5 /* Catch.swift */, + B65E461AC3B3BB42745296F08770B390 /* CombineLatest.swift */, + F7A75F924719AA27A4B299C9697D202B /* CombineLatest+arity.swift */, + A2AC3CD5257A8791A2965A1E98BD7E50 /* CombineLatest+Collection.swift */, + 8D871D153D40F1C0A6DE030288D37CC1 /* Completable.swift */, + CF6A118AC9CBE4E7040B27D37AD55FB2 /* Completable+AndThen.swift */, + 5B5B8A75FF598B81AD4CF67C2F5FE05E /* CompositeDisposable.swift */, + BBA3F5031FCFFF645585DC7AB54893E8 /* Concat.swift */, + A3E0BE15BF87AC678E7C321C6BB49D6C /* ConcurrentDispatchQueueScheduler.swift */, + A818587F3B438998D75C3206B6FA5060 /* ConcurrentMainScheduler.swift */, + B3D5B0A797F39D4E69264A482C5A008E /* ConnectableObservableType.swift */, + D3A650E4486A1A194EB61292D811F3FF /* Create.swift */, + DE188BD0F74495486CB135BF4AA51CB3 /* CurrentThreadScheduler.swift */, + 77044C5E67A4BFF8C81DA6AE7BA0C24F /* Debounce.swift */, + DA1C6B6C8EE757807ECE831DD4DC5C70 /* Debug.swift */, + B018235D0A956F9925D1C437EFD00C60 /* DefaultIfEmpty.swift */, + E4C1D1D9CBA7932E3ECFF1AA1BDEE6C8 /* Deferred.swift */, + A24B2C6BABDA54CFBB2307B84E80E3E4 /* Delay.swift */, + A773C41F5B970076F9FA23272307FE4B /* DelaySubscription.swift */, + 76364568619BB5F3B496E40ED1B023F5 /* Dematerialize.swift */, + 3FF972698FDFE796BFED7D1405325D36 /* Deprecated.swift */, + 1A6B542FC2EE5DF3C874F2E099CD4004 /* DeprecationWarner.swift */, + 9D32E6BE23D99ADB8234E2489F607F65 /* DispatchQueue+Extensions.swift */, + F2F8768D1FAE8DC3C03C6841BF33A4A9 /* DispatchQueueConfiguration.swift */, + 6D66D82F0346E1BF9EEB8702CE38C0B5 /* Disposable.swift */, + 2731D07F74F7CC84230423987D1D9676 /* Disposables.swift */, + 65DAFD456DA21256346E561098DD8102 /* DisposeBag.swift */, + CF974B707B8856787A86858D8961A163 /* DisposeBase.swift */, + 968E3B01C04164A6C646FD39FD71060C /* DistinctUntilChanged.swift */, + 46952D92F910168CA86D53E171AFF6F9 /* Do.swift */, + 6E9C68E5EED40E4F454A3FCA2EB3CA61 /* ElementAt.swift */, + B576551E0278A4412BD0A7F30D46149B /* Empty.swift */, + 5FC2AA62D014AF3DE7B108B2DFB9AFF2 /* Enumerated.swift */, + 39CC7F0C167EBC05E762AE300A288998 /* Error.swift */, + 09227FBF929065990990D9EB0BF01E1F /* Errors.swift */, + 5FB0557BA1CE18DF5C9902469D09217E /* Event.swift */, + 9C9058C31F712D8D4374186649CA91EB /* Filter.swift */, + 599E942DDCB1E8143E3B313C7AFF4D84 /* First.swift */, + 8724F43767BBBA66EFB90F21A154B1CA /* Generate.swift */, + 790BE6FDA25B6A09CD30D499C6156E3A /* GroupBy.swift */, + D7A06BD6F2838BB3EBF8AA49D3AB4EFA /* GroupedObservable.swift */, + 2E4533C6B8B12FB313D29AA77537EE7C /* HistoricalScheduler.swift */, + D44EB4484EC8CF7EB69AB550530425E4 /* HistoricalSchedulerTimeConverter.swift */, + 02B5E897F0CB63D3297CEA55248FE2B8 /* ImmediateSchedulerType.swift */, + C5BB7D0C25AFFFE678DF279C91688DE9 /* InfiniteSequence.swift */, + A96BF26D13245C6034705A668CD49A99 /* InvocableScheduledItem.swift */, + F2F6B71C1CE5C52EF6238C2C6E13AFB1 /* InvocableType.swift */, + D6F9F164C5F49586D3C447374D1AA6DD /* Just.swift */, + EF3D62DB66E0AC668845FE27CED20FB1 /* Lock.swift */, + 6FA1B497A90ED57D2267B21587D537B5 /* LockOwnerType.swift */, + F54D1DC109571924BB93B9F654959463 /* MainScheduler.swift */, + 57B4B8E1EAE295EE0E584E53100A3E74 /* Map.swift */, + E4061B34DAE49A1D00275B9BECDAD0CD /* Materialize.swift */, + BD4D30752CAAD247C60AB5093038FB02 /* Maybe.swift */, + E1734BC5F355FB8FD60403932BE56BD2 /* Merge.swift */, + A31D421772347EE967A949388F5968B7 /* Multicast.swift */, + CC52318E88738159541DB8D2C9BA753C /* Never.swift */, + 08F4F9DD3669BC94AE94F621FFB1AC54 /* NopDisposable.swift */, + 55DE979328AFFC5F6AFC466F5578F1BB /* Observable.swift */, + 15A5C0ECCA57DCF8B449B7BFEB25C4AF /* ObservableConvertibleType.swift */, + A8CC8D54B78433348E75EC56A9861B2B /* ObservableType.swift */, + 8F01F6C9F2FDB69AC7AB41530CF26855 /* ObservableType+Extensions.swift */, + D76D117F97C7C0FAF41E99829FD48B08 /* ObservableType+PrimitiveSequence.swift */, + 409273AACA9F5B31BB8D055343AAD223 /* ObserveOn.swift */, + 6EC9976069E18F2DB9E07D3FC2D5E32E /* ObserverBase.swift */, + 2A14CEE9B85ACC6B27F8780736D7C827 /* ObserverType.swift */, + 4052D1C12993269502196752C9861E26 /* OperationQueueScheduler.swift */, + 6D6A4BA05C1099F4CF270927BCBB72B7 /* Optional.swift */, + 8690EF8A2CD143E8A869D8A89C2B0C10 /* Platform.Darwin.swift */, + E0CE5B9E7B1DD8160EB1F96F53363B76 /* Platform.Linux.swift */, + AD6EFF9C8F9E29739CB011722D97E610 /* PrimitiveSequence.swift */, + B75C56715E3260866E5BF0FEBBFED28F /* PrimitiveSequence+Zip+arity.swift */, + C1A894C23B148F4B4BA6E517C8E779A4 /* PriorityQueue.swift */, + 00904047A0B6B5F5C5618F5DFB73620F /* Producer.swift */, + 45ED378E7DE3C601CCA5E72BEC1000CA /* PublishSubject.swift */, + 81D6453A6D8A1D0614A3A31F412C7C58 /* Queue.swift */, + CDF399874771CD4A3CF72DA907A4B579 /* Range.swift */, + 60597222B888642B62814CB79FDC43D4 /* Reactive.swift */, + 5C6671CC833F0ECFBA97604500D1304C /* RecursiveLock.swift */, + 7CDC02B5A7AF49285AE8446C2192F735 /* RecursiveScheduler.swift */, + 0C5F866D63DAF6917AC5D38F74CF5F24 /* Reduce.swift */, + 31020F43573BCFEC379D55631688F4ED /* RefCountDisposable.swift */, + DDDE738F741A10BC3C028A9163AAA7D7 /* Repeat.swift */, + 8CA9411B0831063C70625D754B4918FD /* ReplaySubject.swift */, + 817CE16450B6CAC8BE63A00FE9E84DC0 /* RetryWhen.swift */, + C0BC19FFA55660A72110E94AAABAEEA4 /* Rx.swift */, + B4189A5C33433E4AC00DF0B51BAA060A /* RxMutableBox.swift */, + E31807D395D50BEA4B29E9678C4968F3 /* Sample.swift */, + A1DD0CFEB17B0C62B52F56F96B5EB28D /* Scan.swift */, + 8D9DAC6BE28EF775D686F17F09B31E3C /* ScheduledDisposable.swift */, + EE92B26C78050C12F31F4D5E482C6402 /* ScheduledItem.swift */, + 5B0B0A09DCF2F8286D9627662951535A /* ScheduledItemType.swift */, + 33F426213A879BAB4E0C792C7D7CB344 /* SchedulerServices+Emulation.swift */, + 692333012F46D8ACF7F13618B00574EE /* SchedulerType.swift */, + F2881205359308BB68FE148FDC08D9B4 /* Sequence.swift */, + 27DC088C384CBF07DFF7C1F511699937 /* SerialDispatchQueueScheduler.swift */, + 691AA8A8E6AB1AACFCE481D89EC544FD /* SerialDisposable.swift */, + 9B7D504EDF0355844420E2017637EC31 /* ShareReplayScope.swift */, + C9F8E1D25A3D17A41F7BE27BF3AA6D1E /* Single.swift */, + 5516C9C3A8AEE60A4D1095326174EB7A /* SingleAssignmentDisposable.swift */, + C76A9E7A003958D35B2CA22F341C5054 /* SingleAsync.swift */, + 740A5CC58B2602CE3DB35BDCDA67EC5F /* Sink.swift */, + 9986B41980C382CD4C8AE87A739A98F6 /* Skip.swift */, + 9505124EAAFCA1E0204A3D69DE20E935 /* SkipUntil.swift */, + 022008893BA814D48459824C8D7DFC3B /* SkipWhile.swift */, + 1B42D224B226072B630A73517F31CFEE /* StartWith.swift */, + 3AE36D7530CCF0CC0DFFC2C92A070BDF /* String+Rx.swift */, + CAF72AA1C52553F0770C1B5E10CFBA6B /* SubjectType.swift */, + D1850B8DA95E3B70153244A58914A5A9 /* SubscribeOn.swift */, + 3736659527C50D97B6E9F378D721450A /* SubscriptionDisposable.swift */, + C952B8243DC3C84AA149D14F8D7898E9 /* SwiftSupport.swift */, + DC5B5849E1B70B9D88E89D99C0F70450 /* Switch.swift */, + DB94BD0848118D7B40B21DF34217C833 /* SwitchIfEmpty.swift */, + C4BAD7F0792CE98805FDCB1622D610CB /* SynchronizedDisposeType.swift */, + A6DA81C2DED81823F164C621DAF7E481 /* SynchronizedOnType.swift */, + 00C6581C996B84EB78C88C2D56364DCC /* SynchronizedUnsubscribeType.swift */, + B9E38172127C8C3307E0F8374AA97FFF /* TailRecursiveSink.swift */, + 8C16718DE3239BD8C23495725023BE81 /* Take.swift */, + 2158C38A5A19AF81CCB3ED036F3ABEFA /* TakeLast.swift */, + 2816CEBAB68E6D7FB5A1D5E3082F6633 /* TakeUntil.swift */, + 4989E1CC689571AA7963C048E171CF97 /* TakeWhile.swift */, + 09F157FD187A7931F9B019BB27EFC183 /* Throttle.swift */, + 7ECB7D39AB45262BEC04CD34738238D6 /* Timeout.swift */, + 1909ACFAAEC1EA873AEAF254E101F56C /* Timer.swift */, + 45B1BF11749644F187F48C6CF13E6F3E /* ToArray.swift */, + EB6E53D977F6C1371466A03ADCC5CABD /* Using.swift */, + 52B63C781391EC69A5BA9191594634EC /* VirtualTimeConverterType.swift */, + 903BA82990CDCC3ADE2630D8C453BF40 /* VirtualTimeScheduler.swift */, + 3ACFACFE85EA2C4424C4AA86A47507EF /* Window.swift */, + 70B8D724F9D3CC76FB194B48D7A16E4E /* WithLatestFrom.swift */, + 7B5136421E833587654400F307680D87 /* Zip.swift */, + B06C16E508CD772D68DC2C43DF123865 /* Zip+arity.swift */, + 6BEE1F39CBA1EB1BAAA9321EA31AC88D /* Zip+Collection.swift */, + 10E5B41DBE74A62D0B0BA4D2D60D9DE0 /* Support Files */, + ); + name = RxSwift; + path = RxSwift; + sourceTree = ""; + }; + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */ = { + isa = PBXGroup; + children = ( + E34DCC8E2CF86B8D72232914781A840D /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 1716B54F87277B2EE1A8D84190A20704 /* ObjectMapper */ = { + isa = PBXGroup; + children = ( + DBA37BDB12E5A5F00C1D336DAC4F100E /* CodableTransform.swift */, + 8A15E924662B8326AEA62629DF948340 /* CustomDateFormatTransform.swift */, + 2B47E95A235609E280F072BC3291023F /* DataTransform.swift */, + 1D55FFB7C4CA782689A14B7246C98F22 /* DateFormatterTransform.swift */, + 732AB1DDEBF13E99AC3F9315786D2716 /* DateTransform.swift */, + 9C1F1EAF75944B4DC06D8FBA81B8D3E8 /* DictionaryTransform.swift */, + 48EB0B672BB6C6CF7753FD5F271746D7 /* EnumOperators.swift */, + 9EA7019CA96E290ECCEC08377988EFD6 /* EnumTransform.swift */, + FEDDC5222BA9C96C2EB140358CD5B191 /* FromJSON.swift */, + 6C531725F7D4F118D3FBD286BB11F4EA /* HexColorTransform.swift */, + F35157C78A40E0B855565E46643C35C1 /* ImmutableMappable.swift */, + 40F5642A9872100F7677F4451F052B11 /* IntegerOperators.swift */, + 5464B189C41224895EFE999411F45595 /* ISO8601DateTransform.swift */, + 8DFB4157C65F8B387F6D0EEA584B7DAF /* Map.swift */, + DFE1D1F824F55E0466A6D3C65D84EA94 /* MapError.swift */, + 5F3DC84FEC32EC10587D6E7AF2FA6DED /* Mappable.swift */, + 9B4DBCA33668769DBB9524E32ABA25CF /* Mapper.swift */, + 26B57589686C7AC8C1DE9A3AF8331BED /* NSDecimalNumberTransform.swift */, + 674D74EEE8893DA4E5848B2C68943133 /* Operators.swift */, + 4EF943B51A4C7BBCCF6F35C973EA32B9 /* ToJSON.swift */, + 3A04DDA234877712C9F0762C6458DD6B /* TransformOf.swift */, + D303D7C8B44000AD2DAF980BABE1C5DD /* TransformOperators.swift */, + 07F27815C986A3BE2EDFEE240D71151B /* TransformType.swift */, + 4E247EF10108B6DACEA3E0A15CBCCA98 /* URLTransform.swift */, + FF16CB386C8121BD283EEEE3E67F35B2 /* Support Files */, + ); + name = ObjectMapper; + path = ObjectMapper; + sourceTree = ""; + }; + 5DB5F3F18FF7EF15D0BB9F575CD07440 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 5B83491D8D14A60D7BA4DFB5C1190B48 /* AFError.swift */, + 46C546D0A547541B2BBB90FBF9E28361 /* Alamofire.swift */, + 9BEFAE140A2E819BD4BFDA6C633869E2 /* AlamofireExtended.swift */, + FF19B4632D4A8440CB9D2328E56E9EC1 /* CachedResponseHandler.swift */, + C3EA162FEFA4906591F1C8EA25EB57AE /* DispatchQueue+Alamofire.swift */, + 38A04CB00C5B9F343A421AE91AD85161 /* EventMonitor.swift */, + FED34C56E8E494491B950FDD0415226A /* HTTPHeaders.swift */, + 9E6DB19C9B36871C0CCF5AC9552C1845 /* HTTPMethod.swift */, + 582D9D34CF51F6013B76B2784AC01DDD /* MultipartFormData.swift */, + C2945668794E05C643879F7DBC20A4DA /* MultipartUpload.swift */, + 4A7A3BEBCA40325A9DB81D5DAA02F357 /* NetworkReachabilityManager.swift */, + 4B2C91000EDE72FA96AADE69DECA0E99 /* Notifications.swift */, + 3245E0AC2B90CF7AB4B58428AE115158 /* OperationQueue+Alamofire.swift */, + 5F384D1CC35F636C57BA266F5FBAF379 /* ParameterEncoder.swift */, + 01E6D8652C3829DEF7E8C9EE70D6489C /* ParameterEncoding.swift */, + FBDDD5766D916E0F6E7618A8DB9548D3 /* Protector.swift */, + C7C9D422C2A9151F4332BD06ED2415B2 /* RedirectHandler.swift */, + 2B453B450B8B7885F02E897CA25DE053 /* Request.swift */, + C47C6E5A4DB55A1DE4ED28144FA37C2C /* RequestInterceptor.swift */, + 796ACE5A3DF864A1BD17633C81D84220 /* RequestTaskMap.swift */, + 19FC3485EA64DD83DC858125494D728D /* Response.swift */, + 99D90428D3C69D1ADC59A83C946DD77D /* ResponseSerialization.swift */, + 39C9D76993253B5F0CEBFAB404FB789D /* Result+Alamofire.swift */, + 414487C576DA387BEEDAF09970D03458 /* RetryPolicy.swift */, + 3C4680CD4891286D154A006117883AF0 /* ServerTrustEvaluation.swift */, + 4F44ECA99BF514A9F6C0FD081EC3CC5B /* Session.swift */, + CBAAA404AAD7C1FB100BA9BC72AB5ADB /* SessionDelegate.swift */, + A903BB49E3C08E8AFD971367D7309791 /* URLConvertible+URLRequestConvertible.swift */, + E98D65119505E958C1F3AFF6CB579E2D /* URLEncodedFormEncoder.swift */, + F70625D7742C9748020E1CADB9B9760A /* URLRequest+Alamofire.swift */, + A1EFD62A67FF699D1F7E0C308B78F133 /* URLSessionConfiguration+Alamofire.swift */, + 065597E2268C23FF7EDF2D1246DC8479 /* Validation.swift */, + 747F53E60CC0AE05367B067824AFFF59 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + 747F53E60CC0AE05367B067824AFFF59 /* Support Files */ = { + isa = PBXGroup; + children = ( + 9181BBD326CCF68240582BCA379CC275 /* Alamofire.modulemap */, + 25696832ECA3AF6FBA021162CD9DC53E /* Alamofire.xcconfig */, + 679E7E083A0DF92827FF3A30B0990FA9 /* Alamofire-dummy.m */, + F7C71CEAD4B9231D2866A6AAECF86D0B /* Alamofire-Info.plist */, + 8AFCBD306E5CF9543EEC032CE7CFAF68 /* Alamofire-prefix.pch */, + 132F425C710D251AD251DAD2B49759D7 /* Alamofire-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + A78315AB7B960344992D7C26CAC0B091 /* Products */ = { + isa = PBXGroup; + children = ( + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */, + B9084FE779702931E8DF1D00A2D725FB /* ObjectMapper.framework */, + DD9220B67AC9D2D96B57F728460F5F0E /* Pods_TesteArenaFelipePerius.framework */, + B66304FC05BAE44E6A8D8BCA6E01CF0A /* Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework */, + E45B8D14F6F0760A64824904F8B607FF /* Pods_TesteArenaFelipePeriusTests.framework */, + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift.framework */, + ); + name = Products; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */, + E8F5F5926F3B3D3871021A4A61728D45 /* Pods */, + A78315AB7B960344992D7C26CAC0B091 /* Products */, + CF67CD56EDD5E5137D127733358B8513 /* Targets Support Files */, + ); + sourceTree = ""; + }; + CF67CD56EDD5E5137D127733358B8513 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + E61D0B10237EB244EEB4B7B514DBFAB0 /* Pods-TesteArenaFelipePerius */, + FD0B0B9601D6BC734C4CABE82D310C4D /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests */, + 00756DEBC8F284E06DCEE65A525F1405 /* Pods-TesteArenaFelipePeriusTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + E34DCC8E2CF86B8D72232914781A840D /* iOS */ = { + isa = PBXGroup; + children = ( + 8B079F294DA5D9A879E6D53A91F51A1E /* CFNetwork.framework */, + 222DAEF0D819F359AFCFF3D4F927E8A7 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + E61D0B10237EB244EEB4B7B514DBFAB0 /* Pods-TesteArenaFelipePerius */ = { + isa = PBXGroup; + children = ( + F795E34A2B46F6A518CBC464BEA75A2A /* Pods-TesteArenaFelipePerius.modulemap */, + 302E410C85087CA7C26E35FD48A1E509 /* Pods-TesteArenaFelipePerius-acknowledgements.markdown */, + 5E77241F9605B8A7F83DF2DB34F77071 /* Pods-TesteArenaFelipePerius-acknowledgements.plist */, + A0F6A23D3C138A29DF8BC2E5613ADE5F /* Pods-TesteArenaFelipePerius-dummy.m */, + CAD1B28227AB07744424DB8AD255D247 /* Pods-TesteArenaFelipePerius-frameworks.sh */, + BA51C0542663CDE5D4F2E74FAB7E90DE /* Pods-TesteArenaFelipePerius-Info.plist */, + 7A41162F8C3C8FA29AF02A02EA24EE6E /* Pods-TesteArenaFelipePerius-umbrella.h */, + 684127AE06A9196946D34747A4DF3EE6 /* Pods-TesteArenaFelipePerius.debug.xcconfig */, + 7C7B176505F1DDC75AD4F887EF2440ED /* Pods-TesteArenaFelipePerius.release.xcconfig */, + ); + name = "Pods-TesteArenaFelipePerius"; + path = "Target Support Files/Pods-TesteArenaFelipePerius"; + sourceTree = ""; + }; + E8F5F5926F3B3D3871021A4A61728D45 /* Pods */ = { + isa = PBXGroup; + children = ( + 5DB5F3F18FF7EF15D0BB9F575CD07440 /* Alamofire */, + 1716B54F87277B2EE1A8D84190A20704 /* ObjectMapper */, + 12DBBEA06433DA6962631C79D15BA125 /* RxSwift */, + ); + name = Pods; + sourceTree = ""; + }; + FD0B0B9601D6BC734C4CABE82D310C4D /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests */ = { + isa = PBXGroup; + children = ( + 7E68DF55DEB7CD02DE5158370E9FA864 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.modulemap */, + BC32A04C153C7C7BF0C3BDB20655BCEF /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.markdown */, + C6F25BBEC57F8C0BCBA311348977D317 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.plist */, + F2DD4F18E82C2C328B3CA26AF8D04C57 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-dummy.m */, + CB512A2C06D80DE1C223486D5735785C /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh */, + D8811E1913260F048DE79BDAF377AFA7 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-Info.plist */, + 42F33AEDBA4FA13CC573232F8EC7241C /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-umbrella.h */, + 2C7FE134A06BB710C0240058346388D2 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig */, + 4E23D83A1B3AF9552D60EAE3F2D3B295 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.release.xcconfig */, + ); + name = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests"; + path = "Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests"; + sourceTree = ""; + }; + FF16CB386C8121BD283EEEE3E67F35B2 /* Support Files */ = { + isa = PBXGroup; + children = ( + 301FB963ABEB224516EDC5C6B6507417 /* ObjectMapper.modulemap */, + 98DCACDA85E1B8B543CDA7CA7ABCD893 /* ObjectMapper.xcconfig */, + F87F786C32AF9EFCFA59FAFE64254A51 /* ObjectMapper-dummy.m */, + 43A85B5D792CC4BF1B54B76B0F8C90DB /* ObjectMapper-Info.plist */, + 9D980CF62CE0957F1A84246BDB2CF5E1 /* ObjectMapper-prefix.pch */, + BD4A9D9A449CE940DF10A0BA19A75320 /* ObjectMapper-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/ObjectMapper"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 4134C6D7FEC0F3CCD2644FAAB81A718A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + DD9A097C36C3873144EA020049CF4F96 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 739334C9A156F2C4271E367C80398073 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 4272E36E41C4EB360E99140A3B296E6D /* Pods-TesteArenaFelipePerius-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 935933105543B4D630DCCF2C7DD6CEB6 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 33EC05F4BA313C6C66BC76BD41368178 /* Pods-TesteArenaFelipePeriusTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ADDF288DD930A46B5F0F198C225895C9 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 00FA97D56201027AEB1C7692A2C3CF8B /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C3F5B833DB2D2F2AD762974D63064320 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 3D1AFEF6601D082C6044491ECC6AB7DE /* RxSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CCA6E17C793ED5BE6A94E6948D844AE5 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B4A09A31159DC4BBD705B24893E7AC38 /* ObjectMapper-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 162E649F50FEC62B61BDD87D1BD422B4 /* ObjectMapper */ = { + isa = PBXNativeTarget; + buildConfigurationList = E87F6954491067B29ADB27A94D68AA11 /* Build configuration list for PBXNativeTarget "ObjectMapper" */; + buildPhases = ( + CCA6E17C793ED5BE6A94E6948D844AE5 /* Headers */, + 39B28AE5344BF7EAB543FC2C9D39AE75 /* Sources */, + ED1637C96BF54A5D16D10C9E2A6FEA60 /* Frameworks */, + DB00122A85F347C8D68E5E2B7D815A51 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = ObjectMapper; + productName = ObjectMapper; + productReference = B9084FE779702931E8DF1D00A2D725FB /* ObjectMapper.framework */; + productType = "com.apple.product-type.framework"; + }; + 972E4A1BAE7D531E3E4072EA3768E9D8 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = BD53AC16DBAF22C0CECAA0CA7065DA51 /* Build configuration list for PBXNativeTarget "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests" */; + buildPhases = ( + 4134C6D7FEC0F3CCD2644FAAB81A718A /* Headers */, + 52CD029BFE5339C65B4BDE70DA9004D2 /* Sources */, + FC1418521A50C9E2BCB487656F55920C /* Frameworks */, + B6A16004FBB30BEE2030ECA54FE35599 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + FBBFCA2012548BEBD4BD0D327D63C501 /* PBXTargetDependency */, + 001BDBABBD3AD35FF82F09EE70D74E6D /* PBXTargetDependency */, + D5E7C3A8929B215469366DC8B28EB79F /* PBXTargetDependency */, + ); + name = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests"; + productName = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests"; + productReference = B66304FC05BAE44E6A8D8BCA6E01CF0A /* Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework */; + productType = "com.apple.product-type.framework"; + }; + 9EADA57C421A18B89B0E0CBCDBF2E9A7 /* Pods-TesteArenaFelipePerius */ = { + isa = PBXNativeTarget; + buildConfigurationList = 825B338BBD2284E6A83ED607847B4FF0 /* Build configuration list for PBXNativeTarget "Pods-TesteArenaFelipePerius" */; + buildPhases = ( + 739334C9A156F2C4271E367C80398073 /* Headers */, + 80D19A5E4C1B9822C977BB0B40B05AEB /* Sources */, + 86D44ED0C44E607770A522CB2F9D6DBC /* Frameworks */, + 681A15772CB0D1398C72BF79BADD2F92 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + DDBD5604CFFDF31C58CBCB579251817C /* PBXTargetDependency */, + 9F04654118755C2F89D11E532D9B4BF9 /* PBXTargetDependency */, + 14BD5B52BB777C6D71F920ED5859E74C /* PBXTargetDependency */, + ); + name = "Pods-TesteArenaFelipePerius"; + productName = "Pods-TesteArenaFelipePerius"; + productReference = DD9220B67AC9D2D96B57F728460F5F0E /* Pods_TesteArenaFelipePerius.framework */; + productType = "com.apple.product-type.framework"; + }; + D633A917761FE7A6C5F25E7B60FFE567 /* Pods-TesteArenaFelipePeriusTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6C7915D9BFBD3F80D7C07D8FA49B243F /* Build configuration list for PBXNativeTarget "Pods-TesteArenaFelipePeriusTests" */; + buildPhases = ( + 935933105543B4D630DCCF2C7DD6CEB6 /* Headers */, + 3855B4724BB0C0750F817A883F40F8F6 /* Sources */, + 15F9D6A1AC1EB5534CAB12B718BC8D6A /* Frameworks */, + 259B5CE04430BF9E49A786191DBC382A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 678D14F98ACC2323EAEC595D177A975D /* PBXTargetDependency */, + ); + name = "Pods-TesteArenaFelipePeriusTests"; + productName = "Pods-TesteArenaFelipePeriusTests"; + productReference = E45B8D14F6F0760A64824904F8B607FF /* Pods_TesteArenaFelipePeriusTests.framework */; + productType = "com.apple.product-type.framework"; + }; + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = EEC60CD54D8DD880A0E55E30905C5FE9 /* Build configuration list for PBXNativeTarget "RxSwift" */; + buildPhases = ( + C3F5B833DB2D2F2AD762974D63064320 /* Headers */, + 961AEDB51FF604CD07D88C896344DFBD /* Sources */, + 632D47EB662A2CDDA94BF8DB4967588E /* Frameworks */, + 8A1BC437A6BE247E644BF69C6E9A45E6 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RxSwift; + productName = RxSwift; + productReference = 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift.framework */; + productType = "com.apple.product-type.framework"; + }; + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6B2B8EC7E21CDBFF2BDA26B1B4AC4C0D /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + ADDF288DD930A46B5F0F198C225895C9 /* Headers */, + 7349DB0E9BEBE664696F1DCC25226F26 /* Sources */, + 8B0D8633F410345F93419B8C3D7B6916 /* Frameworks */, + 28FC0024B79C28A420D7C4FEBB9E3AEB /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1100; + LastUpgradeCheck = 1100; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = A78315AB7B960344992D7C26CAC0B091 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */, + 162E649F50FEC62B61BDD87D1BD422B4 /* ObjectMapper */, + 9EADA57C421A18B89B0E0CBCDBF2E9A7 /* Pods-TesteArenaFelipePerius */, + 972E4A1BAE7D531E3E4072EA3768E9D8 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests */, + D633A917761FE7A6C5F25E7B60FFE567 /* Pods-TesteArenaFelipePeriusTests */, + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 259B5CE04430BF9E49A786191DBC382A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 28FC0024B79C28A420D7C4FEBB9E3AEB /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 681A15772CB0D1398C72BF79BADD2F92 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8A1BC437A6BE247E644BF69C6E9A45E6 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B6A16004FBB30BEE2030ECA54FE35599 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DB00122A85F347C8D68E5E2B7D815A51 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 3855B4724BB0C0750F817A883F40F8F6 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B2F8BA3DCA0EFF1C69932408402BC0CF /* Pods-TesteArenaFelipePeriusTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 39B28AE5344BF7EAB543FC2C9D39AE75 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A23B1618251C3B92A365B5669F513796 /* CodableTransform.swift in Sources */, + F2CA9FD6E3A7EFBB13BCEF662D06524B /* CustomDateFormatTransform.swift in Sources */, + EB2E92AFE8E36A23EE6D311736B88B67 /* DataTransform.swift in Sources */, + F60975556A37AD5647ED82DC76E9CF6F /* DateFormatterTransform.swift in Sources */, + 0E478FF7AD49149E802261DB853A2837 /* DateTransform.swift in Sources */, + 664B70329CC935DB023416ADE2F203DC /* DictionaryTransform.swift in Sources */, + 64C60112E347C8B0F4B70760861FA125 /* EnumOperators.swift in Sources */, + 02E11AACB509E00F07FC45B073374310 /* EnumTransform.swift in Sources */, + 3556C30029720A3AF9CDBF70BE28281C /* FromJSON.swift in Sources */, + 9A2E1EA1F0F8F4FA13589FEFC4D712B0 /* HexColorTransform.swift in Sources */, + F9B31EED95B0E98A057B6012F9883DCF /* ImmutableMappable.swift in Sources */, + 96DBFE11AAE27CA46A220B4FB06C355B /* IntegerOperators.swift in Sources */, + 0C9FD48191A4E68417C886A9BA356C76 /* ISO8601DateTransform.swift in Sources */, + 45EF41171CA52C2B9E61E1CCD69DDAB6 /* Map.swift in Sources */, + 9F73038C5D5809B9C54A4D5455C0CA91 /* MapError.swift in Sources */, + BE77AF28ABBCD1A186B56195290331D8 /* Mappable.swift in Sources */, + 7908F4065CB1E8A38293CE28F4936941 /* Mapper.swift in Sources */, + 553CF23D91DC8777B26191C77938004A /* NSDecimalNumberTransform.swift in Sources */, + 78BB4BFABCB498A10A06C02661795CDB /* ObjectMapper-dummy.m in Sources */, + 86D61ED9E92755CAA98639EF12E90D65 /* Operators.swift in Sources */, + 8DA5B74F96053B88D81B4C81C4D42C64 /* ToJSON.swift in Sources */, + 65F3F57891C3534229655745DB094F1B /* TransformOf.swift in Sources */, + BA2A816A2CDE195F83BBC03AB4671980 /* TransformOperators.swift in Sources */, + A35CB412DFB6E16F962F7D2A5E792D5D /* TransformType.swift in Sources */, + F000D6CA12F7C477EC63335B91707775 /* URLTransform.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 52CD029BFE5339C65B4BDE70DA9004D2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9BDBDE47C9E56453E7DA76F530FDAF4C /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7349DB0E9BEBE664696F1DCC25226F26 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 17953A9CF2E354B3E69B9ABC2F367AD9 /* AFError.swift in Sources */, + B1C58F6CED7B3E45170711D9ADF878AF /* Alamofire-dummy.m in Sources */, + B788B3354CCEBE56DFDB963CAFD7F6C2 /* Alamofire.swift in Sources */, + 44127C4B989C9CC6A90D78B66A929A5E /* AlamofireExtended.swift in Sources */, + 0AE06C3AEA6CA45342BA703230ABD2CB /* CachedResponseHandler.swift in Sources */, + E9A5AC2F471699CCA516952A5FEB990B /* DispatchQueue+Alamofire.swift in Sources */, + CACBD166E573774FB5613C34AA6DA7A7 /* EventMonitor.swift in Sources */, + 56EC8ED1535DAB987F3D2B71D4C05773 /* HTTPHeaders.swift in Sources */, + B23E9A5CDA31534491226F4C2EE8F8E6 /* HTTPMethod.swift in Sources */, + 5C4A0685B5A201436AB52EF25829B333 /* MultipartFormData.swift in Sources */, + E07BD425C4EA9ADF15DDFCDB10D0B2FB /* MultipartUpload.swift in Sources */, + 7CF8362BA31492053F5CB165637AE117 /* NetworkReachabilityManager.swift in Sources */, + C7369563F6946D8984124E1A546B6425 /* Notifications.swift in Sources */, + 92811AC5CD9A5004116AE43C4E8FD955 /* OperationQueue+Alamofire.swift in Sources */, + 5D61C8ED0DDCC9F8B576B6514B19EE50 /* ParameterEncoder.swift in Sources */, + 14AB7976E100075ADEA0AB1DB833E72D /* ParameterEncoding.swift in Sources */, + 0419772A87B16DB7DCF405A9E77D671F /* Protector.swift in Sources */, + C64AF152F7928CDB59385528DB65FE19 /* RedirectHandler.swift in Sources */, + 6A22C46CB1EDE471794D9AB2AC10327F /* Request.swift in Sources */, + AD9899986955B2EC1EC20818C860C971 /* RequestInterceptor.swift in Sources */, + 48D97BE7D5CAED273BD2341C239CC934 /* RequestTaskMap.swift in Sources */, + F71789DC91A75033EFB79DB828676451 /* Response.swift in Sources */, + 13457FE4E607509A3B9527B0711033D5 /* ResponseSerialization.swift in Sources */, + 4082513A35C682F2193D002C80F72B79 /* Result+Alamofire.swift in Sources */, + D6B2983389480F48F27A0704EEB5DC81 /* RetryPolicy.swift in Sources */, + 0CC43FF0E31AA320ACFEB0FE6239DF34 /* ServerTrustEvaluation.swift in Sources */, + 69ACE4EEE5A8C1C618B22CC1F7B8EF01 /* Session.swift in Sources */, + 42CDB5C986C78BBC8E5C0185F746CABF /* SessionDelegate.swift in Sources */, + 70517C3BAC2D6614347DEAC15299EB84 /* URLConvertible+URLRequestConvertible.swift in Sources */, + 5D12235D061AEE7459279AAF8C348DFE /* URLEncodedFormEncoder.swift in Sources */, + E4E12208D5246E64B7E6CCAE987ADB03 /* URLRequest+Alamofire.swift in Sources */, + AF92602937CA016548022C600B8CDC16 /* URLSessionConfiguration+Alamofire.swift in Sources */, + 06507A26118BA5ACFBBC8C225776920E /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 80D19A5E4C1B9822C977BB0B40B05AEB /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 891A009970AF42E416E8EF1B4A37A4D1 /* Pods-TesteArenaFelipePerius-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 961AEDB51FF604CD07D88C896344DFBD /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F230322D5145458A896ED7D641D19E64 /* AddRef.swift in Sources */, + CC4E41F3DE4EE1DD1FE4874DECC84A1D /* Amb.swift in Sources */, + 817ED2243443BD343BDC1AB8D5FBC2F1 /* AnonymousDisposable.swift in Sources */, + 4893C8F3929377C85421EFBF81F0836B /* AnonymousObserver.swift in Sources */, + 01583BA662A9872D48D28C751D55B24B /* AnyObserver.swift in Sources */, + 9ECECA1B41F18CE45A4D20709F9A5487 /* AsMaybe.swift in Sources */, + 6CAEF7E0ECDC028227CFBAB36C77BBD2 /* AsSingle.swift in Sources */, + A2C4396DDD4292AD59649AD2CD1F1CC0 /* AsyncLock.swift in Sources */, + 6DE50875734CBFD27A31861B9A75DB78 /* AsyncSubject.swift in Sources */, + 2F8D6B77C3CF5941C1548FF10CB98FC2 /* AtomicInt.swift in Sources */, + CC55AAEFDD8CD4E969A877137A705316 /* Bag+Rx.swift in Sources */, + 78DF56F844DD301803BA5B2B83807C70 /* Bag.swift in Sources */, + 959337D036DC6106477095D6A01F7DB5 /* BehaviorSubject.swift in Sources */, + 877DED3B7D9A8F69418663543A063C82 /* BinaryDisposable.swift in Sources */, + 029C9E6FF8FC37DF72685033033C31D3 /* BooleanDisposable.swift in Sources */, + 5CED4B1037FE7BF72AD9B1309FB8FCE0 /* Buffer.swift in Sources */, + A93F251CEF0CF3B502CEB0D676B91D64 /* Cancelable.swift in Sources */, + 5BBF8DB12A216FCEDECFDC44B35ED69A /* Catch.swift in Sources */, + ABE620144FCB1B1FD36136A228523714 /* CombineLatest+arity.swift in Sources */, + D78C9A5F2CB1916E38F9B4F12073D465 /* CombineLatest+Collection.swift in Sources */, + 0BF18101F110A610E932C09478C19996 /* CombineLatest.swift in Sources */, + AC44B54E0896D07BB51B02001C6A7D8D /* Completable+AndThen.swift in Sources */, + 25FBC375CF8486550BC18F88226B494D /* Completable.swift in Sources */, + A72CEDDB5F5C89EBB49F25267D47FD63 /* CompositeDisposable.swift in Sources */, + 32497A7570F8F1E079F54D79A4F09C5D /* Concat.swift in Sources */, + 79C90FE708909D3BCF611A937D9617A8 /* ConcurrentDispatchQueueScheduler.swift in Sources */, + 43D34BE64EDEF11DB411C336BB81FE26 /* ConcurrentMainScheduler.swift in Sources */, + 33E59ADD313BF01CADE082F171772353 /* ConnectableObservableType.swift in Sources */, + 375AFA552D7C3CF1014A6A06E13B2FD6 /* Create.swift in Sources */, + 06FA813F2102B86983243F467562DD9A /* CurrentThreadScheduler.swift in Sources */, + F43AE958AC1430231576F1D88BBF7D56 /* Debounce.swift in Sources */, + B899AA8ACE377B6CAF904ECEFE9BA81D /* Debug.swift in Sources */, + 04B703D2FC0FFFAD0115D801C676ABB1 /* DefaultIfEmpty.swift in Sources */, + D534CEA49AB76E0432965963395D0C25 /* Deferred.swift in Sources */, + 14989A83765C3E0A66D54CBFD69E1FBD /* Delay.swift in Sources */, + A57F5F585A08486FA53EEA0EA430FF6F /* DelaySubscription.swift in Sources */, + ACD89BDA0B2CEEB7F7827129B0D8B0CC /* Dematerialize.swift in Sources */, + AAAD38EB32589BE4DCD548F9C9104993 /* Deprecated.swift in Sources */, + 1614F9A6C8856359C7575D3B2FC46636 /* DeprecationWarner.swift in Sources */, + AB9E672AF3538B811BC7336A1E90659F /* DispatchQueue+Extensions.swift in Sources */, + 706078C52F15B826E0A6271861CACACA /* DispatchQueueConfiguration.swift in Sources */, + F1BE6785A54BCB788F60491011A8DCD6 /* Disposable.swift in Sources */, + B8467DE1690C9BE8F1CDFE82E795B10A /* Disposables.swift in Sources */, + BF89CD237E2186816E39AA80FD8AB05D /* DisposeBag.swift in Sources */, + E6EAE8A2A8AEF8E4D3A826EB3DFDEDF0 /* DisposeBase.swift in Sources */, + C51A3EBD74ED98E219BAEA9C5CD6C350 /* DistinctUntilChanged.swift in Sources */, + 5B44856C3CE5247C723F6DC3C36BEA9B /* Do.swift in Sources */, + 9A172E50D23699806F98D5B4DB8452C3 /* ElementAt.swift in Sources */, + 8A9188BD8F2C0151543C83C1478766DC /* Empty.swift in Sources */, + 100F129E754B7CB6CF69874F744FB8BC /* Enumerated.swift in Sources */, + 269449A9477302B3E8929B89D0B6CE6E /* Error.swift in Sources */, + 5BF4C747A56403BA9A8C8CDBB38FDC2E /* Errors.swift in Sources */, + E89448038F1372265827DA3C69762228 /* Event.swift in Sources */, + E51871737E176D0F5174853EC7496C7E /* Filter.swift in Sources */, + 1C86F4B6C026B119DFA54B3BCC1BCEF3 /* First.swift in Sources */, + DF1B93A09C32A648C5FEA29F04BBEB35 /* Generate.swift in Sources */, + 09844EAB842B1D906B98799F642926D9 /* GroupBy.swift in Sources */, + 379123DB108E9E446FA6C4B01CB7E807 /* GroupedObservable.swift in Sources */, + 23AF54AD1F0D53DF49F324BEAB4AE536 /* HistoricalScheduler.swift in Sources */, + B5EF8C417B25E730F773ADB61221363B /* HistoricalSchedulerTimeConverter.swift in Sources */, + A0CC0B62A8116013F2AC5A3B5B426FC8 /* ImmediateSchedulerType.swift in Sources */, + BEDA4F82D1D68F7D8ADA400D67C3EAAE /* InfiniteSequence.swift in Sources */, + 0F37E729175217A2CB24F1A8C0B09450 /* InvocableScheduledItem.swift in Sources */, + CCFAC36949B2C8DFC1C2C214ED3290F1 /* InvocableType.swift in Sources */, + F749D5A6764A29C5C6614B3DEE95CD3A /* Just.swift in Sources */, + 5A69133161C31B32CE262348245F5185 /* Lock.swift in Sources */, + 79664C5564F47E2FEDBE3BB373D6465F /* LockOwnerType.swift in Sources */, + 72A8589BDBF13A150E97686672A13F7C /* MainScheduler.swift in Sources */, + 3F3377FE0D4247A5D9EF803F23B1AC90 /* Map.swift in Sources */, + 35779FE4EBB531F83C97750B228BAC6C /* Materialize.swift in Sources */, + 5D7854CB3BAF89CB56DC2FA6FA0F1D7F /* Maybe.swift in Sources */, + F2597F9634495618EAD07B49183CA90E /* Merge.swift in Sources */, + 96EC2785BABA625338A08217F7D7C612 /* Multicast.swift in Sources */, + 66FA53FB8682C7667B27C6A7D05AF59B /* Never.swift in Sources */, + 1BA583010A01C3A7BB60E9D93BDDE18A /* NopDisposable.swift in Sources */, + 3F4ED7110D968DE73EA7602071A6135F /* Observable.swift in Sources */, + 362A02F50D4398E8645F8247F380A55D /* ObservableConvertibleType.swift in Sources */, + 7B8DD8F89C26F047BECB9B33D593CBB6 /* ObservableType+Extensions.swift in Sources */, + CE7DDCBF7C04B230C8DACC7041151064 /* ObservableType+PrimitiveSequence.swift in Sources */, + F6E5DFA17B33C90BB4B73B8E83E12A3D /* ObservableType.swift in Sources */, + 88D07CE931E093D37F12E8621664B79F /* ObserveOn.swift in Sources */, + 2D0B12C1BFC22097EFFE1FD784D35D99 /* ObserverBase.swift in Sources */, + 12C557905671AAC56D2DE2477F0F195F /* ObserverType.swift in Sources */, + 9436C6A5D04E902A2BC07F12F5B93074 /* OperationQueueScheduler.swift in Sources */, + E85C75B6E6D960ABF56E2010726A9B22 /* Optional.swift in Sources */, + D6E7F973C8A561ADA044C0FFE052FA1B /* Platform.Darwin.swift in Sources */, + BD8BC6D483502E11120900CD34A00632 /* Platform.Linux.swift in Sources */, + EEBEFFF677DA6233893B89A14D78CC7A /* PrimitiveSequence+Zip+arity.swift in Sources */, + D196E5F5F8D5565116984ECBD138F28E /* PrimitiveSequence.swift in Sources */, + 0D7A41095DB4717F69E83EB8D9829FD2 /* PriorityQueue.swift in Sources */, + 23A4066ECE04C81C35E644EFADA9E603 /* Producer.swift in Sources */, + C9D795BFFA7E9C3C8D0AEAD6D8919B20 /* PublishSubject.swift in Sources */, + 1758B42B3C615677A6E694DD81370024 /* Queue.swift in Sources */, + C968A9E89E27647D34CFDFCA1BDD65CC /* Range.swift in Sources */, + CC2EA5B0EECDC8026FD81FB3612DA3D3 /* Reactive.swift in Sources */, + 217B9CCB60A28B253D351F5F74AFF385 /* RecursiveLock.swift in Sources */, + 505B0F0C90CB5F50C87275AFB3A1C505 /* RecursiveScheduler.swift in Sources */, + D8E2A362C1777E5DDE88297B7F04A02D /* Reduce.swift in Sources */, + D29659285A04FF140EA4ED20342CF62D /* RefCountDisposable.swift in Sources */, + 2D417D7B258F09BDFAF9E0B7A9010CB3 /* Repeat.swift in Sources */, + D2872BEFA1DCE5EF6F70B768570AE78C /* ReplaySubject.swift in Sources */, + A04DFFBEA2D3249F2611754AA265656B /* RetryWhen.swift in Sources */, + 204C11BBCF868CB47451E165BBB8F09E /* Rx.swift in Sources */, + 3E2F878AB013408C80610FA5201B9364 /* RxMutableBox.swift in Sources */, + F0F964DC2104A764E6E3B5CA0C2DC31E /* RxSwift-dummy.m in Sources */, + 4307469BDE7273054C15E2DF200E5EF9 /* Sample.swift in Sources */, + 627FDF2DF14521C18D4F96B9F6026425 /* Scan.swift in Sources */, + 553A4CA64B6F1A2F3035369860834F6E /* ScheduledDisposable.swift in Sources */, + F215D3929BDA35D18695E2BA2230A644 /* ScheduledItem.swift in Sources */, + E34BC8E5000420228B970B7E2C1D3E10 /* ScheduledItemType.swift in Sources */, + 1A4947A8F9B05CF36DBA9624D34E5401 /* SchedulerServices+Emulation.swift in Sources */, + 49E6A4598830CE43A67733A511A4562E /* SchedulerType.swift in Sources */, + D206A5C308CA2B0DDCD09429B0036E3B /* Sequence.swift in Sources */, + B2BA9BD5B4D7BA8C1843F756B78D9498 /* SerialDispatchQueueScheduler.swift in Sources */, + 644BABA965DD85C4049544C4CD1E2C2D /* SerialDisposable.swift in Sources */, + 46A164FD210C579419A49C8C3A5D6E85 /* ShareReplayScope.swift in Sources */, + 03B41652C8E7BE6ABBF7A931C33A81D0 /* Single.swift in Sources */, + 6B60A21C62A7A0825956F48DADC9B1F7 /* SingleAssignmentDisposable.swift in Sources */, + A2BE21A0FE2E363877D5C0F99AA016EE /* SingleAsync.swift in Sources */, + E3CCA9E0385E9002C620F447E376EC7B /* Sink.swift in Sources */, + 93C870B6E5F3F8FF3F1E20938F097D3E /* Skip.swift in Sources */, + 9360D62F6B93BE806FC527217E88C377 /* SkipUntil.swift in Sources */, + 8F41E28B8975B0B1321B110DD3B91ABC /* SkipWhile.swift in Sources */, + 255EA947703D90486B8457C4795F71C8 /* StartWith.swift in Sources */, + 59F8A559BC4FA908AD167B8FAB6BF03E /* String+Rx.swift in Sources */, + 4B1B70B9BFF1DFF9A3827A62DE72E007 /* SubjectType.swift in Sources */, + F70AB95F5AF01EBE987FADC4CECBAD9B /* SubscribeOn.swift in Sources */, + B9011BFC91920A46CA122F85720C44EE /* SubscriptionDisposable.swift in Sources */, + EC403B493DA9E0F0531C3270D32DA78C /* SwiftSupport.swift in Sources */, + 4627D0E643B7324883728859F3BE00DA /* Switch.swift in Sources */, + 48A99A67AF357300AB3FDEDE730A3CDE /* SwitchIfEmpty.swift in Sources */, + 9CF79BEB6FAA6608FEE07BD6EA4C0980 /* SynchronizedDisposeType.swift in Sources */, + 13183BCA9B70617DE557EC035283629B /* SynchronizedOnType.swift in Sources */, + 69C532B1143A3F9F849278F81AE995BE /* SynchronizedUnsubscribeType.swift in Sources */, + 3C92BA90E647087175525C54F04D66A2 /* TailRecursiveSink.swift in Sources */, + A13555F3AEEFACB76A0399A0DF2D9437 /* Take.swift in Sources */, + E7522A2CA21238B3F43E11CA85CB0824 /* TakeLast.swift in Sources */, + 4624014FCD87250548822907886E6EE0 /* TakeUntil.swift in Sources */, + 7DDD4D07E90C163EF747703B7EC692E5 /* TakeWhile.swift in Sources */, + 13B45E0BEF5335984AF500EDB444E960 /* Throttle.swift in Sources */, + B94F0C9DD64FFE4C479B3F866B22D879 /* Timeout.swift in Sources */, + DB34CB2BAD36A15A2DD37261D3916E57 /* Timer.swift in Sources */, + 30B5DB10E2ECBBF929AAA24796A4A4A3 /* ToArray.swift in Sources */, + A94F4467C6AF8C300477F2EFD03EF690 /* Using.swift in Sources */, + DEC346A5B91D097E6226E81CD5454D42 /* VirtualTimeConverterType.swift in Sources */, + 3FBC333A1E8AD0550775062381566EBD /* VirtualTimeScheduler.swift in Sources */, + 6546BD2ABC8273186A919CFCED10F7D7 /* Window.swift in Sources */, + 751F0B27EAFEA469964C97E637FB5207 /* WithLatestFrom.swift in Sources */, + BF0BC56DB1191B96B14A7E85C762EBD2 /* Zip+arity.swift in Sources */, + CC1F3E44843601482FE0BE51EBB2EB77 /* Zip+Collection.swift in Sources */, + 6C77ADD177D4C2044395C41F7EC88B0D /* Zip.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 001BDBABBD3AD35FF82F09EE70D74E6D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = ObjectMapper; + target = 162E649F50FEC62B61BDD87D1BD422B4 /* ObjectMapper */; + targetProxy = BF2CD561EC320D8224A3824ECF4E71E1 /* PBXContainerItemProxy */; + }; + 14BD5B52BB777C6D71F920ED5859E74C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 2C7C3C60706C1FC2B104266E6FDE8F81 /* PBXContainerItemProxy */; + }; + 678D14F98ACC2323EAEC595D177A975D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Pods-TesteArenaFelipePerius"; + target = 9EADA57C421A18B89B0E0CBCDBF2E9A7 /* Pods-TesteArenaFelipePerius */; + targetProxy = C8A2EAC0144968ED0493F92679375379 /* PBXContainerItemProxy */; + }; + 9F04654118755C2F89D11E532D9B4BF9 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = ObjectMapper; + target = 162E649F50FEC62B61BDD87D1BD422B4 /* ObjectMapper */; + targetProxy = 13CD5DF3EAF6E05DC555C1C3A436AD21 /* PBXContainerItemProxy */; + }; + D5E7C3A8929B215469366DC8B28EB79F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 215A64B1AF5EC90AF2ECB0294BA26BE1 /* PBXContainerItemProxy */; + }; + DDBD5604CFFDF31C58CBCB579251817C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 47FB802B4F6F8C7DC36269145B9EFA52 /* PBXContainerItemProxy */; + }; + FBBFCA2012548BEBD4BD0D327D63C501 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 756B3B9D4245827E7CDADF93DFE9EBAE /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 00319A2330DC739FCBFBB6CFB0C5F58D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 25696832ECA3AF6FBA021162CD9DC53E /* Alamofire.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 13049AA41BBA470FCF6FD2872090678C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 98DCACDA85E1B8B543CDA7CA7ABCD893 /* ObjectMapper.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/ObjectMapper/ObjectMapper-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/ObjectMapper/ObjectMapper-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/ObjectMapper/ObjectMapper.modulemap"; + PRODUCT_MODULE_NAME = ObjectMapper; + PRODUCT_NAME = ObjectMapper; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 1ED1F44165CC2AF16C51E4FBDCEE538A /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9F679050B0FD7100AECF1EF118B1A023 /* RxSwift.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/RxSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + PRODUCT_MODULE_NAME = RxSwift; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 2A86D1004FFE5A00E6FD50C766309253 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4E23D83A1B3AF9552D60EAE3F2D3B295 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 314CE90F4B98A28526664FB89D8B7D34 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7C7B176505F1DDC75AD4F887EF2440ED /* Pods-TesteArenaFelipePerius.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 702D26FE60B046FEC5D74C9FDAD6318C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9F679050B0FD7100AECF1EF118B1A023 /* RxSwift.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/RxSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + PRODUCT_MODULE_NAME = RxSwift; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 939F1A8F6BCEB7F9F64D9EEE50CAE014 /* 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; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 969151D5C9AFF80D4FA45D5A6C1D8F04 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2C7FE134A06BB710C0240058346388D2 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + AAC32C769BB7275DEFD11A5D52A8613B /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 98DCACDA85E1B8B543CDA7CA7ABCD893 /* ObjectMapper.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/ObjectMapper/ObjectMapper-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/ObjectMapper/ObjectMapper-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/ObjectMapper/ObjectMapper.modulemap"; + PRODUCT_MODULE_NAME = ObjectMapper; + PRODUCT_NAME = ObjectMapper; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + D742D05BDC6FD99B680E24ECBC677980 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C733267DB36BA7634B1C013704DDE71B /* Pods-TesteArenaFelipePeriusTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + E959C100F5F4BEB6A6DE05A2958A79AD /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 684127AE06A9196946D34747A4DF3EE6 /* Pods-TesteArenaFelipePerius.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + ECB437504DF805BD96CAABF97400B526 /* 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; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + EE0DDD7F7520CA5FDF20B41C4E3910ED /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6B41D078EEA17D635B974F06337C94AB /* Pods-TesteArenaFelipePeriusTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + F659822BFF3B3C20B29B76B89800A5E9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 25696832ECA3AF6FBA021162CD9DC53E /* Alamofire.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 939F1A8F6BCEB7F9F64D9EEE50CAE014 /* Debug */, + ECB437504DF805BD96CAABF97400B526 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6B2B8EC7E21CDBFF2BDA26B1B4AC4C0D /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 00319A2330DC739FCBFBB6CFB0C5F58D /* Debug */, + F659822BFF3B3C20B29B76B89800A5E9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6C7915D9BFBD3F80D7C07D8FA49B243F /* Build configuration list for PBXNativeTarget "Pods-TesteArenaFelipePeriusTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D742D05BDC6FD99B680E24ECBC677980 /* Debug */, + EE0DDD7F7520CA5FDF20B41C4E3910ED /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 825B338BBD2284E6A83ED607847B4FF0 /* Build configuration list for PBXNativeTarget "Pods-TesteArenaFelipePerius" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E959C100F5F4BEB6A6DE05A2958A79AD /* Debug */, + 314CE90F4B98A28526664FB89D8B7D34 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + BD53AC16DBAF22C0CECAA0CA7065DA51 /* Build configuration list for PBXNativeTarget "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 969151D5C9AFF80D4FA45D5A6C1D8F04 /* Debug */, + 2A86D1004FFE5A00E6FD50C766309253 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E87F6954491067B29ADB27A94D68AA11 /* Build configuration list for PBXNativeTarget "ObjectMapper" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 13049AA41BBA470FCF6FD2872090678C /* Debug */, + AAC32C769BB7275DEFD11A5D52A8613B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + EEC60CD54D8DD880A0E55E30905C5FE9 /* Build configuration list for PBXNativeTarget "RxSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1ED1F44165CC2AF16C51E4FBDCEE538A /* Debug */, + 702D26FE60B046FEC5D74C9FDAD6318C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/LICENSE.md b/TesteArenaFelipePerius/Pods/RxSwift/LICENSE.md new file mode 100644 index 0000000..d6765d9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher** +**All rights reserved.** + +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. \ No newline at end of file diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/AtomicInt.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/AtomicInt.swift new file mode 100644 index 0000000..d8d9580 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/AtomicInt.swift @@ -0,0 +1,71 @@ +// +// AtomicInt.swift +// Platform +// +// Created by Krunoslav Zaher on 10/28/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +import class Foundation.NSLock + +final class AtomicInt: NSLock { + fileprivate var value: Int32 + public init(_ value: Int32 = 0) { + self.value = value + } +} + +@discardableResult +@inline(__always) +func add(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value += value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func sub(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value -= value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func fetchOr(_ this: AtomicInt, _ mask: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value |= mask + this.unlock() + return oldValue +} + +@inline(__always) +func load(_ this: AtomicInt) -> Int32 { + this.lock() + let oldValue = this.value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func increment(_ this: AtomicInt) -> Int32 { + return add(this, 1) +} + +@discardableResult +@inline(__always) +func decrement(_ this: AtomicInt) -> Int32 { + return sub(this, 1) +} + +@inline(__always) +func isFlagSet(_ this: AtomicInt, _ mask: Int32) -> Bool { + return (load(this) & mask) != 0 +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/Bag.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/Bag.swift new file mode 100644 index 0000000..4ad0a2b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/Bag.swift @@ -0,0 +1,187 @@ +// +// Bag.swift +// Platform +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Swift + +let arrayDictionaryMaxSize = 30 + +struct BagKey { + /** + Unique identifier for object added to `Bag`. + + It's underlying type is UInt64. If we assume there in an idealized CPU that works at 4GHz, + it would take ~150 years of continuous running time for it to overflow. + */ + fileprivate let rawValue: UInt64 +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion and deletion is O(n). + +It is suitable for storing small number of elements. +*/ +struct Bag : CustomDebugStringConvertible { + /// Type of identifier for inserted elements. + typealias KeyType = BagKey + + typealias Entry = (key: BagKey, value: T) + + fileprivate var _nextKey: BagKey = BagKey(rawValue: 0) + + // data + + // first fill inline variables + var _key0: BagKey? + var _value0: T? + + // then fill "array dictionary" + var _pairs = ContiguousArray() + + // last is sparse dictionary + var _dictionary: [BagKey: T]? + + var _onlyFastPath = true + + /// Creates new empty `Bag`. + init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + mutating func insert(_ element: T) -> BagKey { + let key = _nextKey + + _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append((key: key, value: element)) + return key + } + + _dictionary = [key: element] + + return key + } + + /// - returns: Number of elements in bag. + var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount + } + + /// Removes all elements from bag and clears capacity. + mutating func removeAll() { + _key0 = nil + _value0 = nil + + _pairs.removeAll(keepingCapacity: false) + _dictionary?.removeAll(keepingCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + mutating func removeKey(_ key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if let existingObject = _dictionary?.removeValue(forKey: key) { + return existingObject + } + + for i in 0 ..< _pairs.count where _pairs[i].key == key { + let value = _pairs[i].value + _pairs.remove(at: i) + return value + } + + return nil + } +} + +extension Bag { + /// A textual representation of `self`, suitable for debugging. + var debugDescription : String { + return "\(self.count) elements in Bag" + } +} + +extension Bag { + /// Enumerates elements inside the bag. + /// + /// - parameter action: Enumeration closure. + func forEach(_ action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let value0 = _value0 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + for i in 0 ..< _pairs.count { + action(_pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension BagKey: Hashable { + #if swift(>=4.2) + func hash(into hasher: inout Hasher) { + hasher.combine(rawValue) + } + #else + var hashValue: Int { + return rawValue.hashValue + } + #endif +} + +func ==(lhs: BagKey, rhs: BagKey) -> Bool { + return lhs.rawValue == rhs.rawValue +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 0000000..5a573a0 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift @@ -0,0 +1,26 @@ +// +// InfiniteSequence.swift +// Platform +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Sequence that repeats `repeatedValue` infinite number of times. +struct InfiniteSequence : Sequence { + typealias Element = E + typealias Iterator = AnyIterator + + private let _repeatedValue: E + + init(repeatedValue: E) { + _repeatedValue = repeatedValue + } + + func makeIterator() -> Iterator { + let repeatedValue = _repeatedValue + return AnyIterator { + return repeatedValue + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 0000000..f7cb99c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift @@ -0,0 +1,111 @@ +// +// PriorityQueue.swift +// Platform +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct PriorityQueue { + private let _hasHigherPriority: (Element, Element) -> Bool + private let _isEqual: (Element, Element) -> Bool + + fileprivate var _elements = [Element]() + + init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) { + _hasHigherPriority = hasHigherPriority + _isEqual = isEqual + } + + mutating func enqueue(_ element: Element) { + _elements.append(element) + bubbleToHigherPriority(_elements.count - 1) + } + + func peek() -> Element? { + return _elements.first + } + + var isEmpty: Bool { + return _elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(_ element: Element) { + for i in 0 ..< _elements.count { + if _isEqual(_elements[i], element) { + removeAt(i) + return + } + } + } + + private mutating func removeAt(_ index: Int) { + let removingLast = index == _elements.count - 1 + if !removingLast { + _elements.swapAt(index, _elements.count - 1) + } + + _ = _elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < _elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + guard _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) else { break } + _elements.swapAt(unbalancedIndex, parentIndex) + unbalancedIndex = parentIndex + } + } + + private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < _elements.count) + + var unbalancedIndex = initialUnbalancedIndex + while true { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < _elements.count && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + guard highestPriorityIndex != unbalancedIndex else { break } + _elements.swapAt(highestPriorityIndex, unbalancedIndex) + + unbalancedIndex = highestPriorityIndex + } + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + return _elements.debugDescription + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/Queue.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/Queue.swift new file mode 100644 index 0000000..d05726c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DataStructures/Queue.swift @@ -0,0 +1,152 @@ +// +// Queue.swift +// Platform +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +struct Queue: Sequence { + /// Type of generator. + typealias Generator = AnyIterator + + private let _resizeFactor = 2 + + private var _storage: ContiguousArray + private var _count = 0 + private var _pushNextIndex = 0 + private let _initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + init(capacity: Int) { + _initialCapacity = capacity + + _storage = ContiguousArray(repeating: nil, count: capacity) + } + + private var dequeueIndex: Int { + let index = _pushNextIndex - count + return index < 0 ? index + _storage.count : index + } + + /// - returns: Is queue empty. + var isEmpty: Bool { + return count == 0 + } + + /// - returns: Number of elements inside queue. + var count: Int { + return _count + } + + /// - returns: Element in front of a list of elements to `dequeue`. + func peek() -> T { + precondition(count > 0) + + return _storage[dequeueIndex]! + } + + mutating private func resizeTo(_ size: Int) { + var newStorage = ContiguousArray(repeating: nil, count: size) + + let count = _count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = _storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = _storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = _storage[0 ..< numberOfElementsInSecondBatch] + + _count = count + _pushNextIndex = count + _storage = newStorage + } + + /// Enqueues `element`. + /// + /// - parameter element: Element to enqueue. + mutating func enqueue(_ element: T) { + if count == _storage.count { + resizeTo(Swift.max(_storage.count, 1) * _resizeFactor) + } + + _storage[_pushNextIndex] = element + _pushNextIndex += 1 + _count += 1 + + if _pushNextIndex >= _storage.count { + _pushNextIndex -= _storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + _storage[index] = nil + _count -= 1 + } + + return _storage[index]! + } + + /// Dequeues element or throws an exception in case queue is empty. + /// + /// - returns: Dequeued element. + mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = _storage.count / (_resizeFactor * _resizeFactor) + if _count < downsizeLimit && downsizeLimit >= _initialCapacity { + resizeTo(_storage.count / _resizeFactor) + } + } + + return dequeueElementOnly() + } + + /// - returns: Generator of contained elements. + func makeIterator() -> AnyIterator { + var i = dequeueIndex + var count = _count + + return AnyIterator { + if count == 0 { + return nil + } + + defer { + count -= 1 + i += 1 + } + + if i >= self._storage.count { + i -= self._storage.count + } + + return self._storage[i] + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/DeprecationWarner.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DeprecationWarner.swift new file mode 100644 index 0000000..863636b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DeprecationWarner.swift @@ -0,0 +1,43 @@ +// +// DeprecationWarner.swift +// Platform +// +// Created by Shai Mishali on 1/9/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if DEBUG + class DeprecationWarner { + private static var warned = Set() + private static var _lock = NSRecursiveLock() + + static func warnIfNeeded(_ kind: Kind) { + _lock.lock(); defer { _lock.unlock() } + guard !warned.contains(kind) else { return } + + warned.insert(kind) + print("ℹ️ [DEPRECATED] \(kind.message)") + } + } + + extension DeprecationWarner { + enum Kind { + case variable + case globalTestFunctionNext + case globalTestFunctionError + case globalTestFunctionCompleted + + var message: String { + switch self { + case .variable: return "`Variable` is planned for future deprecation. Please consider `BehaviorRelay` as a replacement. Read more at: https://git.io/vNqvx" + case .globalTestFunctionNext: return "The `next()` global function is planned for future deprecation. Please use `Recorded.next()` instead." + case .globalTestFunctionError: return "The `error()` global function is planned for future deprecation. Please use `Recorded.error()` instead." + case .globalTestFunctionCompleted: return "The `completed()` global function is planned for future deprecation. Please use `Recorded.completed()` instead." + } + } + } + } +#endif + diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 0000000..552314a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift @@ -0,0 +1,21 @@ +// +// DispatchQueue+Extensions.swift +// Platform +// +// Created by Krunoslav Zaher on 10/22/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +extension DispatchQueue { + private static var token: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + return DispatchQueue.getSpecific(key: token) != nil + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/Platform.Darwin.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/Platform.Darwin.swift new file mode 100644 index 0000000..6dc36ad --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/Platform.Darwin.swift @@ -0,0 +1,36 @@ +// +// Platform.Darwin.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import class Foundation.Thread + import protocol Foundation.NSCopying + + extension Thread { + static func setThreadLocalStorageValue(_ value: T?, forKey key: NSCopying) { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: NSCopying) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/Platform.Linux.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/Platform.Linux.swift new file mode 100644 index 0000000..570f8f0 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/Platform.Linux.swift @@ -0,0 +1,37 @@ +// +// Platform.Linux.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + + import class Foundation.Thread + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: String) { + let currentThread = Thread.current + var threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + + currentThread.threadDictionary = threadDictionary + } + + static func getThreadLocalStorageValueForKey(_ key: String) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/TesteArenaFelipePerius/Pods/RxSwift/Platform/RecursiveLock.swift b/TesteArenaFelipePerius/Pods/RxSwift/Platform/RecursiveLock.swift new file mode 100644 index 0000000..c03471d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/Platform/RecursiveLock.swift @@ -0,0 +1,34 @@ +// +// RecursiveLock.swift +// Platform +// +// Created by Krunoslav Zaher on 12/18/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import class Foundation.NSRecursiveLock + +#if TRACE_RESOURCES + class RecursiveLock: NSRecursiveLock { + override init() { + _ = Resources.incrementTotal() + super.init() + } + + override func lock() { + super.lock() + _ = Resources.incrementTotal() + } + + override func unlock() { + super.unlock() + _ = Resources.decrementTotal() + } + + deinit { + _ = Resources.decrementTotal() + } + } +#else + typealias RecursiveLock = NSRecursiveLock +#endif diff --git a/TesteArenaFelipePerius/Pods/RxSwift/README.md b/TesteArenaFelipePerius/Pods/RxSwift/README.md new file mode 100644 index 0000000..17c8a95 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/README.md @@ -0,0 +1,217 @@ +Miss Electric Eel 2016 RxSwift: ReactiveX for Swift +====================================== + +[![Travis CI](https://travis-ci.org/ReactiveX/RxSwift.svg?branch=master)](https://travis-ci.org/ReactiveX/RxSwift) ![platforms](https://img.shields.io/badge/platforms-iOS%20%7C%20macOS%20%7C%20tvOS%20%7C%20watchOS%20%7C%20Linux-333333.svg) [![pod](https://img.shields.io/cocoapods/v/RxSwift.svg)](https://cocoapods.org/pods/RxSwift) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Swift Package Manager compatible](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager) + +* RxSwift 3.x / Swift 3.x can be found in [**rxswift-3.0** branch](https://github.com/ReactiveX/RxSwift/tree/rxswift-3.0). + +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface. + +This is a Swift version of [Rx](https://github.com/Reactive-Extensions/Rx.NET). + +It tries to port as many concepts from the original version as possible, but some concepts were adapted for more pleasant and performant integration with iOS/macOS environment. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like the original Rx, its intention is to enable easy composition of asynchronous operations and event/data streams. + +KVO observing, async operations and streams are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with other libraries](Documentation/ComparisonWithOtherLibraries.md). + + +###### ... find compatible + +* libraries from [RxSwiftCommunity](https://github.com/RxSwiftCommunity). +* [Pods using RxSwift](https://cocoapods.org/?q=uses%3Arxswift). + +###### ... see the broader vision + +* Does this exist for Android? [RxJava](https://github.com/ReactiveX/RxJava) +* Where is all of this going, what is the future, what about reactive architectures, how do you design entire apps this way? [Cycle.js](https://github.com/cyclejs/cycle-core) - this is javascript, but [RxJS](https://github.com/Reactive-Extensions/RxJS) is javascript version of Rx. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(0.3, scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchErrorJustReturn([])
+    }
+    .observeOn(MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 9.0 +* Swift 4.0 +* Swift 3.x ([use `rxswift-3.0` branch](https://github.com/ReactiveX/RxSwift/tree/rxswift-3.0) instead) +* Swift 2.3 ([use `rxswift-2.0` branch](https://github.com/ReactiveX/RxSwift/tree/rxswift-2.0) instead) + +## Installation + +Rx doesn't contain any external dependencies. + +These are currently the supported options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +**Tested with `pod --version`: `1.3.1`** + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '~> 4.0' + pod 'RxCocoa', '~> 4.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '~> 4.0' + pod 'RxTest', '~> 4.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### [Carthage](https://github.com/Carthage/Carthage) + +**Tested with `carthage version`: `0.26.2`** + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" ~> 4.0 +``` + +```bash +$ carthage update +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +**Tested with `swift build --version`: `Swift 4.0.0-dev (swiftpm-13126)`** + +Create a `Package.swift` file. + +```swift +// swift-tools-version:4.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", "4.0.0" ..< "5.0.0") + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. ([RxSwift >= 3.4.2](https://github.com/ReactiveX/RxSwift/releases/tag/3.4.2)) + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift-[Platform]` and `RxCocoa-[Platform]` targets + + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Erik Meijer (Wikipedia)](http://en.wikipedia.org/wiki/Erik_Meijer_%28computer_scientist%29) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://www.youtube.com/watch?v=dwP1TNXE6fc) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/AnyObserver.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/AnyObserver.swift new file mode 100644 index 0000000..85a5efa --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/AnyObserver.swift @@ -0,0 +1,72 @@ +// +// AnyObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObserverType`. +/// +/// Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type. +public struct AnyObserver : ObserverType { + /// The type of elements in sequence that observer can observe. + public typealias E = Element + + /// Anonymous event handler type. + public typealias EventHandler = (Event) -> Void + + private let observer: EventHandler + + /// Construct an instance whose `on(event)` calls `eventHandler(event)` + /// + /// - parameter eventHandler: Event handler that observes sequences events. + public init(eventHandler: @escaping EventHandler) { + self.observer = eventHandler + } + + /// Construct an instance whose `on(event)` calls `observer.on(event)` + /// + /// - parameter observer: Observer that receives sequence events. + public init(_ observer: O) where O.E == Element { + self.observer = observer.on + } + + /// Send `event` to this observer. + /// + /// - parameter event: Event instance. + public func on(_ event: Event) { + return self.observer(event) + } + + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + return self + } +} + +extension AnyObserver { + /// Collection of `AnyObserver`s + typealias s = Bag<(Event) -> Void> +} + +extension ObserverType { + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + return AnyObserver(self) + } + + /// Transforms observer of type R to type E using custom transform method. + /// Each event sent to result observer is transformed and sent to `self`. + /// + /// - returns: observer that transforms events. + public func mapObserver(_ transform: @escaping (R) throws -> E) -> AnyObserver { + return AnyObserver { e in + self.on(e.map(transform)) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Cancelable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Cancelable.swift new file mode 100644 index 0000000..1fa7a67 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Cancelable.swift @@ -0,0 +1,13 @@ +// +// Cancelable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents disposable resource with state tracking. +public protocol Cancelable : Disposable { + /// Was resource disposed. + var isDisposed: Bool { get } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift new file mode 100644 index 0000000..80332db --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift @@ -0,0 +1,102 @@ +// +// AsyncLock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +In case nobody holds this lock, the work will be queued and executed immediately +on thread that is requesting lock. + +In case there is somebody currently holding that lock, action will be enqueued. +When owned of the lock finishes with it's processing, it will also execute +and pending work. + +That means that enqueued work could possibly be executed later on a different thread. +*/ +final class AsyncLock + : Disposable + , Lock + , SynchronizedDisposeType { + typealias Action = () -> Void + + var _lock = SpinLock() + + private var _queue: Queue = Queue(capacity: 0) + + private var _isExecuting: Bool = false + private var _hasFaulted: Bool = false + + // lock { + func lock() { + self._lock.lock() + } + + func unlock() { + self._lock.unlock() + } + // } + + private func enqueue(_ action: I) -> I? { + self._lock.lock(); defer { self._lock.unlock() } // { + if self._hasFaulted { + return nil + } + + if self._isExecuting { + self._queue.enqueue(action) + return nil + } + + self._isExecuting = true + + return action + // } + } + + private func dequeue() -> I? { + self._lock.lock(); defer { self._lock.unlock() } // { + if !self._queue.isEmpty { + return self._queue.dequeue() + } + else { + self._isExecuting = false + return nil + } + // } + } + + func invoke(_ action: I) { + let firstEnqueuedAction = self.enqueue(action) + + if let firstEnqueuedAction = firstEnqueuedAction { + firstEnqueuedAction.invoke() + } + else { + // action is enqueued, it's somebody else's concern now + return + } + + while true { + let nextAction = self.dequeue() + + if let nextAction = nextAction { + nextAction.invoke() + } + else { + return + } + } + } + + func dispose() { + self.synchronizedDispose() + } + + func _synchronized_dispose() { + self._queue = Queue(capacity: 0) + self._hasFaulted = true + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/Lock.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/Lock.swift new file mode 100644 index 0000000..b26f5b7 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/Lock.swift @@ -0,0 +1,36 @@ +// +// Lock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol Lock { + func lock() + func unlock() +} + +// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html +typealias SpinLock = RecursiveLock + +extension RecursiveLock : Lock { + @inline(__always) + final func performLocked(_ action: () -> Void) { + self.lock(); defer { self.unlock() } + action() + } + + @inline(__always) + final func calculateLocked(_ action: () -> T) -> T { + self.lock(); defer { self.unlock() } + return action() + } + + @inline(__always) + final func calculateLockedOrFail(_ action: () throws -> T) throws -> T { + self.lock(); defer { self.unlock() } + let result = try action() + return result + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift new file mode 100644 index 0000000..ed6b28a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift @@ -0,0 +1,21 @@ +// +// LockOwnerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol LockOwnerType : class, Lock { + var _lock: RecursiveLock { get } +} + +extension LockOwnerType { + func lock() { + self._lock.lock() + } + + func unlock() { + self._lock.unlock() + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift new file mode 100644 index 0000000..0490a69 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedDisposeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedDisposeType : class, Disposable, Lock { + func _synchronized_dispose() +} + +extension SynchronizedDisposeType { + func synchronizedDispose() { + self.lock(); defer { self.unlock() } + self._synchronized_dispose() + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift new file mode 100644 index 0000000..33aa84f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedOnType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedOnType : class, ObserverType, Lock { + func _synchronized_on(_ event: Event) +} + +extension SynchronizedOnType { + func synchronizedOn(_ event: Event) { + self.lock(); defer { self.unlock() } + self._synchronized_on(event) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift new file mode 100644 index 0000000..bb1aa7e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift @@ -0,0 +1,13 @@ +// +// SynchronizedUnsubscribeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedUnsubscribeType : class { + associatedtype DisposeKey + + func synchronizedUnsubscribe(_ disposeKey: DisposeKey) +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ConnectableObservableType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ConnectableObservableType.swift new file mode 100644 index 0000000..52bf93c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ConnectableObservableType.swift @@ -0,0 +1,19 @@ +// +// ConnectableObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents an observable sequence wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public protocol ConnectableObservableType : ObservableType { + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + func connect() -> Disposable +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Deprecated.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Deprecated.swift new file mode 100644 index 0000000..cb41090 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Deprecated.swift @@ -0,0 +1,228 @@ +// +// Deprecated.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/5/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension Observable { + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + @available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:)") + public static func from(_ optional: E?) -> Observable { + return Observable.from(optional: optional) + } + + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the optional element on. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + @available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:scheduler:)") + public static func from(_ optional: E?, scheduler: ImmediateSchedulerType) -> Observable { + return Observable.from(optional: optional, scheduler: scheduler) + } +} + +extension ObservableType { + /** + + Projects each element of an observable sequence into a new form by incorporating the element's index. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter selector: A transform function to apply to each source element; the second parameter of the function represents the index of the source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + @available(*, deprecated, message: "Please use enumerated().map()") + public func mapWithIndex(_ selector: @escaping (E, Int) throws -> R) + -> Observable { + return self.enumerated().map { try selector($0.element, $0.index) } + } + + + /** + + Projects each element of an observable sequence to an observable sequence by incorporating the element's index and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element; the second parameter of the function represents the index of the source element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + @available(*, deprecated, message: "Please use enumerated().flatMap()") + public func flatMapWithIndex(_ selector: @escaping (E, Int) throws -> O) + -> Observable { + return self.enumerated().flatMap { try selector($0.element, $0.index) } + } + + /** + + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + The element's index is used in the logic of the predicate function. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + @available(*, deprecated, message: "Please use enumerated().skipWhile().map()") + public func skipWhileWithIndex(_ predicate: @escaping (E, Int) throws -> Bool) -> Observable { + return self.enumerated().skipWhile { try predicate($0.element, $0.index) }.map { $0.element } + } + + + /** + + Returns elements from an observable sequence as long as a specified condition is true. + + The element's index is used in the logic of the predicate function. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + @available(*, deprecated, message: "Please use enumerated().takeWhile().map()") + public func takeWhileWithIndex(_ predicate: @escaping (E, Int) throws -> Bool) -> Observable { + return self.enumerated().takeWhile { try predicate($0.element, $0.index) }.map { $0.element } + } +} + +extension Disposable { + /// Deprecated in favor of `disposed(by:)` + /// + /// + /// Adds `self` to `bag`. + /// + /// - parameter bag: `DisposeBag` to add `self` to. + @available(*, deprecated, message: "use disposed(by:) instead", renamed: "disposed(by:)") + public func addDisposableTo(_ bag: DisposeBag) { + self.disposed(by: bag) + } +} + + +extension ObservableType { + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays latest element in buffer. + + This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + @available(*, deprecated, message: "use share(replay: 1) instead", renamed: "share(replay:)") + public func shareReplayLatestWhileConnected() + -> Observable { + return self.share(replay: 1, scope: .whileConnected) + } +} + + +extension ObservableType { + + /** + Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays maximum number of elements in buffer. + + This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + @available(*, deprecated, message: "Suggested replacement is `share(replay: 1)`. In case old 3.x behavior of `shareReplay` is required please use `share(replay: 1, scope: .forever)` instead.", renamed: "share(replay:)") + public func shareReplay(_ bufferSize: Int) + -> Observable { + return self.share(replay: bufferSize, scope: .forever) + } +} + +/// Variable is a wrapper for `BehaviorSubject`. +/// +/// Unlike `BehaviorSubject` it can't terminate with error, and when variable is deallocated +/// it will complete its observable sequence (`asObservable`). +/// +/// **This concept will be deprecated from RxSwift but offical migration path hasn't been decided yet.** +/// https://github.com/ReactiveX/RxSwift/issues/1501 +/// +/// Current recommended replacement for this API is `RxCocoa.BehaviorRelay` because: +/// * `Variable` isn't a standard cross platform concept, hence it's out of place in RxSwift target. +/// * It doesn't have a counterpart for handling events (`PublishRelay`). It models state only. +/// * It doesn't have a consistent naming with *Relay or other Rx concepts. +/// * It has an inconsistent memory management model compared to other parts of RxSwift (completes on `deinit`). +/// +/// Once plans are finalized, official availability attribute will be added in one of upcoming versions. +public final class Variable { + + public typealias E = Element + + private let _subject: BehaviorSubject + + private var _lock = SpinLock() + + // state + private var _value: E + + #if DEBUG + fileprivate let _synchronizationTracker = SynchronizationTracker() + #endif + + /// Gets or sets current value of variable. + /// + /// Whenever a new value is set, all the observers are notified of the change. + /// + /// Even if the newly set value is same as the old value, observers are still notified for change. + public var value: E { + get { + self._lock.lock(); defer { self._lock.unlock() } + return self._value + } + set(newValue) { + #if DEBUG + self._synchronizationTracker.register(synchronizationErrorMessage: .variable) + defer { self._synchronizationTracker.unregister() } + #endif + self._lock.lock() + self._value = newValue + self._lock.unlock() + + self._subject.on(.next(newValue)) + } + } + + /// Initializes variable with initial value. + /// + /// - parameter value: Initial variable value. + public init(_ value: Element) { + #if DEBUG + DeprecationWarner.warnIfNeeded(.variable) + #endif + + self._value = value + self._subject = BehaviorSubject(value: value) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + return self._subject + } + + deinit { + self._subject.on(.completed) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposable.swift new file mode 100644 index 0000000..b79c77a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposable.swift @@ -0,0 +1,13 @@ +// +// Disposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource. +public protocol Disposable { + /// Dispose resource. + func dispose() +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift new file mode 100644 index 0000000..6fbd635 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift @@ -0,0 +1,59 @@ +// +// AnonymousDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an Action-based disposable. +/// +/// When dispose method is called, disposal action will be dereferenced. +fileprivate final class AnonymousDisposable : DisposeBase, Cancelable { + public typealias DisposeAction = () -> Void + + private let _isDisposed = AtomicInt(0) + private var _disposeAction: DisposeAction? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + return isFlagSet(self._isDisposed, 1) + } + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter disposeAction: Disposal action which will be run upon calling `dispose`. + fileprivate init(_ disposeAction: @escaping DisposeAction) { + self._disposeAction = disposeAction + super.init() + } + + // Non-deprecated version of the constructor, used by `Disposables.create(with:)` + fileprivate init(disposeAction: @escaping DisposeAction) { + self._disposeAction = disposeAction + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + fileprivate func dispose() { + if fetchOr(self._isDisposed, 1) == 0 { + if let action = self._disposeAction { + self._disposeAction = nil + action() + } + } + } +} + +extension Disposables { + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter dispose: Disposal action which will be run upon calling `dispose`. + public static func create(with dispose: @escaping () -> Void) -> Cancelable { + return AnonymousDisposable(disposeAction: dispose) + } + +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift new file mode 100644 index 0000000..5693268 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift @@ -0,0 +1,53 @@ +// +// BinaryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents two disposable resources that are disposed together. +private final class BinaryDisposable : DisposeBase, Cancelable { + + private let _isDisposed = AtomicInt(0) + + // state + private var _disposable1: Disposable? + private var _disposable2: Disposable? + + /// - returns: Was resource disposed. + var isDisposed: Bool { + return isFlagSet(self._isDisposed, 1) + } + + /// Constructs new binary disposable from two disposables. + /// + /// - parameter disposable1: First disposable + /// - parameter disposable2: Second disposable + init(_ disposable1: Disposable, _ disposable2: Disposable) { + self._disposable1 = disposable1 + self._disposable2 = disposable2 + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + func dispose() { + if fetchOr(self._isDisposed, 1) == 0 { + self._disposable1?.dispose() + self._disposable2?.dispose() + self._disposable1 = nil + self._disposable2 = nil + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable) -> Cancelable { + return BinaryDisposable(disposable1, disposable2) + } + +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift new file mode 100644 index 0000000..a0f5c2f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift @@ -0,0 +1,33 @@ +// +// BooleanDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that can be checked for disposal status. +public final class BooleanDisposable : Cancelable { + + internal static let BooleanDisposableTrue = BooleanDisposable(isDisposed: true) + private var _isDisposed = false + + /// Initializes a new instance of the `BooleanDisposable` class + public init() { + } + + /// Initializes a new instance of the `BooleanDisposable` class with given value + public init(isDisposed: Bool) { + self._isDisposed = isDisposed + } + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + return self._isDisposed + } + + /// Sets the status to disposed, which can be observer through the `isDisposed` property. + public func dispose() { + self._isDisposed = true + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift new file mode 100644 index 0000000..ce0da6a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift @@ -0,0 +1,151 @@ +// +// CompositeDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a group of disposable resources that are disposed together. +public final class CompositeDisposable : DisposeBase, Cancelable { + /// Key used to remove disposable from composite disposable + public struct DisposeKey { + fileprivate let key: BagKey + fileprivate init(key: BagKey) { + self.key = key + } + } + + private var _lock = SpinLock() + + // state + private var _disposables: Bag? = Bag() + + public var isDisposed: Bool { + self._lock.lock(); defer { self._lock.unlock() } + return self._disposables == nil + } + + public override init() { + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self._disposables!.insert(disposable1) + _ = self._disposables!.insert(disposable2) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self._disposables!.insert(disposable1) + _ = self._disposables!.insert(disposable2) + _ = self._disposables!.insert(disposable3) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self._disposables!.insert(disposable1) + _ = self._disposables!.insert(disposable2) + _ = self._disposables!.insert(disposable3) + _ = self._disposables!.insert(disposable4) + + for disposable in disposables { + _ = self._disposables!.insert(disposable) + } + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(disposables: [Disposable]) { + for disposable in disposables { + _ = self._disposables!.insert(disposable) + } + } + + /** + Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + + - parameter disposable: Disposable to add. + - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already + disposed `nil` will be returned. + */ + public func insert(_ disposable: Disposable) -> DisposeKey? { + let key = self._insert(disposable) + + if key == nil { + disposable.dispose() + } + + return key + } + + private func _insert(_ disposable: Disposable) -> DisposeKey? { + self._lock.lock(); defer { self._lock.unlock() } + + let bagKey = self._disposables?.insert(disposable) + return bagKey.map(DisposeKey.init) + } + + /// - returns: Gets the number of disposables contained in the `CompositeDisposable`. + public var count: Int { + self._lock.lock(); defer { self._lock.unlock() } + return self._disposables?.count ?? 0 + } + + /// Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. + /// + /// - parameter disposeKey: Key used to identify disposable to be removed. + public func remove(for disposeKey: DisposeKey) { + self._remove(for: disposeKey)?.dispose() + } + + private func _remove(for disposeKey: DisposeKey) -> Disposable? { + self._lock.lock(); defer { self._lock.unlock() } + return self._disposables?.removeKey(disposeKey.key) + } + + /// Disposes all disposables in the group and removes them from the group. + public func dispose() { + if let disposables = self._dispose() { + disposeAll(in: disposables) + } + } + + private func _dispose() -> Bag? { + self._lock.lock(); defer { self._lock.unlock() } + + let disposeBag = self._disposables + self._disposables = nil + + return disposeBag + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable { + return CompositeDisposable(disposable1, disposable2, disposable3) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable { + var disposables = disposables + disposables.append(disposable1) + disposables.append(disposable2) + disposables.append(disposable3) + return CompositeDisposable(disposables: disposables) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposables: [Disposable]) -> Cancelable { + switch disposables.count { + case 2: + return Disposables.create(disposables[0], disposables[1]) + default: + return CompositeDisposable(disposables: disposables) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/Disposables.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/Disposables.swift new file mode 100644 index 0000000..8cd6e28 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/Disposables.swift @@ -0,0 +1,13 @@ +// +// Disposables.swift +// RxSwift +// +// Created by Mohsen Ramezanpoor on 01/08/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/// A collection of utility methods for common disposable operations. +public struct Disposables { + private init() {} +} + diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift new file mode 100644 index 0000000..22e5cb0 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift @@ -0,0 +1,114 @@ +// +// DisposeBag.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Disposable { + /// Adds `self` to `bag` + /// + /// - parameter bag: `DisposeBag` to add `self` to. + public func disposed(by bag: DisposeBag) { + bag.insert(self) + } +} + +/** +Thread safe bag that disposes added disposables on `deinit`. + +This returns ARC (RAII) like resource management to `RxSwift`. + +In case contained disposables need to be disposed, just put a different dispose bag +or create a new one in its place. + + self.existingDisposeBag = DisposeBag() + +In case explicit disposal is necessary, there is also `CompositeDisposable`. +*/ +public final class DisposeBag: DisposeBase { + + private var _lock = SpinLock() + + // state + fileprivate var _disposables = [Disposable]() + fileprivate var _isDisposed = false + + /// Constructs new empty dispose bag. + public override init() { + super.init() + } + + /// Adds `disposable` to be disposed when dispose bag is being deinited. + /// + /// - parameter disposable: Disposable to add. + public func insert(_ disposable: Disposable) { + self._insert(disposable)?.dispose() + } + + private func _insert(_ disposable: Disposable) -> Disposable? { + self._lock.lock(); defer { self._lock.unlock() } + if self._isDisposed { + return disposable + } + + self._disposables.append(disposable) + + return nil + } + + /// This is internal on purpose, take a look at `CompositeDisposable` instead. + private func dispose() { + let oldDisposables = self._dispose() + + for disposable in oldDisposables { + disposable.dispose() + } + } + + private func _dispose() -> [Disposable] { + self._lock.lock(); defer { self._lock.unlock() } + + let disposables = self._disposables + + self._disposables.removeAll(keepingCapacity: false) + self._isDisposed = true + + return disposables + } + + deinit { + self.dispose() + } +} + +extension DisposeBag { + + /// Convenience init allows a list of disposables to be gathered for disposal. + public convenience init(disposing disposables: Disposable...) { + self.init() + self._disposables += disposables + } + + /// Convenience init allows an array of disposables to be gathered for disposal. + public convenience init(disposing disposables: [Disposable]) { + self.init() + self._disposables += disposables + } + + /// Convenience function allows a list of disposables to be gathered for disposal. + public func insert(_ disposables: Disposable...) { + self.insert(disposables) + } + + /// Convenience function allows an array of disposables to be gathered for disposal. + public func insert(_ disposables: [Disposable]) { + self._lock.lock(); defer { self._lock.unlock() } + if self._isDisposed { + disposables.forEach { $0.dispose() } + } else { + self._disposables += disposables + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift new file mode 100644 index 0000000..0d4b2fb --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift @@ -0,0 +1,22 @@ +// +// DisposeBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for all disposables. +public class DisposeBase { + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift new file mode 100644 index 0000000..149f866 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift @@ -0,0 +1,32 @@ +// +// NopDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable that does nothing on disposal. +/// +/// Nop = No Operation +fileprivate struct NopDisposable : Disposable { + + fileprivate static let noOp: Disposable = NopDisposable() + + fileprivate init() { + + } + + /// Does nothing. + public func dispose() { + } +} + +extension Disposables { + /** + Creates a disposable that does nothing on disposal. + */ + static public func create() -> Disposable { + return NopDisposable.noOp + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift new file mode 100644 index 0000000..922f20a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift @@ -0,0 +1,113 @@ +// +// RefCountDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. +public final class RefCountDisposable : DisposeBase, Cancelable { + private var _lock = SpinLock() + private var _disposable = nil as Disposable? + private var _primaryDisposed = false + private var _count = 0 + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self._lock.lock(); defer { self._lock.unlock() } + return self._disposable == nil + } + + /// Initializes a new instance of the `RefCountDisposable`. + public init(disposable: Disposable) { + self._disposable = disposable + super.init() + } + + /** + Holds a dependent disposable that when disposed decreases the refcount on the underlying disposable. + + When getter is called, a dependent disposable contributing to the reference count that manages the underlying disposable's lifetime is returned. + */ + public func retain() -> Disposable { + return self._lock.calculateLocked { + if self._disposable != nil { + do { + _ = try incrementChecked(&self._count) + } catch { + rxFatalError("RefCountDisposable increment failed") + } + + return RefCountInnerDisposable(self) + } else { + return Disposables.create() + } + } + } + + /// Disposes the underlying disposable only when all dependent disposables have been disposed. + public func dispose() { + let oldDisposable: Disposable? = self._lock.calculateLocked { + if let oldDisposable = self._disposable, !self._primaryDisposed { + self._primaryDisposed = true + + if self._count == 0 { + self._disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } + + fileprivate func release() { + let oldDisposable: Disposable? = self._lock.calculateLocked { + if let oldDisposable = self._disposable { + do { + _ = try decrementChecked(&self._count) + } catch { + rxFatalError("RefCountDisposable decrement on release failed") + } + + guard self._count >= 0 else { + rxFatalError("RefCountDisposable counter is lower than 0") + } + + if self._primaryDisposed && self._count == 0 { + self._disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } +} + +internal final class RefCountInnerDisposable: DisposeBase, Disposable +{ + private let _parent: RefCountDisposable + private let _isDisposed = AtomicInt(0) + + init(_ parent: RefCountDisposable) { + self._parent = parent + super.init() + } + + internal func dispose() + { + if fetchOr(self._isDisposed, 1) == 0 { + self._parent.release() + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift new file mode 100644 index 0000000..c834f5b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift @@ -0,0 +1,50 @@ +// +// ScheduledDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private let disposeScheduledDisposable: (ScheduledDisposable) -> Disposable = { sd in + sd.disposeInner() + return Disposables.create() +} + +/// Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler. +public final class ScheduledDisposable : Cancelable { + public let scheduler: ImmediateSchedulerType + + private let _isDisposed = AtomicInt(0) + + // state + private var _disposable: Disposable? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + return isFlagSet(self._isDisposed, 1) + } + + /** + Initializes a new instance of the `ScheduledDisposable` that uses a `scheduler` on which to dispose the `disposable`. + + - parameter scheduler: Scheduler where the disposable resource will be disposed on. + - parameter disposable: Disposable resource to dispose on the given scheduler. + */ + public init(scheduler: ImmediateSchedulerType, disposable: Disposable) { + self.scheduler = scheduler + self._disposable = disposable + } + + /// Disposes the wrapped disposable on the provided scheduler. + public func dispose() { + _ = self.scheduler.schedule(self, action: disposeScheduledDisposable) + } + + func disposeInner() { + if fetchOr(self._isDisposed, 1) == 0 { + self._disposable!.dispose() + self._disposable = nil + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift new file mode 100644 index 0000000..22dce36 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift @@ -0,0 +1,75 @@ +// +// SerialDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. +public final class SerialDisposable : DisposeBase, Cancelable { + private var _lock = SpinLock() + + // state + private var _current = nil as Disposable? + private var _isDisposed = false + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + return self._isDisposed + } + + /// Initializes a new instance of the `SerialDisposable`. + override public init() { + super.init() + } + + /** + Gets or sets the underlying disposable. + + Assigning this property disposes the previous disposable object. + + If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. + */ + public var disposable: Disposable { + get { + return self._lock.calculateLocked { + return self._current ?? Disposables.create() + } + } + set (newDisposable) { + let disposable: Disposable? = self._lock.calculateLocked { + if self._isDisposed { + return newDisposable + } + else { + let toDispose = self._current + self._current = newDisposable + return toDispose + } + } + + if let disposable = disposable { + disposable.dispose() + } + } + } + + /// Disposes the underlying disposable as well as all future replacements. + public func dispose() { + self._dispose()?.dispose() + } + + private func _dispose() -> Disposable? { + self._lock.lock(); defer { self._lock.unlock() } + if self._isDisposed { + return nil + } + else { + self._isDisposed = true + let current = self._current + self._current = nil + return current + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift new file mode 100644 index 0000000..88d59db --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift @@ -0,0 +1,70 @@ +// +// SingleAssignmentDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + +If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. +*/ +public final class SingleAssignmentDisposable : DisposeBase, Cancelable { + + fileprivate enum DisposeState: Int32 { + case disposed = 1 + case disposableSet = 2 + } + + // state + private let _state = AtomicInt(0) + private var _disposable = nil as Disposable? + + /// - returns: A value that indicates whether the object is disposed. + public var isDisposed: Bool { + return isFlagSet(self._state, DisposeState.disposed.rawValue) + } + + /// Initializes a new instance of the `SingleAssignmentDisposable`. + public override init() { + super.init() + } + + /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. + /// + /// **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** + public func setDisposable(_ disposable: Disposable) { + self._disposable = disposable + + let previousState = fetchOr(self._state, DisposeState.disposableSet.rawValue) + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + rxFatalError("oldState.disposable != nil") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + disposable.dispose() + self._disposable = nil + } + } + + /// Disposes the underlying disposable. + public func dispose() { + let previousState = fetchOr(self._state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + guard let disposable = self._disposable else { + rxFatalError("Disposable not set") + } + disposable.dispose() + self._disposable = nil + } + } + +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift new file mode 100644 index 0000000..430e4c6 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift @@ -0,0 +1,21 @@ +// +// SubscriptionDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct SubscriptionDisposable : Disposable { + private let _key: T.DisposeKey + private weak var _owner: T? + + init(owner: T, key: T.DisposeKey) { + self._owner = owner + self._key = key + } + + func dispose() { + self._owner?.synchronizedUnsubscribe(self._key) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Errors.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Errors.swift new file mode 100644 index 0000000..f17b52d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Errors.swift @@ -0,0 +1,52 @@ +// +// Errors.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +let RxErrorDomain = "RxErrorDomain" +let RxCompositeFailures = "RxCompositeFailures" + +/// Generic Rx error codes. +public enum RxError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error occurred. + case unknown + /// Performing an action on disposed object. + case disposed(object: AnyObject) + /// Aritmetic overflow error. + case overflow + /// Argument out of range error. + case argumentOutOfRange + /// Sequence doesn't contain any elements. + case noElements + /// Sequence contains more than one element. + case moreThanOneElement + /// Timeout error. + case timeout +} + +extension RxError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error occurred." + case .disposed(let object): + return "Object `\(object)` was already disposed." + case .overflow: + return "Arithmetic overflow occurred." + case .argumentOutOfRange: + return "Argument out of range." + case .noElements: + return "Sequence doesn't contain any elements." + case .moreThanOneElement: + return "Sequence contains more than one element." + case .timeout: + return "Sequence timeout." + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Event.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Event.swift new file mode 100644 index 0000000..9193e35 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Event.swift @@ -0,0 +1,106 @@ +// +// Event.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a sequence event. +/// +/// Sequence grammar: +/// **next\* (error | completed)** +public enum Event { + /// Next element is produced. + case next(Element) + + /// Sequence terminated with an error. + case error(Swift.Error) + + /// Sequence completed successfully. + case completed +} + +extension Event : CustomDebugStringConvertible { + /// Description of event. + public var debugDescription: String { + switch self { + case .next(let value): + return "next(\(value))" + case .error(let error): + return "error(\(error))" + case .completed: + return "completed" + } + } +} + +extension Event { + /// Is `completed` or `error` event. + public var isStopEvent: Bool { + switch self { + case .next: return false + case .error, .completed: return true + } + } + + /// If `next` event, returns element value. + public var element: Element? { + if case .next(let value) = self { + return value + } + return nil + } + + /// If `error` event, returns error. + public var error: Swift.Error? { + if case .error(let error) = self { + return error + } + return nil + } + + /// If `completed` event, returns `true`. + public var isCompleted: Bool { + if case .completed = self { + return true + } + return false + } +} + +extension Event { + /// Maps sequence elements using transform. If error happens during the transform, `.error` + /// will be returned as value. + public func map(_ transform: (Element) throws -> Result) -> Event { + do { + switch self { + case let .next(element): + return .next(try transform(element)) + case let .error(error): + return .error(error) + case .completed: + return .completed + } + } + catch let e { + return .error(e) + } + } +} + +/// A type that can be converted to `Event`. +public protocol EventConvertible { + /// Type of element in event + associatedtype ElementType + + /// Event representation of this instance + var event: Event { get } +} + +extension Event : EventConvertible { + /// Event representation of this instance + public var event: Event { + return self + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift new file mode 100644 index 0000000..fc9b22c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift @@ -0,0 +1,50 @@ +// +// Bag+Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/19/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + + +// MARK: forEach + +@inline(__always) +func dispatch(_ bag: Bag<(Event) -> Void>, _ event: Event) { + bag._value0?(event) + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value(event) + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element(event) + } + } +} + +/// Dispatches `dispose` to all disposables contained inside bag. +func disposeAll(in bag: Bag) { + bag._value0?.dispose() + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value.dispose() + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element.dispose() + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift new file mode 100644 index 0000000..70d4786 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift @@ -0,0 +1,22 @@ +// +// String+Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension String { + /// This is needed because on Linux Swift doesn't have `rangeOfString(..., options: .BackwardsSearch)` + func lastIndexOf(_ character: Character) -> Index? { + var index = self.endIndex + while index > self.startIndex { + index = self.index(before: index) + if self[index] == character { + return index + } + } + + return nil + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/GroupedObservable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/GroupedObservable.swift new file mode 100644 index 0000000..c5b0a9d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/GroupedObservable.swift @@ -0,0 +1,37 @@ +// +// GroupedObservable.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an observable sequence of elements that have a common key. +public struct GroupedObservable : ObservableType { + public typealias E = Element + + /// Gets the common key. + public let key: Key + + private let source: Observable + + /// Initializes grouped observable sequence with key and source observable sequence. + /// + /// - parameter key: Grouped observable sequence key + /// - parameter source: Observable sequence that represents sequence of elements for the key + /// - returns: Grouped observable sequence of elements for the specific key + public init(key: Key, source: Observable) { + self.key = key + self.source = source + } + + /// Subscribes `observer` to receive events for this sequence. + public func subscribe(_ observer: O) -> Disposable where O.E == E { + return self.source.subscribe(observer) + } + + /// Converts `self` to `Observable` sequence. + public func asObservable() -> Observable { + return self.source + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift new file mode 100644 index 0000000..954fbf0 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift @@ -0,0 +1,36 @@ +// +// ImmediateSchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an object that immediately schedules units of work. +public protocol ImmediateSchedulerType { + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable +} + +extension ImmediateSchedulerType { + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRecursive(_ state: State, action: @escaping (_ state: State, _ recurse: (State) -> Void) -> Void) -> Disposable { + let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self) + + recursiveScheduler.schedule(state) + + return Disposables.create(with: recursiveScheduler.dispose) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observable.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observable.swift new file mode 100644 index 0000000..08caab4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observable.swift @@ -0,0 +1,44 @@ +// +// Observable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObservableType`. +/// +/// It represents a push style sequence. +public class Observable : ObservableType { + /// Type of elements in sequence. + public typealias E = Element + + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + public func subscribe(_ observer: O) -> Disposable where O.E == E { + rxAbstractMethod() + } + + public func asObservable() -> Observable { + return self + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } + + // this is kind of ugly I know :( + // Swift compiler reports "Not supported yet" when trying to override protocol extensions, so ¯\_(ツ)_/¯ + + /// Optimizations for map operator + internal func composeMap(_ transform: @escaping (Element) throws -> R) -> Observable { + return _map(source: self, transform: transform) + } +} + diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift new file mode 100644 index 0000000..d89c5aa --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift @@ -0,0 +1,18 @@ +// +// ObservableConvertibleType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Type that can be converted to observable sequence (`Observable`). +public protocol ObservableConvertibleType { + /// Type of elements in sequence. + associatedtype E + + /// Converts `self` to `Observable` sequence. + /// + /// - returns: Observable sequence that represents `self`. + func asObservable() -> Observable +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift new file mode 100644 index 0000000..362fc58 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift @@ -0,0 +1,131 @@ +// +// ObservableType+Extensions.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if DEBUG + import Foundation +#endif + +extension ObservableType { + /** + Subscribes an event handler to an observable sequence. + + - parameter on: Action to invoke for each event in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe(_ on: @escaping (Event) -> Void) + -> Disposable { + let observer = AnonymousObserver { e in + on(e) + } + return self.asObservable().subscribe(observer) + } + + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) + -> Disposable { + let disposable: Disposable + + if let disposed = onDisposed { + disposable = Disposables.create(with: disposed) + } + else { + disposable = Disposables.create() + } + + #if DEBUG + let synchronizationTracker = SynchronizationTracker() + #endif + + let callStack = Hooks.recordCallStackOnError ? Hooks.customCaptureSubscriptionCallstack() : [] + + let observer = AnonymousObserver { event in + + #if DEBUG + synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { synchronizationTracker.unregister() } + #endif + + switch event { + case .next(let value): + onNext?(value) + case .error(let error): + if let onError = onError { + onError(error) + } + else { + Hooks.defaultErrorHandler(callStack, error) + } + disposable.dispose() + case .completed: + onCompleted?() + disposable.dispose() + } + } + return Disposables.create( + self.asObservable().subscribe(observer), + disposable + ) + } +} + +import class Foundation.NSRecursiveLock + +extension Hooks { + public typealias DefaultErrorHandler = (_ subscriptionCallStack: [String], _ error: Error) -> Void + public typealias CustomCaptureSubscriptionCallstack = () -> [String] + + fileprivate static let _lock = RecursiveLock() + fileprivate static var _defaultErrorHandler: DefaultErrorHandler = { subscriptionCallStack, error in + #if DEBUG + let serializedCallStack = subscriptionCallStack.joined(separator: "\n") + print("Unhandled error happened: \(error)\n subscription called from:\n\(serializedCallStack)") + #endif + } + fileprivate static var _customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack = { + #if DEBUG + return Thread.callStackSymbols + #else + return [] + #endif + } + + /// Error handler called in case onError handler wasn't provided. + public static var defaultErrorHandler: DefaultErrorHandler { + get { + _lock.lock(); defer { _lock.unlock() } + return _defaultErrorHandler + } + set { + _lock.lock(); defer { _lock.unlock() } + _defaultErrorHandler = newValue + } + } + + /// Subscription callstack block to fetch custom callstack information. + public static var customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack { + get { + _lock.lock(); defer { _lock.unlock() } + return _customCaptureSubscriptionCallstack + } + set { + _lock.lock(); defer { _lock.unlock() } + _customCaptureSubscriptionCallstack = newValue + } + } +} + diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableType.swift new file mode 100644 index 0000000..e41a36a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObservableType.swift @@ -0,0 +1,47 @@ +// +// ObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a push style sequence. +public protocol ObservableType : ObservableConvertibleType { + /** + Subscribes `observer` to receive events for this sequence. + + ### Grammar + + **Next\* (Error | Completed)?** + + * sequences can produce zero or more elements so zero or more `Next` events can be sent to `observer` + * once an `Error` or `Completed` event is sent, the sequence terminates and can't produce any other elements + + It is possible that events are sent from different threads, but no two events can be sent concurrently to + `observer`. + + ### Resource Management + + When sequence sends `Complete` or `Error` event all internal resources that compute sequence elements + will be freed. + + To cancel production of sequence elements and free resources immediately, call `dispose` on returned + subscription. + + - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. + */ + func subscribe(_ observer: O) -> Disposable where O.E == E +} + +extension ObservableType { + + /// Default implementation of converting `ObservableType` to `Observable`. + public func asObservable() -> Observable { + // temporary workaround + //return Observable.create(subscribe: self.subscribe) + return Observable.create { o in + return self.subscribe(o) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AddRef.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AddRef.swift new file mode 100644 index 0000000..a69147c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AddRef.swift @@ -0,0 +1,44 @@ +// +// AddRef.swift +// RxSwift +// +// Created by Junior B. on 30/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AddRefSink : Sink, ObserverType { + typealias Element = O.E + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final class AddRef : Producer { + + private let _source: Observable + private let _refCount: RefCountDisposable + + init(source: Observable, refCount: RefCountDisposable) { + self._source = source + self._refCount = refCount + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let releaseDisposable = self._refCount.retain() + let sink = AddRefSink(observer: observer, cancel: cancel) + let subscription = Disposables.create(releaseDisposable, self._source.subscribe(sink)) + + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Amb.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Amb.swift new file mode 100644 index 0000000..b4b9b7e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Amb.swift @@ -0,0 +1,157 @@ +// +// Amb.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - returns: An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + public static func amb(_ sequence: S) -> Observable + where S.Iterator.Element == Observable { + return sequence.reduce(Observable.never()) { a, o in + return a.amb(o.asObservable()) + } + } +} + +extension ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - parameter right: Second observable sequence. + - returns: An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + public func amb + (_ right: O2) + -> Observable where O2.E == E { + return Amb(left: self.asObservable(), right: right.asObservable()) + } +} + +fileprivate enum AmbState { + case neither + case left + case right +} + +final private class AmbObserver: ObserverType { + typealias Element = O.E + typealias Parent = AmbSink + typealias This = AmbObserver + typealias Sink = (This, Event) -> Void + + fileprivate let _parent: Parent + fileprivate var _sink: Sink + fileprivate var _cancel: Disposable + + init(parent: Parent, cancel: Disposable, sink: @escaping Sink) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + + self._parent = parent + self._sink = sink + self._cancel = cancel + } + + func on(_ event: Event) { + self._sink(self, event) + if event.isStopEvent { + self._cancel.dispose() + } + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final private class AmbSink: Sink { + typealias ElementType = O.E + typealias Parent = Amb + typealias AmbObserverType = AmbObserver + + private let _parent: Parent + + private let _lock = RecursiveLock() + // state + private var _choice = AmbState.neither + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let disposeAll = Disposables.create(subscription1, subscription2) + + let forwardEvent = { (o: AmbObserverType, event: Event) -> Void in + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + let decide = { (o: AmbObserverType, event: Event, me: AmbState, otherSubscription: Disposable) in + self._lock.performLocked { + if self._choice == .neither { + self._choice = me + o._sink = forwardEvent + o._cancel = disposeAll + otherSubscription.dispose() + } + + if self._choice == me { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + } + } + + let sink1 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .left, subscription2) + } + + let sink2 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .right, subscription1) + } + + subscription1.setDisposable(self._parent._left.subscribe(sink1)) + subscription2.setDisposable(self._parent._right.subscribe(sink2)) + + return disposeAll + } +} + +final private class Amb: Producer { + fileprivate let _left: Observable + fileprivate let _right: Observable + + init(left: Observable, right: Observable) { + self._left = left + self._right = right + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = AmbSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift new file mode 100644 index 0000000..d9010dd --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift @@ -0,0 +1,49 @@ +// +// AsMaybe.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +fileprivate final class AsMaybeSink : Sink, ObserverType { + typealias ElementType = O.E + typealias E = ElementType + + private var _element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self._element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self._element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self._element { + self.forwardOn(element) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class AsMaybe: Producer { + fileprivate let _source: Observable + + init(source: Observable) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = AsMaybeSink(observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AsSingle.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AsSingle.swift new file mode 100644 index 0000000..8682f1f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/AsSingle.swift @@ -0,0 +1,52 @@ +// +// AsSingle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +fileprivate final class AsSingleSink : Sink, ObserverType { + typealias ElementType = O.E + typealias E = ElementType + + private var _element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self._element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self._element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self._element { + self.forwardOn(element) + self.forwardOn(.completed) + } + else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class AsSingle: Producer { + fileprivate let _source: Observable + + init(source: Observable) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = AsSingleSink(observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Buffer.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Buffer.swift new file mode 100644 index 0000000..db4cf21 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Buffer.swift @@ -0,0 +1,139 @@ +// +// Buffer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. + + A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. + + - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) + + - parameter timeSpan: Maximum time length of a buffer. + - parameter count: Maximum element count of a buffer. + - parameter scheduler: Scheduler to run buffering timers on. + - returns: An observable sequence of buffers. + */ + public func buffer(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable<[E]> { + return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class BufferTimeCount: Producer<[Element]> { + + fileprivate let _timeSpan: RxTimeInterval + fileprivate let _count: Int + fileprivate let _scheduler: SchedulerType + fileprivate let _source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self._source = source + self._timeSpan = timeSpan + self._count = count + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [Element] { + let sink = BufferTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class BufferTimeCountSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where O.E == [Element] { + typealias Parent = BufferTimeCount + typealias E = Element + + private let _parent: Parent + + let _lock = RecursiveLock() + + // state + private let _timerD = SerialDisposable() + private var _buffer = [Element]() + private var _windowID = 0 + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.createTimer(self._windowID) + return Disposables.create(_timerD, _parent._source.subscribe(self)) + } + + func startNewWindowAndSendCurrentOne() { + self._windowID = self._windowID &+ 1 + let windowID = self._windowID + + let buffer = self._buffer + self._buffer = [] + self.forwardOn(.next(buffer)) + + self.createTimer(windowID) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self._buffer.append(element) + + if self._buffer.count == self._parent._count { + self.startNewWindowAndSendCurrentOne() + } + + case .error(let error): + self._buffer = [] + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(self._buffer)) + self.forwardOn(.completed) + self.dispose() + } + } + + func createTimer(_ windowID: Int) { + if self._timerD.isDisposed { + return + } + + if self._windowID != windowID { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self._timerD.disposable = nextTimer + + let disposable = self._parent._scheduler.scheduleRelative(windowID, dueTime: self._parent._timeSpan) { previousWindowID in + self._lock.performLocked { + if previousWindowID != self._windowID { + return + } + + self.startNewWindowAndSendCurrentOne() + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposable) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Catch.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Catch.swift new file mode 100644 index 0000000..1306076 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Catch.swift @@ -0,0 +1,235 @@ +// +// Catch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + return Catch(source: self.asObservable(), handler: handler) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + public func catchErrorJustReturn(_ element: E) + -> Observable { + return Catch(source: self.asObservable(), handler: { _ in Observable.just(element) }) + } + +} + +extension ObservableType { + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + public static func catchError(_ sequence: S) -> Observable + where S.Iterator.Element == Observable { + return CatchSequence(sources: sequence) + } +} + +extension ObservableType { + + /** + Repeats the source observable sequence until it successfully terminates. + + **This could potentially create an infinite sequence.** + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - returns: Observable sequence to repeat until it successfully terminates. + */ + public func retry() -> Observable { + return CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. + + If you encounter an error and want it to retry once, then you must use `retry(2)` + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter maxAttemptCount: Maximum number of times to repeat the sequence. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + public func retry(_ maxAttemptCount: Int) + -> Observable { + return CatchSequence(sources: Swift.repeatElement(self.asObservable(), count: maxAttemptCount)) + } +} + +// catch with callback + +final private class CatchSinkProxy: ObserverType { + typealias E = O.E + typealias Parent = CatchSink + + private let _parent: Parent + + init(parent: Parent) { + self._parent = parent + } + + func on(_ event: Event) { + self._parent.forwardOn(event) + + switch event { + case .next: + break + case .error, .completed: + self._parent.dispose() + } + } +} + +final private class CatchSink: Sink, ObserverType { + typealias E = O.E + typealias Parent = Catch + + private let _parent: Parent + private let _subscription = SerialDisposable() + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let d1 = SingleAssignmentDisposable() + self._subscription.disposable = d1 + d1.setDisposable(self._parent._source.subscribe(self)) + + return self._subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed: + self.forwardOn(event) + self.dispose() + case .error(let error): + do { + let catchSequence = try self._parent._handler(error) + + let observer = CatchSinkProxy(parent: self) + + self._subscription.disposable = catchSequence.subscribe(observer) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Catch: Producer { + typealias Handler = (Swift.Error) throws -> Observable + + fileprivate let _source: Observable + fileprivate let _handler: Handler + + init(source: Observable, handler: @escaping Handler) { + self._source = source + self._handler = handler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = CatchSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// catch enumerable + +final private class CatchSequenceSink + : TailRecursiveSink + , ObserverType where S.Iterator.Element: ObservableConvertibleType, S.Iterator.Element.E == O.E { + typealias Element = O.E + typealias Parent = CatchSequence + + private var _lastError: Swift.Error? + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error(let error): + self._lastError = error + self.schedule(.moveNext) + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + return source.subscribe(self) + } + + override func done() { + if let lastError = self._lastError { + self.forwardOn(.error(lastError)) + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let onError = observable as? CatchSequence { + return (onError.sources.makeIterator(), nil) + } + else { + return nil + } + } +} + +final private class CatchSequence: Producer where S.Iterator.Element: ObservableConvertibleType { + typealias Element = S.Iterator.Element.E + + let sources: S + + init(sources: S) { + self.sources = sources + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = CatchSequenceSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift new file mode 100644 index 0000000..b62fa29 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift @@ -0,0 +1,157 @@ +// +// CombineLatest+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest(_ collection: C, _ resultSelector: @escaping ([C.Iterator.Element.E]) throws -> E) -> Observable + where C.Iterator.Element: ObservableType { + return CombineLatestCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest(_ collection: C) -> Observable<[E]> + where C.Iterator.Element: ObservableType, C.Iterator.Element.E == E { + return CombineLatestCollectionType(sources: collection, resultSelector: { $0 }) + } +} + +final private class CombineLatestCollectionTypeSink + : Sink where C.Iterator.Element: ObservableConvertibleType { + typealias R = O.E + typealias Parent = CombineLatestCollectionType + typealias SourceElement = C.Iterator.Element.E + + let _parent: Parent + + let _lock = RecursiveLock() + + // state + var _numberOfValues = 0 + var _values: [SourceElement?] + var _isDone: [Bool] + var _numberOfDone = 0 + var _subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._values = [SourceElement?](repeating: nil, count: parent._count) + self._isDone = [Bool](repeating: false, count: parent._count) + self._subscriptions = [SingleAssignmentDisposable]() + self._subscriptions.reserveCapacity(parent._count) + + for _ in 0 ..< parent._count { + self._subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self._lock.lock(); defer { self._lock.unlock() } // { + switch event { + case .next(let element): + if self._values[atIndex] == nil { + self._numberOfValues += 1 + } + + self._values[atIndex] = element + + if self._numberOfValues < self._parent._count { + let numberOfOthersThatAreDone = self._numberOfDone - (self._isDone[atIndex] ? 1 : 0) + if numberOfOthersThatAreDone == self._parent._count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + let result = try self._parent._resultSelector(self._values.map { $0! }) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self._isDone[atIndex] { + return + } + + self._isDone[atIndex] = true + self._numberOfDone += 1 + + if self._numberOfDone == self._parent._count { + self.forwardOn(.completed) + self.dispose() + } + else { + self._subscriptions[atIndex].dispose() + } + } + // } + } + + func run() -> Disposable { + var j = 0 + for i in self._parent._sources { + let index = j + let source = i.asObservable() + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + + self._subscriptions[j].setDisposable(disposable) + + j += 1 + } + + if self._parent._sources.isEmpty { + self.forwardOn(.completed) + } + + return Disposables.create(_subscriptions) + } +} + +final private class CombineLatestCollectionType: Producer where C.Iterator.Element: ObservableConvertibleType { + typealias ResultSelector = ([C.Iterator.Element.E]) throws -> R + + let _sources: C + let _resultSelector: ResultSelector + let _count: Int + + init(sources: C, resultSelector: @escaping ResultSelector) { + self._sources = sources + self._resultSelector = resultSelector + self._count = Int(Int64(self._sources.count)) + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift new file mode 100644 index 0000000..7474bdc --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift @@ -0,0 +1,843 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// CombineLatest+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.E, O2.E) throws -> E) + -> Observable { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2) + -> Observable<(O1.E, O2.E)> { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class CombineLatestSink2_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest2 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self._lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self._lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + + subscription1.setDisposable(self._parent._source1.subscribe(observer1)) + subscription2.setDisposable(self._parent._source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._latestElement1, self._latestElement2) + } +} + +final class CombineLatest2 : Producer { + typealias ResultSelector = (E1, E2) throws -> R + + let _source1: Observable + let _source2: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self._source1 = source1 + self._source2 = source2 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.E, O2.E, O3.E) throws -> E) + -> Observable { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.E, O2.E, O3.E)> { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class CombineLatestSink3_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest3 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self._lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self._lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self._lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + + subscription1.setDisposable(self._parent._source1.subscribe(observer1)) + subscription2.setDisposable(self._parent._source2.subscribe(observer2)) + subscription3.setDisposable(self._parent._source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3) + } +} + +final class CombineLatest3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self._source1 = source1 + self._source2 = source2 + self._source3 = source3 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E) throws -> E) + -> Observable { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.E, O2.E, O3.E, O4.E)> { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class CombineLatestSink4_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest4 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self._lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self._lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self._lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self._lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + + subscription1.setDisposable(self._parent._source1.subscribe(observer1)) + subscription2.setDisposable(self._parent._source2.subscribe(observer2)) + subscription3.setDisposable(self._parent._source3.subscribe(observer3)) + subscription4.setDisposable(self._parent._source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4) + } +} + +final class CombineLatest4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self._source1 = source1 + self._source2 = source2 + self._source3 = source3 + self._source4 = source4 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E) throws -> E) + -> Observable { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E)> { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class CombineLatestSink5_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest5 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self._lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self._lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self._lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self._lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self._lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + + subscription1.setDisposable(self._parent._source1.subscribe(observer1)) + subscription2.setDisposable(self._parent._source2.subscribe(observer2)) + subscription3.setDisposable(self._parent._source3.subscribe(observer3)) + subscription4.setDisposable(self._parent._source4.subscribe(observer4)) + subscription5.setDisposable(self._parent._source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4, self._latestElement5) + } +} + +final class CombineLatest5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self._source1 = source1 + self._source2 = source2 + self._source3 = source3 + self._source4 = source4 + self._source5 = source5 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E) throws -> E) + -> Observable { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E)> { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class CombineLatestSink6_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest6 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + var _latestElement6: E6! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self._lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self._lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self._lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self._lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self._lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self._lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6) + + subscription1.setDisposable(self._parent._source1.subscribe(observer1)) + subscription2.setDisposable(self._parent._source2.subscribe(observer2)) + subscription3.setDisposable(self._parent._source3.subscribe(observer3)) + subscription4.setDisposable(self._parent._source4.subscribe(observer4)) + subscription5.setDisposable(self._parent._source5.subscribe(observer5)) + subscription6.setDisposable(self._parent._source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4, self._latestElement5, self._latestElement6) + } +} + +final class CombineLatest6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self._source1 = source1 + self._source2 = source2 + self._source3 = source3 + self._source4 = source4 + self._source5 = source5 + self._source6 = source6 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E) throws -> E) + -> Observable { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E)> { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class CombineLatestSink7_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest7 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + var _latestElement6: E6! = nil + var _latestElement7: E7! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self._lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self._lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self._lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self._lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self._lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self._lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self._lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self._latestElement7 = e }, this: subscription7) + + subscription1.setDisposable(self._parent._source1.subscribe(observer1)) + subscription2.setDisposable(self._parent._source2.subscribe(observer2)) + subscription3.setDisposable(self._parent._source3.subscribe(observer3)) + subscription4.setDisposable(self._parent._source4.subscribe(observer4)) + subscription5.setDisposable(self._parent._source5.subscribe(observer5)) + subscription6.setDisposable(self._parent._source6.subscribe(observer6)) + subscription7.setDisposable(self._parent._source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4, self._latestElement5, self._latestElement6, self._latestElement7) + } +} + +final class CombineLatest7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + let _source7: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self._source1 = source1 + self._source2 = source2 + self._source3 = source3 + self._source4 = source4 + self._source5 = source5 + self._source6 = source6 + self._source7 = source7 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E) throws -> E) + -> Observable { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E)> { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class CombineLatestSink8_ : CombineLatestSink { + typealias R = O.E + typealias Parent = CombineLatest8 + + let _parent: Parent + + var _latestElement1: E1! = nil + var _latestElement2: E2! = nil + var _latestElement3: E3! = nil + var _latestElement4: E4! = nil + var _latestElement5: E5! = nil + var _latestElement6: E6! = nil + var _latestElement7: E7! = nil + var _latestElement8: E8! = nil + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self._lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self._latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self._lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self._latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self._lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self._latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self._lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self._latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self._lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self._latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self._lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self._latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self._lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self._latestElement7 = e }, this: subscription7) + let observer8 = CombineLatestObserver(lock: self._lock, parent: self, index: 7, setLatestValue: { (e: E8) -> Void in self._latestElement8 = e }, this: subscription8) + + subscription1.setDisposable(self._parent._source1.subscribe(observer1)) + subscription2.setDisposable(self._parent._source2.subscribe(observer2)) + subscription3.setDisposable(self._parent._source3.subscribe(observer3)) + subscription4.setDisposable(self._parent._source4.subscribe(observer4)) + subscription5.setDisposable(self._parent._source5.subscribe(observer5)) + subscription6.setDisposable(self._parent._source6.subscribe(observer6)) + subscription7.setDisposable(self._parent._source7.subscribe(observer7)) + subscription8.setDisposable(self._parent._source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4, self._latestElement5, self._latestElement6, self._latestElement7, self._latestElement8) + } +} + +final class CombineLatest8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> R + + let _source1: Observable + let _source2: Observable + let _source3: Observable + let _source4: Observable + let _source5: Observable + let _source6: Observable + let _source7: Observable + let _source8: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self._source1 = source1 + self._source2 = source2 + self._source3 = source3 + self._source4 = source4 + self._source5 = source5 + self._source6 = source6 + self._source7 = source7 + self._source8 = source8 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = CombineLatestSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift new file mode 100644 index 0000000..dbecf98 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift @@ -0,0 +1,132 @@ +// +// CombineLatest.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol CombineLatestProtocol : class { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class CombineLatestSink + : Sink + , CombineLatestProtocol { + typealias Element = O.E + + let _lock = RecursiveLock() + + private let _arity: Int + private var _numberOfValues = 0 + private var _numberOfDone = 0 + private var _hasValue: [Bool] + private var _isDone: [Bool] + + init(arity: Int, observer: O, cancel: Cancelable) { + self._arity = arity + self._hasValue = [Bool](repeating: false, count: arity) + self._isDone = [Bool](repeating: false, count: arity) + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func next(_ index: Int) { + if !self._hasValue[index] { + self._hasValue[index] = true + self._numberOfValues += 1 + } + + if self._numberOfValues == self._arity { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + else { + var allOthersDone = true + + for i in 0 ..< self._arity { + if i != index && !self._isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + self.forwardOn(.completed) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + if self._isDone[index] { + return + } + + self._isDone[index] = true + self._numberOfDone += 1 + + if self._numberOfDone == self._arity { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class CombineLatestObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = ElementType + typealias ValueSetter = (Element) -> Void + + private let _parent: CombineLatestProtocol + + let _lock: RecursiveLock + private let _index: Int + private let _this: Disposable + private let _setLatestValue: ValueSetter + + init(lock: RecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: @escaping ValueSetter, this: Disposable) { + self._lock = lock + self._parent = parent + self._index = index + self._this = this + self._setLatestValue = setLatestValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self._setLatestValue(value) + self._parent.next(self._index) + case .error(let error): + self._this.dispose() + self._parent.fail(error) + case .completed: + self._this.dispose() + self._parent.done(self._index) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Concat.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Concat.swift new file mode 100644 index 0000000..27daf8d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Concat.swift @@ -0,0 +1,131 @@ +// +// Concat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Concatenates the second observable sequence to `self` upon successful termination of `self`. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - parameter second: Second observable sequence. + - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. + */ + public func concat(_ second: O) -> Observable where O.E == E { + return Observable.concat([self.asObservable(), second.asObservable()]) + } +} + +extension ObservableType { + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sequence: S) -> Observable + where S.Iterator.Element == Observable { + return Concat(sources: sequence, count: nil) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ collection: S) -> Observable + where S.Iterator.Element == Observable { + return Concat(sources: collection, count: Int64(collection.count)) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sources: Observable ...) -> Observable { + return Concat(sources: sources, count: Int64(sources.count)) + } +} + +final private class ConcatSink + : TailRecursiveSink + , ObserverType where S.Iterator.Element: ObservableConvertibleType, S.Iterator.Element.E == O.E { + typealias Element = O.E + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event){ + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.schedule(.moveNext) + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + return source.subscribe(self) + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let source = observable as? Concat { + return (source._sources.makeIterator(), source._count) + } + else { + return nil + } + } +} + +final private class Concat: Producer where S.Iterator.Element: ObservableConvertibleType { + typealias Element = S.Iterator.Element.E + + fileprivate let _sources: S + fileprivate let _count: IntMax? + + init(sources: S, count: IntMax?) { + self._sources = sources + self._count = count + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = ConcatSink(observer: observer, cancel: cancel) + let subscription = sink.run((self._sources.makeIterator(), self._count)) + return (sink: sink, subscription: subscription) + } +} + diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Create.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Create.swift new file mode 100644 index 0000000..b57a63a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Create.swift @@ -0,0 +1,78 @@ +// +// Create.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: create + + /** + Creates an observable sequence from a specified subscribe method implementation. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. + - returns: The observable sequence with the specified implementation for the `subscribe` method. + */ + public static func create(_ subscribe: @escaping (AnyObserver) -> Disposable) -> Observable { + return AnonymousObservable(subscribe) + } +} + +final private class AnonymousObservableSink: Sink, ObserverType { + typealias E = O.E + typealias Parent = AnonymousObservable + + // state + private let _isStopped = AtomicInt(0) + + #if DEBUG + fileprivate let _synchronizationTracker = SynchronizationTracker() + #endif + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + #if DEBUG + self._synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self._synchronizationTracker.unregister() } + #endif + switch event { + case .next: + if load(self._isStopped) == 1 { + return + } + self.forwardOn(event) + case .error, .completed: + if fetchOr(self._isStopped, 1) == 0 { + self.forwardOn(event) + self.dispose() + } + } + } + + func run(_ parent: Parent) -> Disposable { + return parent._subscribeHandler(AnyObserver(self)) + } +} + +final private class AnonymousObservable: Producer { + typealias SubscribeHandler = (AnyObserver) -> Disposable + + let _subscribeHandler: SubscribeHandler + + init(_ subscribeHandler: @escaping SubscribeHandler) { + self._subscribeHandler = subscribeHandler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = AnonymousObservableSink(observer: observer, cancel: cancel) + let subscription = sink.run(self) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Debounce.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Debounce.swift new file mode 100644 index 0000000..0b23cc9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Debounce.swift @@ -0,0 +1,118 @@ +// +// Debounce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/11/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Debounce(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DebounceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias ParentType = Debounce + + private let _parent: ParentType + + let _lock = RecursiveLock() + + // state + private var _id = 0 as UInt64 + private var _value: Element? + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: O, cancel: Cancelable) { + self._parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self._parent._source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self._id = self._id &+ 1 + let currentId = self._id + self._value = element + + + let scheduler = self._parent._scheduler + let dueTime = self._parent._dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate)) + case .error: + self._value = nil + self.forwardOn(event) + self.dispose() + case .completed: + if let value = self._value { + self._value = nil + self.forwardOn(.next(value)) + } + self.forwardOn(.completed) + self.dispose() + } + } + + func propagate(_ currentId: UInt64) -> Disposable { + self._lock.lock(); defer { self._lock.unlock() } // { + let originalValue = self._value + + if let value = originalValue, self._id == currentId { + self._value = nil + self.forwardOn(.next(value)) + } + // } + return Disposables.create() + } +} + +final private class Debounce: Producer { + fileprivate let _source: Observable + fileprivate let _dueTime: RxTimeInterval + fileprivate let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self._source = source + self._dueTime = dueTime + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = DebounceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Debug.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Debug.swift new file mode 100644 index 0000000..1a07eb6 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Debug.swift @@ -0,0 +1,103 @@ +// +// Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date +import class Foundation.DateFormatter + +extension ObservableType { + + /** + Prints received events for all observers on standard output. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter identifier: Identifier that is printed together with event description to standard output. + - parameter trimOutput: Should output be trimmed to max 40 characters. + - returns: An observable sequence whose events are printed to standard output. + */ + public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) + -> Observable { + return Debug(source: self, identifier: identifier, trimOutput: trimOutput, file: file, line: line, function: function) + } +} + +fileprivate let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" + +fileprivate func logEvent(_ identifier: String, dateFormat: DateFormatter, content: String) { + print("\(dateFormat.string(from: Date())): \(identifier) -> \(content)") +} + +final private class DebugSink: Sink, ObserverType where O.E == Source.E { + typealias Element = O.E + typealias Parent = Debug + + private let _parent: Parent + private let _timestampFormatter = DateFormatter() + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._timestampFormatter.dateFormat = dateFormat + + logEvent(self._parent._identifier, dateFormat: self._timestampFormatter, content: "subscribed") + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + let maxEventTextLength = 40 + let eventText = "\(event)" + + let eventNormalized = (eventText.count > maxEventTextLength) && self._parent._trimOutput + ? String(eventText.prefix(maxEventTextLength / 2)) + "..." + String(eventText.suffix(maxEventTextLength / 2)) + : eventText + + logEvent(self._parent._identifier, dateFormat: self._timestampFormatter, content: "Event \(eventNormalized)") + + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + override func dispose() { + if !self.disposed { + logEvent(self._parent._identifier, dateFormat: self._timestampFormatter, content: "isDisposed") + } + super.dispose() + } +} + +final private class Debug: Producer { + fileprivate let _identifier: String + fileprivate let _trimOutput: Bool + fileprivate let _source: Source + + init(source: Source, identifier: String?, trimOutput: Bool, file: String, line: UInt, function: String) { + self._trimOutput = trimOutput + if let identifier = identifier { + self._identifier = identifier + } + else { + let trimmedFile: String + if let lastIndex = file.lastIndexOf("/") { + trimmedFile = String(file[file.index(after: lastIndex) ..< file.endIndex]) + } + else { + trimmedFile = file + } + self._identifier = "\(trimmedFile):\(line) (\(function))" + } + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Source.E { + let sink = DebugSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift new file mode 100644 index 0000000..cf0bfed --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift @@ -0,0 +1,66 @@ +// +// DefaultIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Emits elements from the source observable sequence, or a default element if the source observable sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter default: Default element to be sent if the source does not emit any elements + - returns: An observable sequence which emits default element end completes in case the original sequence is empty + */ + public func ifEmpty(default: E) -> Observable { + return DefaultIfEmpty(source: self.asObservable(), default: `default`) + } +} + +final private class DefaultIfEmptySink: Sink, ObserverType { + typealias E = O.E + private let _default: E + private var _isEmpty = true + + init(default: E, observer: O, cancel: Cancelable) { + self._default = `default` + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self._isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self._isEmpty { + self.forwardOn(.next(self._default)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class DefaultIfEmpty: Producer { + private let _source: Observable + private let _default: SourceType + + init(source: Observable, `default`: SourceType) { + self._source = source + self._default = `default` + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceType { + let sink = DefaultIfEmptySink(default: self._default, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Deferred.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Deferred.swift new file mode 100644 index 0000000..b75fbf9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Deferred.swift @@ -0,0 +1,74 @@ +// +// Deferred.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + public static func deferred(_ observableFactory: @escaping () throws -> Observable) + -> Observable { + return Deferred(observableFactory: observableFactory) + } +} + +final private class DeferredSink: Sink, ObserverType where S.E == O.E { + typealias E = O.E + + private let _observableFactory: () throws -> S + + init(observableFactory: @escaping () throws -> S, observer: O, cancel: Cancelable) { + self._observableFactory = observableFactory + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let result = try self._observableFactory() + return result.subscribe(self) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + + switch event { + case .next: + break + case .error: + self.dispose() + case .completed: + self.dispose() + } + } +} + +final private class Deferred: Producer { + typealias Factory = () throws -> S + + private let _observableFactory : Factory + + init(observableFactory: @escaping Factory) { + self._observableFactory = observableFactory + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = DeferredSink(observableFactory: self._observableFactory, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Delay.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Delay.swift new file mode 100644 index 0000000..61969d5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Delay.swift @@ -0,0 +1,179 @@ +// +// Delay.swift +// RxSwift +// +// Created by tarunon on 2016/02/09. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date + +extension ObservableType { + + /** + Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the source by. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: the source Observable shifted in time by the specified delay. + */ + public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Delay(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySink + : Sink + , ObserverType { + typealias E = O.E + typealias Source = Observable + typealias DisposeKey = Bag.KeyType + + private let _lock = RecursiveLock() + + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + private let _sourceSubscription = SingleAssignmentDisposable() + private let _cancelable = SerialDisposable() + + // is scheduled some action + private var _active = false + // is "run loop" on different scheduler running + private var _running = false + private var _errorEvent: Event? + + // state + private var _queue = Queue<(eventTime: RxTime, event: Event)>(capacity: 0) + private var _disposed = false + + init(observer: O, dueTime: RxTimeInterval, scheduler: SchedulerType, cancel: Cancelable) { + self._dueTime = dueTime + self._scheduler = scheduler + super.init(observer: observer, cancel: cancel) + } + + // All of these complications in this method are caused by the fact that + // error should be propagated immediately. Error can be potentially received on different + // scheduler so this process needs to be synchronized somehow. + // + // Another complication is that scheduler is potentially concurrent so internal queue is used. + func drainQueue(state: (), scheduler: AnyRecursiveScheduler<()>) { + + self._lock.lock() // { + let hasFailed = self._errorEvent != nil + if !hasFailed { + self._running = true + } + self._lock.unlock() // } + + if hasFailed { + return + } + + var ranAtLeastOnce = false + + while true { + self._lock.lock() // { + let errorEvent = self._errorEvent + + let eventToForwardImmediately = ranAtLeastOnce ? nil : self._queue.dequeue()?.event + let nextEventToScheduleOriginalTime: Date? = ranAtLeastOnce && !self._queue.isEmpty ? self._queue.peek().eventTime : nil + + if errorEvent == nil { + if eventToForwardImmediately != nil { + } + else if nextEventToScheduleOriginalTime != nil { + self._running = false + } + else { + self._running = false + self._active = false + } + } + self._lock.unlock() // { + + if let errorEvent = errorEvent { + self.forwardOn(errorEvent) + self.dispose() + return + } + else { + if let eventToForwardImmediately = eventToForwardImmediately { + ranAtLeastOnce = true + self.forwardOn(eventToForwardImmediately) + if case .completed = eventToForwardImmediately { + self.dispose() + return + } + } + else if let nextEventToScheduleOriginalTime = nextEventToScheduleOriginalTime { + let elapsedTime = self._scheduler.now.timeIntervalSince(nextEventToScheduleOriginalTime) + let interval = self._dueTime - elapsedTime + let normalizedInterval = interval < 0.0 ? 0.0 : interval + scheduler.schedule((), dueTime: normalizedInterval) + return + } + else { + return + } + } + } + } + + func on(_ event: Event) { + if event.isStopEvent { + self._sourceSubscription.dispose() + } + + switch event { + case .error: + self._lock.lock() // { + let shouldSendImmediately = !self._running + self._queue = Queue(capacity: 0) + self._errorEvent = event + self._lock.unlock() // } + + if shouldSendImmediately { + self.forwardOn(event) + self.dispose() + } + default: + self._lock.lock() // { + let shouldSchedule = !self._active + self._active = true + self._queue.enqueue((self._scheduler.now, event)) + self._lock.unlock() // } + + if shouldSchedule { + self._cancelable.disposable = self._scheduler.scheduleRecursive((), dueTime: self._dueTime, action: self.drainQueue) + } + } + } + + func run(source: Observable) -> Disposable { + self._sourceSubscription.setDisposable(source.subscribe(self)) + return Disposables.create(_sourceSubscription, _cancelable) + } +} + +final private class Delay: Producer { + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self._source = source + self._dueTime = dueTime + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = DelaySink(observer: observer, dueTime: self._dueTime, scheduler: self._scheduler, cancel: cancel) + let subscription = sink.run(source: self._source) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift new file mode 100644 index 0000000..16218a7 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift @@ -0,0 +1,58 @@ +// +// DelaySubscription.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the subscription. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: Time-shifted sequence. + */ + public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySubscriptionSink + : Sink, ObserverType { + typealias E = O.E + + func on(_ event: Event) { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + +} + +final private class DelaySubscription: Producer { + private let _source: Observable + private let _dueTime: RxTimeInterval + private let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self._source = source + self._dueTime = dueTime + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = DelaySubscriptionSink(observer: observer, cancel: cancel) + let subscription = self._scheduler.scheduleRelative((), dueTime: self._dueTime) { _ in + return self._source.subscribe(sink) + } + + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift new file mode 100644 index 0000000..e315d17 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift @@ -0,0 +1,51 @@ +// +// Dematerialize.swift +// RxSwift +// +// Created by Jamie Pinkham on 3/13/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where E: EventConvertible { + /** + Convert any previously materialized Observable into it's original form. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: The dematerialized observable sequence. + */ + public func dematerialize() -> Observable { + return Dematerialize(source: self.asObservable()) + } + +} + +fileprivate final class DematerializeSink: Sink, ObserverType where O.E == Element.ElementType { + fileprivate func on(_ event: Event) { + switch event { + case .next(let element): + self.forwardOn(element.event) + if element.event.isStopEvent { + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Dematerialize: Producer { + private let _source: Observable + + init(source: Observable) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element.ElementType { + let sink = DematerializeSink(observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift new file mode 100644 index 0000000..db0b0ab --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift @@ -0,0 +1,125 @@ +// +// DistinctUntilChanged.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where E: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + public func distinctUntilChanged() + -> Observable { + return self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + } +} + +extension ObservableType { + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (E) throws -> K) + -> Observable { + return self.distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + public func distinctUntilChanged(_ comparer: @escaping (E, E) throws -> Bool) + -> Observable { + return self.distinctUntilChanged({ $0 }, comparer: comparer) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (E) throws -> K, comparer: @escaping (K, K) throws -> Bool) + -> Observable { + return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer) + } +} + +final private class DistinctUntilChangedSink: Sink, ObserverType { + typealias E = O.E + + private let _parent: DistinctUntilChanged + private var _currentKey: Key? + + init(parent: DistinctUntilChanged, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let key = try self._parent._selector(value) + var areEqual = false + if let currentKey = self._currentKey { + areEqual = try self._parent._comparer(currentKey, key) + } + + if areEqual { + return + } + + self._currentKey = key + + self.forwardOn(event) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class DistinctUntilChanged: Producer { + typealias KeySelector = (Element) throws -> Key + typealias EqualityComparer = (Key, Key) throws -> Bool + + fileprivate let _source: Observable + fileprivate let _selector: KeySelector + fileprivate let _comparer: EqualityComparer + + init(source: Observable, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) { + self._source = source + self._selector = selector + self._comparer = comparer + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Do.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Do.swift new file mode 100644 index 0000000..d057131 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Do.swift @@ -0,0 +1,93 @@ +// +// Do.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. + - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. + - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. + - returns: The source sequence with the side-effecting behavior applied. + */ + public func `do`(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) + -> Observable { + return Do(source: self.asObservable(), eventHandler: { e in + switch e { + case .next(let element): + try onNext?(element) + case .error(let e): + try onError?(e) + case .completed: + try onCompleted?() + } + }, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) + } +} + +final private class DoSink: Sink, ObserverType { + typealias Element = O.E + typealias EventHandler = (Event) throws -> Void + + private let _eventHandler: EventHandler + + init(eventHandler: @escaping EventHandler, observer: O, cancel: Cancelable) { + self._eventHandler = eventHandler + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + do { + try self._eventHandler(event) + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Do: Producer { + typealias EventHandler = (Event) throws -> Void + + fileprivate let _source: Observable + fileprivate let _eventHandler: EventHandler + fileprivate let _onSubscribe: (() -> Void)? + fileprivate let _onSubscribed: (() -> Void)? + fileprivate let _onDispose: (() -> Void)? + + init(source: Observable, eventHandler: @escaping EventHandler, onSubscribe: (() -> Void)?, onSubscribed: (() -> Void)?, onDispose: (() -> Void)?) { + self._source = source + self._eventHandler = eventHandler + self._onSubscribe = onSubscribe + self._onSubscribed = onSubscribed + self._onDispose = onDispose + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + self._onSubscribe?() + let sink = DoSink(eventHandler: self._eventHandler, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + self._onSubscribed?() + let onDispose = self._onDispose + let allSubscriptions = Disposables.create { + subscription.dispose() + onDispose?() + } + return (sink: sink, subscription: allSubscriptions) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ElementAt.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ElementAt.swift new file mode 100644 index 0000000..2279400 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ElementAt.swift @@ -0,0 +1,92 @@ +// +// ElementAt.swift +// RxSwift +// +// Created by Junior B. on 21/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + public func elementAt(_ index: Int) + -> Observable { + return ElementAt(source: self.asObservable(), index: index, throwOnEmpty: true) + } +} + +final private class ElementAtSink: Sink, ObserverType { + typealias SourceType = O.E + typealias Parent = ElementAt + + let _parent: Parent + var _i: Int + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._i = parent._index + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + + if self._i == 0 { + self.forwardOn(event) + self.forwardOn(.completed) + self.dispose() + } + + do { + _ = try decrementChecked(&self._i) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + if self._parent._throwOnEmpty { + self.forwardOn(.error(RxError.argumentOutOfRange)) + } else { + self.forwardOn(.completed) + } + + self.dispose() + } + } +} + +final private class ElementAt: Producer { + let _source: Observable + let _throwOnEmpty: Bool + let _index: Int + + init(source: Observable, index: Int, throwOnEmpty: Bool) { + if index < 0 { + rxFatalError("index can't be negative") + } + + self._source = source + self._index = index + self._throwOnEmpty = throwOnEmpty + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceType { + let sink = ElementAtSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Empty.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Empty.swift new file mode 100644 index 0000000..cf72519 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Empty.swift @@ -0,0 +1,27 @@ +// +// Empty.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence with no elements. + */ + public static func empty() -> Observable { + return EmptyProducer() + } +} + +final private class EmptyProducer: Producer { + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + observer.on(.completed) + return Disposables.create() + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Enumerated.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Enumerated.swift new file mode 100644 index 0000000..fdf326e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Enumerated.swift @@ -0,0 +1,62 @@ +// +// Enumerated.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/6/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Enumerates the elements of an observable sequence. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - returns: An observable sequence that contains tuples of source sequence elements and their indexes. + */ + public func enumerated() + -> Observable<(index: Int, element: E)> { + return Enumerated(source: self.asObservable()) + } +} + +final private class EnumeratedSink: Sink, ObserverType where O.E == (index: Int, element: Element) { + typealias E = Element + var index = 0 + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let nextIndex = try incrementChecked(&self.index) + let next = (index: nextIndex, element: value) + self.forwardOn(.next(next)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Enumerated: Producer<(index: Int, element: Element)> { + private let _source: Observable + + init(source: Observable) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == (index: Int, element: Element) { + let sink = EnumeratedSink(observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Error.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Error.swift new file mode 100644 index 0000000..026a7ce --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Error.swift @@ -0,0 +1,33 @@ +// +// Error.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that terminates with an `error`. + + - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: The observable sequence that terminates with specified error. + */ + public static func error(_ error: Swift.Error) -> Observable { + return ErrorProducer(error: error) + } +} + +final private class ErrorProducer: Producer { + private let _error: Swift.Error + + init(error: Swift.Error) { + self._error = error + } + + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + observer.on(.error(self._error)) + return Disposables.create() + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Filter.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Filter.swift new file mode 100644 index 0000000..d77e890 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Filter.swift @@ -0,0 +1,90 @@ +// +// Filter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Filters the elements of an observable sequence based on a predicate. + + - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + public func filter(_ predicate: @escaping (E) throws -> Bool) + -> Observable { + return Filter(source: self.asObservable(), predicate: predicate) + } +} + +extension ObservableType { + + /** + Skips elements and completes (or errors) when the observable sequence completes (or errors). Equivalent to filter that always returns false. + + - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) + + - returns: An observable sequence that skips all elements of the source sequence. + */ + public func ignoreElements() + -> Completable { + return self.flatMap { _ in + return Observable.empty() + } + .asCompletable() + } +} + +final private class FilterSink: Sink, ObserverType { + typealias Predicate = (Element) throws -> Bool + typealias Element = O.E + + private let _predicate: Predicate + + init(predicate: @escaping Predicate, observer: O, cancel: Cancelable) { + self._predicate = predicate + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let satisfies = try self._predicate(value) + if satisfies { + self.forwardOn(.next(value)) + } + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class Filter: Producer { + typealias Predicate = (Element) throws -> Bool + + private let _source: Observable + private let _predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self._source = source + self._predicate = predicate + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = FilterSink(predicate: self._predicate, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/First.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/First.swift new file mode 100644 index 0000000..29ba8de --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/First.swift @@ -0,0 +1,42 @@ +// +// First.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/31/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +fileprivate final class FirstSink : Sink, ObserverType where O.E == Element? { + typealias E = Element + typealias Parent = First + + func on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(nil)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class First: Producer { + fileprivate let _source: Observable + + init(source: Observable) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element? { + let sink = FirstSink(observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Generate.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Generate.swift new file mode 100644 index 0000000..98635e9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Generate.swift @@ -0,0 +1,87 @@ +// +// Generate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler + to run the loop send out observer messages. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter initialState: Initial state. + - parameter condition: Condition to terminate generation (upon returning `false`). + - parameter iterate: Iteration step function. + - parameter scheduler: Scheduler on which to run the generator loop. + - returns: The generated sequence. + */ + public static func generate(initialState: E, condition: @escaping (E) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (E) throws -> E) -> Observable { + return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) + } +} + +final private class GenerateSink: Sink { + typealias Parent = Generate + + private let _parent: Parent + + private var _state: S + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._state = parent._initialState + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self._parent._scheduler.scheduleRecursive(true) { isFirst, recurse -> Void in + do { + if !isFirst { + self._state = try self._parent._iterate(self._state) + } + + if try self._parent._condition(self._state) { + let result = try self._parent._resultSelector(self._state) + self.forwardOn(.next(result)) + + recurse(false) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + } +} + +final private class Generate: Producer { + fileprivate let _initialState: S + fileprivate let _condition: (S) throws -> Bool + fileprivate let _iterate: (S) throws -> S + fileprivate let _resultSelector: (S) throws -> E + fileprivate let _scheduler: ImmediateSchedulerType + + init(initialState: S, condition: @escaping (S) throws -> Bool, iterate: @escaping (S) throws -> S, resultSelector: @escaping (S) throws -> E, scheduler: ImmediateSchedulerType) { + self._initialState = initialState + self._condition = condition + self._iterate = iterate + self._resultSelector = resultSelector + self._scheduler = scheduler + super.init() + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = GenerateSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/GroupBy.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/GroupBy.swift new file mode 100644 index 0000000..adce876 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/GroupBy.swift @@ -0,0 +1,134 @@ +// +// GroupBy.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /* + Groups the elements of an observable sequence according to a specified key selector function. + + - seealso: [groupBy operator on reactivex.io](http://reactivex.io/documentation/operators/groupby.html) + + - parameter keySelector: A function to extract the key for each element. + - returns: A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + public func groupBy(keySelector: @escaping (E) throws -> K) + -> Observable> { + return GroupBy(source: self.asObservable(), selector: keySelector) + } +} + +final private class GroupedObservableImpl: Observable { + private var _subject: PublishSubject + private var _refCount: RefCountDisposable + + init(subject: PublishSubject, refCount: RefCountDisposable) { + self._subject = subject + self._refCount = refCount + } + + override public func subscribe(_ observer: O) -> Disposable where O.E == E { + let release = self._refCount.retain() + let subscription = self._subject.subscribe(observer) + return Disposables.create(release, subscription) + } +} + + +final private class GroupBySink + : Sink + , ObserverType where O.E == GroupedObservable { + typealias E = Element + typealias ResultType = O.E + typealias Parent = GroupBy + + private let _parent: Parent + private let _subscription = SingleAssignmentDisposable() + private var _refCountDisposable: RefCountDisposable! + private var _groupedSubjectTable: [Key: PublishSubject] + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._groupedSubjectTable = [Key: PublishSubject]() + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self._refCountDisposable = RefCountDisposable(disposable: self._subscription) + + self._subscription.setDisposable(self._parent._source.subscribe(self)) + + return self._refCountDisposable + } + + private func onGroupEvent(key: Key, value: Element) { + if let writer = self._groupedSubjectTable[key] { + writer.on(.next(value)) + } else { + let writer = PublishSubject() + self._groupedSubjectTable[key] = writer + + let group = GroupedObservable( + key: key, + source: GroupedObservableImpl(subject: writer, refCount: _refCountDisposable) + ) + + self.forwardOn(.next(group)) + writer.on(.next(value)) + } + } + + final func on(_ event: Event) { + switch event { + case let .next(value): + do { + let groupKey = try self._parent._selector(value) + self.onGroupEvent(key: groupKey, value: value) + } + catch let e { + self.error(e) + return + } + case let .error(e): + self.error(e) + case .completed: + self.forwardOnGroups(event: .completed) + self.forwardOn(.completed) + self._subscription.dispose() + self.dispose() + } + } + + final func error(_ error: Swift.Error) { + self.forwardOnGroups(event: .error(error)) + self.forwardOn(.error(error)) + self._subscription.dispose() + self.dispose() + } + + final func forwardOnGroups(event: Event) { + for writer in self._groupedSubjectTable.values { + writer.on(event) + } + } +} + +final private class GroupBy: Producer> { + typealias KeySelector = (Element) throws -> Key + + fileprivate let _source: Observable + fileprivate let _selector: KeySelector + + init(source: Observable, selector: @escaping KeySelector) { + self._source = source + self._selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == GroupedObservable { + let sink = GroupBySink(parent: self, observer: observer, cancel: cancel) + return (sink: sink, subscription: sink.run()) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Just.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Just.swift new file mode 100644 index 0000000..f4fa0d2 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Just.swift @@ -0,0 +1,87 @@ +// +// Just.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: E) -> Observable { + return Just(element: element) + } + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the single element on. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: E, scheduler: ImmediateSchedulerType) -> Observable { + return JustScheduled(element: element, scheduler: scheduler) + } +} + +final private class JustScheduledSink: Sink { + typealias Parent = JustScheduled + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let scheduler = self._parent._scheduler + return scheduler.schedule(self._parent._element) { element in + self.forwardOn(.next(element)) + return scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class JustScheduled: Producer { + fileprivate let _scheduler: ImmediateSchedulerType + fileprivate let _element: Element + + init(element: Element, scheduler: ImmediateSchedulerType) { + self._scheduler = scheduler + self._element = element + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = JustScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class Just: Producer { + private let _element: Element + + init(element: Element) { + self._element = element + } + + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + observer.on(.next(self._element)) + observer.on(.completed) + return Disposables.create() + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Map.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Map.swift new file mode 100644 index 0000000..b5ae370 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Map.swift @@ -0,0 +1,108 @@ +// +// Map.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a new form. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter transform: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + + */ + public func map(_ transform: @escaping (E) throws -> R) + -> Observable { + return self.asObservable().composeMap(transform) + } +} + +final private class MapSink: Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType + + typealias ResultType = O.E + typealias Element = SourceType + + private let _transform: Transform + + init(transform: @escaping Transform, observer: O, cancel: Cancelable) { + self._transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + let mappedElement = try self._transform(element) + self.forwardOn(.next(mappedElement)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +#if TRACE_RESOURCES + fileprivate let _numberOfMapOperators = AtomicInt(0) + extension Resources { + public static var numberOfMapOperators: Int32 { + return load(_numberOfMapOperators) + } + } +#endif + +internal func _map(source: Observable, transform: @escaping (Element) throws -> R) -> Observable { + return Map(source: source, transform: transform) +} + +final private class Map: Producer { + typealias Transform = (SourceType) throws -> ResultType + + private let _source: Observable + + private let _transform: Transform + + init(source: Observable, transform: @escaping Transform) { + self._source = source + self._transform = transform + +#if TRACE_RESOURCES + _ = increment(_numberOfMapOperators) +#endif + } + + override func composeMap(_ selector: @escaping (ResultType) throws -> R) -> Observable { + let originalSelector = self._transform + return Map(source: self._source, transform: { (s: SourceType) throws -> R in + let r: ResultType = try originalSelector(s) + return try selector(r) + }) + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType { + let sink = MapSink(transform: self._transform, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + + #if TRACE_RESOURCES + deinit { + _ = decrement(_numberOfMapOperators) + } + #endif +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Materialize.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Materialize.swift new file mode 100644 index 0000000..1a5e2f5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Materialize.swift @@ -0,0 +1,44 @@ +// +// Materialize.swift +// RxSwift +// +// Created by sergdort on 08/03/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Convert any Observable into an Observable of its events. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: An observable sequence that wraps events in an Event. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable. + */ + public func materialize() -> Observable> { + return Materialize(source: self.asObservable()) + } +} + +fileprivate final class MaterializeSink: Sink, ObserverType where O.E == Event { + + func on(_ event: Event) { + self.forwardOn(.next(event)) + if event.isStopEvent { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Materialize: Producer> { + private let _source: Observable + + init(source: Observable) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = MaterializeSink(observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Merge.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Merge.swift new file mode 100644 index 0000000..0bc0a38 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Merge.swift @@ -0,0 +1,598 @@ +// +// Merge.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMap(_ selector: @escaping (E) throws -> O) + -> Observable { + return FlatMap(source: self.asObservable(), selector: selector) + } + +} + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + public func flatMapFirst(_ selector: @escaping (E) throws -> O) + -> Observable { + return FlatMapFirst(source: self.asObservable(), selector: selector) + } +} + +extension ObservableType where E : ObservableConvertibleType { + + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public func merge() -> Observable { + return Merge(source: self.asObservable()) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + public func merge(maxConcurrent: Int) + -> Observable { + return MergeLimited(source: self.asObservable(), maxConcurrent: maxConcurrent) + } +} + +extension ObservableType where E : ObservableConvertibleType { + + /** + Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + public func concat() -> Observable { + return self.merge(maxConcurrent: 1) + } +} + +extension ObservableType { + /** + Merges elements from all observable sequences from collection into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: C) -> Observable where C.Iterator.Element == Observable { + return MergeArray(sources: Array(sources)) + } + + /** + Merges elements from all observable sequences from array into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Array of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: [Observable]) -> Observable { + return MergeArray(sources: sources) + } + + /** + Merges elements from all observable sequences into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Observable...) -> Observable { + return MergeArray(sources: sources) + } +} + +// MARK: concatMap + +extension ObservableType { + /** + Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + + public func concatMap(_ selector: @escaping (E) throws -> O) + -> Observable { + return ConcatMap(source: self.asObservable(), selector: selector) + } +} + +fileprivate final class MergeLimitedSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where SourceSequence.E == Observer.E { + typealias E = Observer.E + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Parent = MergeLimitedSink + + private let _parent: Parent + private let _disposeKey: DisposeKey + + var _lock: RecursiveLock { + return self._parent._lock + } + + init(parent: Parent, disposeKey: DisposeKey) { + self._parent = parent + self._disposeKey = disposeKey + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + self._parent.forwardOn(event) + case .error: + self._parent.forwardOn(event) + self._parent.dispose() + case .completed: + self._parent._group.remove(for: self._disposeKey) + if let next = self._parent._queue.dequeue() { + self._parent.subscribe(next, group: self._parent._group) + } + else { + self._parent._activeCount -= 1 + + if self._parent._stopped && self._parent._activeCount == 0 { + self._parent.forwardOn(.completed) + self._parent.dispose() + } + } + } + } +} + +fileprivate final class ConcatMapSink: MergeLimitedSink where Observer.E == SourceSequence.E { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let _selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self._selector = selector + super.init(maxConcurrent: 1, observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + return try self._selector(element) + } +} + +fileprivate final class MergeLimitedBasicSink: MergeLimitedSink where Observer.E == SourceSequence.E { + + override func performMap(_ element: SourceSequence) throws -> SourceSequence { + return element + } +} + +private class MergeLimitedSink + : Sink + , ObserverType where Observer.E == SourceSequence.E { + typealias QueueType = Queue + + let _maxConcurrent: Int + + let _lock = RecursiveLock() + + // state + var _stopped = false + var _activeCount = 0 + var _queue = QueueType(capacity: 2) + + let _sourceSubscription = SingleAssignmentDisposable() + let _group = CompositeDisposable() + + init(maxConcurrent: Int, observer: Observer, cancel: Cancelable) { + self._maxConcurrent = maxConcurrent + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + _ = self._group.insert(self._sourceSubscription) + + let disposable = source.subscribe(self) + self._sourceSubscription.setDisposable(disposable) + return self._group + } + + func subscribe(_ innerSource: SourceSequence, group: CompositeDisposable) { + let subscription = SingleAssignmentDisposable() + + let key = group.insert(subscription) + + if let key = key { + let observer = MergeLimitedSinkIter(parent: self, disposeKey: key) + + let disposable = innerSource.asObservable().subscribe(observer) + subscription.setDisposable(disposable) + } + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self._lock.lock(); defer { self._lock.unlock() } // { + let subscribe: Bool + if self._activeCount < self._maxConcurrent { + self._activeCount += 1 + subscribe = true + } + else { + do { + let value = try self.performMap(element) + self._queue.enqueue(value) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + subscribe = false + } + + if subscribe { + do { + return try self.performMap(element) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + } + + return nil + // } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let sequence = self.nextElementArrived(element: element) { + self.subscribe(sequence, group: self._group) + } + case .error(let error): + self._lock.lock(); defer { self._lock.unlock() } + + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self._lock.lock(); defer { self._lock.unlock() } + + if self._activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + else { + self._sourceSubscription.dispose() + } + + self._stopped = true + } + } +} + +final private class MergeLimited: Producer { + private let _source: Observable + private let _maxConcurrent: Int + + init(source: Observable, maxConcurrent: Int) { + self._source = source + self._maxConcurrent = maxConcurrent + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceSequence.E { + let sink = MergeLimitedBasicSink(maxConcurrent: self._maxConcurrent, observer: observer, cancel: cancel) + let subscription = sink.run(self._source) + return (sink: sink, subscription: subscription) + } +} + +// MARK: Merge + +fileprivate final class MergeBasicSink : MergeSink where O.E == S.E { + override func performMap(_ element: S) throws -> S { + return element + } +} + +// MARK: flatMap + +fileprivate final class FlatMapSink : MergeSink where Observer.E == SourceSequence.E { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let _selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self._selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + return try self._selector(element) + } +} + +// MARK: FlatMapFirst + +fileprivate final class FlatMapFirstSink : MergeSink where Observer.E == SourceSequence.E { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let _selector: Selector + + override var subscribeNext: Bool { + return self._activeCount == 0 + } + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self._selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + return try self._selector(element) + } +} + +fileprivate final class MergeSinkIter : ObserverType where Observer.E == SourceSequence.E { + typealias Parent = MergeSink + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias E = Observer.E + + private let _parent: Parent + private let _disposeKey: DisposeKey + + init(parent: Parent, disposeKey: DisposeKey) { + self._parent = parent + self._disposeKey = disposeKey + } + + func on(_ event: Event) { + self._parent._lock.lock(); defer { self._parent._lock.unlock() } // lock { + switch event { + case .next(let value): + self._parent.forwardOn(.next(value)) + case .error(let error): + self._parent.forwardOn(.error(error)) + self._parent.dispose() + case .completed: + self._parent._group.remove(for: self._disposeKey) + self._parent._activeCount -= 1 + self._parent.checkCompleted() + } + // } + } +} + + +private class MergeSink + : Sink + , ObserverType where Observer.E == SourceSequence.E { + typealias ResultType = Observer.E + typealias Element = SourceElement + + let _lock = RecursiveLock() + + var subscribeNext: Bool { + return true + } + + // state + let _group = CompositeDisposable() + let _sourceSubscription = SingleAssignmentDisposable() + + var _activeCount = 0 + var _stopped = false + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self._lock.lock(); defer { self._lock.unlock() } // { + if !self.subscribeNext { + return nil + } + + do { + let value = try self.performMap(element) + self._activeCount += 1 + return value + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return nil + } + // } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let value = self.nextElementArrived(element: element) { + self.subscribeInner(value.asObservable()) + } + case .error(let error): + self._lock.lock(); defer { self._lock.unlock() } + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self._lock.lock(); defer { self._lock.unlock() } + self._stopped = true + self._sourceSubscription.dispose() + self.checkCompleted() + } + } + + func subscribeInner(_ source: Observable) { + let iterDisposable = SingleAssignmentDisposable() + if let disposeKey = self._group.insert(iterDisposable) { + let iter = MergeSinkIter(parent: self, disposeKey: disposeKey) + let subscription = source.subscribe(iter) + iterDisposable.setDisposable(subscription) + } + } + + func run(_ sources: [Observable]) -> Disposable { + self._activeCount += sources.count + + for source in sources { + self.subscribeInner(source) + } + + self._stopped = true + + self.checkCompleted() + + return self._group + } + + @inline(__always) + func checkCompleted() { + if self._stopped && self._activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + + func run(_ source: Observable) -> Disposable { + _ = self._group.insert(self._sourceSubscription) + + let subscription = source.subscribe(self) + self._sourceSubscription.setDisposable(subscription) + + return self._group + } +} + +// MARK: Producers + +final private class FlatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self._source = source + self._selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceSequence.E { + let sink = FlatMapSink(selector: self._selector, observer: observer, cancel: cancel) + let subscription = sink.run(self._source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapFirst: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let _source: Observable + + private let _selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self._source = source + self._selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceSequence.E { + let sink = FlatMapFirstSink(selector: self._selector, observer: observer, cancel: cancel) + let subscription = sink.run(self._source) + return (sink: sink, subscription: subscription) + } +} + +final class ConcatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let _source: Observable + private let _selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self._source = source + self._selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceSequence.E { + let sink = ConcatMapSink(selector: self._selector, observer: observer, cancel: cancel) + let subscription = sink.run(self._source) + return (sink: sink, subscription: subscription) + } +} + +final class Merge : Producer { + private let _source: Observable + + init(source: Observable) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceSequence.E { + let sink = MergeBasicSink(observer: observer, cancel: cancel) + let subscription = sink.run(self._source) + return (sink: sink, subscription: subscription) + } +} + +final private class MergeArray: Producer { + private let _sources: [Observable] + + init(sources: [Observable]) { + self._sources = sources + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = MergeBasicSink, O>(observer: observer, cancel: cancel) + let subscription = sink.run(self._sources) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Multicast.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Multicast.swift new file mode 100644 index 0000000..7e47389 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Multicast.swift @@ -0,0 +1,408 @@ +// +// Multicast.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** + Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence. + */ +public class ConnectableObservable + : Observable + , ConnectableObservableType { + + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + public func connect() -> Disposable { + rxAbstractMethod() + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. + + Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + - parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + public func multicast(_ subjectSelector: @escaping () throws -> S, selector: @escaping (Observable) throws -> Observable) + -> Observable where S.SubjectObserverType.E == E { + return Multicast( + source: self.asObservable(), + subjectSelector: subjectSelector, + selector: selector + ) + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of `multicast` using a `PublishSubject`. + + - seealso: [publish operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func publish() -> ConnectableObservable { + return self.multicast { PublishSubject() } + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replay(_ bufferSize: Int) + -> ConnectableObservable { + return self.multicast { ReplaySubject.create(bufferSize: bufferSize) } + } + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying all elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replayAll() + -> ConnectableObservable { + return self.multicast { ReplaySubject.createUnbounded() } + } +} + +extension ConnectableObservableType { + + /** + Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + + - seealso: [refCount operator on reactivex.io](http://reactivex.io/documentation/operators/refcount.html) + + - returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + */ + public func refCount() -> Observable { + return RefCount(source: self) + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through the specified subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subject: Subject to push source elements into. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(_ subject: S) + -> ConnectableObservable where S.SubjectObserverType.E == E { + return ConnectableObservableAdapter(source: self.asObservable(), makeSubject: { subject }) + } + + /** + Multicasts the source sequence notifications through an instantiated subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + Subject is cleared on connection disposal or in case source sequence produces terminal event. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter makeSubject: Factory function used to instantiate a subject for each connection. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(makeSubject: @escaping () -> S) + -> ConnectableObservable where S.SubjectObserverType.E == E { + return ConnectableObservableAdapter(source: self.asObservable(), makeSubject: makeSubject) + } +} + +final private class Connection: ObserverType, Disposable { + typealias E = S.SubjectObserverType.E + + private var _lock: RecursiveLock + // state + private var _parent: ConnectableObservableAdapter? + private var _subscription : Disposable? + private var _subjectObserver: S.SubjectObserverType + + private let _disposed = AtomicInt(0) + + init(parent: ConnectableObservableAdapter, subjectObserver: S.SubjectObserverType, lock: RecursiveLock, subscription: Disposable) { + self._parent = parent + self._subscription = subscription + self._lock = lock + self._subjectObserver = subjectObserver + } + + func on(_ event: Event) { + if isFlagSet(self._disposed, 1) { + return + } + if event.isStopEvent { + self.dispose() + } + self._subjectObserver.on(event) + } + + func dispose() { + _lock.lock(); defer { _lock.unlock() } // { + fetchOr(self._disposed, 1) + guard let parent = _parent else { + return + } + + if parent._connection === self { + parent._connection = nil + parent._subject = nil + } + self._parent = nil + + self._subscription?.dispose() + self._subscription = nil + // } + } +} + +final private class ConnectableObservableAdapter + : ConnectableObservable { + typealias ConnectionType = Connection + + fileprivate let _source: Observable + fileprivate let _makeSubject: () -> S + + fileprivate let _lock = RecursiveLock() + fileprivate var _subject: S? + + // state + fileprivate var _connection: ConnectionType? + + init(source: Observable, makeSubject: @escaping () -> S) { + self._source = source + self._makeSubject = makeSubject + self._subject = nil + self._connection = nil + } + + override func connect() -> Disposable { + return self._lock.calculateLocked { + if let connection = self._connection { + return connection + } + + let singleAssignmentDisposable = SingleAssignmentDisposable() + let connection = Connection(parent: self, subjectObserver: self.lazySubject.asObserver(), lock: self._lock, subscription: singleAssignmentDisposable) + self._connection = connection + let subscription = self._source.subscribe(connection) + singleAssignmentDisposable.setDisposable(subscription) + return connection + } + } + + fileprivate var lazySubject: S { + if let subject = self._subject { + return subject + } + + let subject = self._makeSubject() + self._subject = subject + return subject + } + + override func subscribe(_ observer: O) -> Disposable where O.E == S.E { + return self.lazySubject.subscribe(observer) + } +} + +final private class RefCountSink + : Sink + , ObserverType where CO.E == O.E { + typealias Element = O.E + typealias Parent = RefCount + + private let _parent: Parent + + private var _connectionIdSnapshot: Int64 = -1 + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self._parent._source.subscribe(self) + self._parent._lock.lock(); defer { self._parent._lock.unlock() } // { + + self._connectionIdSnapshot = self._parent._connectionId + + if self.disposed { + return Disposables.create() + } + + if self._parent._count == 0 { + self._parent._count = 1 + self._parent._connectableSubscription = self._parent._source.connect() + } + else { + self._parent._count += 1 + } + // } + + return Disposables.create { + subscription.dispose() + self._parent._lock.lock(); defer { self._parent._lock.unlock() } // { + if self._parent._connectionId != self._connectionIdSnapshot { + return + } + if self._parent._count == 1 { + self._parent._count = 0 + guard let connectableSubscription = self._parent._connectableSubscription else { + return + } + + connectableSubscription.dispose() + self._parent._connectableSubscription = nil + } + else if self._parent._count > 1 { + self._parent._count -= 1 + } + else { + rxFatalError("Something went wrong with RefCount disposing mechanism") + } + // } + } + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error, .completed: + self._parent._lock.lock() // { + if self._parent._connectionId == self._connectionIdSnapshot { + let connection = self._parent._connectableSubscription + defer { connection?.dispose() } + self._parent._count = 0 + self._parent._connectionId = self._parent._connectionId &+ 1 + self._parent._connectableSubscription = nil + } + // } + self._parent._lock.unlock() + self.forwardOn(event) + self.dispose() + } + } +} + +final private class RefCount: Producer { + fileprivate let _lock = RecursiveLock() + + // state + fileprivate var _count = 0 + fileprivate var _connectionId: Int64 = 0 + fileprivate var _connectableSubscription = nil as Disposable? + + fileprivate let _source: CO + + init(source: CO) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == CO.E { + let sink = RefCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class MulticastSink: Sink, ObserverType { + typealias Element = O.E + typealias ResultType = Element + typealias MutlicastType = Multicast + + private let _parent: MutlicastType + + init(parent: MutlicastType, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let subject = try self._parent._subjectSelector() + let connectable = ConnectableObservableAdapter(source: self._parent._source, makeSubject: { subject }) + + let observable = try self._parent._selector(connectable) + + let subscription = observable.subscribe(self) + let connection = connectable.connect() + + return Disposables.create(subscription, connection) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + switch event { + case .next: break + case .error, .completed: + self.dispose() + } + } +} + +final private class Multicast: Producer { + typealias SubjectSelectorType = () throws -> S + typealias SelectorType = (Observable) throws -> Observable + + fileprivate let _source: Observable + fileprivate let _subjectSelector: SubjectSelectorType + fileprivate let _selector: SelectorType + + init(source: Observable, subjectSelector: @escaping SubjectSelectorType, selector: @escaping SelectorType) { + self._source = source + self._subjectSelector = subjectSelector + self._selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = MulticastSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Never.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Never.swift new file mode 100644 index 0000000..51aa3f0 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Never.swift @@ -0,0 +1,27 @@ +// +// Never.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence whose observers will never get called. + */ + public static func never() -> Observable { + return NeverProducer() + } +} + +final private class NeverProducer: Producer { + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + return Disposables.create() + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift new file mode 100644 index 0000000..cf7e0b6 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift @@ -0,0 +1,231 @@ +// +// ObserveOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + public func observeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + if let scheduler = scheduler as? SerialDispatchQueueScheduler { + return ObserveOnSerialDispatchQueue(source: self.asObservable(), scheduler: scheduler) + } + else { + return ObserveOn(source: self.asObservable(), scheduler: scheduler) + } + } +} + +final private class ObserveOn: Producer { + let scheduler: ImmediateSchedulerType + let source: Observable + + init(source: Observable, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = ObserveOnSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +enum ObserveOnState : Int32 { + // pump is not running + case stopped = 0 + // pump is running + case running = 1 +} + +final private class ObserveOnSink: ObserverBase { + typealias E = O.E + + let _scheduler: ImmediateSchedulerType + + var _lock = SpinLock() + let _observer: O + + // state + var _state = ObserveOnState.stopped + var _queue = Queue>(capacity: 10) + + let _scheduleDisposable = SerialDisposable() + let _cancel: Cancelable + + init(scheduler: ImmediateSchedulerType, observer: O, cancel: Cancelable) { + self._scheduler = scheduler + self._observer = observer + self._cancel = cancel + } + + override func onCore(_ event: Event) { + let shouldStart = self._lock.calculateLocked { () -> Bool in + self._queue.enqueue(event) + + switch self._state { + case .stopped: + self._state = .running + return true + case .running: + return false + } + } + + if shouldStart { + self._scheduleDisposable.disposable = self._scheduler.scheduleRecursive((), action: self.run) + } + } + + func run(_ state: (), _ recurse: (()) -> Void) { + let (nextEvent, observer) = self._lock.calculateLocked { () -> (Event?, O) in + if !self._queue.isEmpty { + return (self._queue.dequeue(), self._observer) + } + else { + self._state = .stopped + return (nil, self._observer) + } + } + + if let nextEvent = nextEvent, !self._cancel.isDisposed { + observer.on(nextEvent) + if nextEvent.isStopEvent { + self.dispose() + } + } + else { + return + } + + let shouldContinue = self._shouldContinue_synchronized() + + if shouldContinue { + recurse(()) + } + } + + func _shouldContinue_synchronized() -> Bool { + self._lock.lock(); defer { self._lock.unlock() } // { + if !self._queue.isEmpty { + return true + } + else { + self._state = .stopped + return false + } + // } + } + + override func dispose() { + super.dispose() + + self._cancel.dispose() + self._scheduleDisposable.dispose() + } +} + +#if TRACE_RESOURCES + fileprivate let _numberOfSerialDispatchQueueObservables = AtomicInt(0) + extension Resources { + /** + Counts number of `SerialDispatchQueueObservables`. + + Purposed for unit tests. + */ + public static var numberOfSerialDispatchQueueObservables: Int32 { + return load(_numberOfSerialDispatchQueueObservables) + } + } +#endif + +final private class ObserveOnSerialDispatchQueueSink: ObserverBase { + let scheduler: SerialDispatchQueueScheduler + let observer: O + + let cancel: Cancelable + + var cachedScheduleLambda: (((sink: ObserveOnSerialDispatchQueueSink, event: Event)) -> Disposable)! + + init(scheduler: SerialDispatchQueueScheduler, observer: O, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + super.init() + + self.cachedScheduleLambda = { pair in + guard !cancel.isDisposed else { return Disposables.create() } + + pair.sink.observer.on(pair.event) + + if pair.event.isStopEvent { + pair.sink.dispose() + } + + return Disposables.create() + } + } + + override func onCore(_ event: Event) { + _ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!) + } + + override func dispose() { + super.dispose() + + self.cancel.dispose() + } +} + +final private class ObserveOnSerialDispatchQueue: Producer { + let scheduler: SerialDispatchQueueScheduler + let source: Observable + + init(source: Observable, scheduler: SerialDispatchQueueScheduler) { + self.scheduler = scheduler + self.source = source + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + _ = increment(_numberOfSerialDispatchQueueObservables) + #endif + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = ObserveOnSerialDispatchQueueSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + _ = decrement(_numberOfSerialDispatchQueueObservables) + } + #endif +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Optional.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Optional.swift new file mode 100644 index 0000000..43fede5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Optional.swift @@ -0,0 +1,95 @@ +// +// Optional.swift +// RxSwift +// +// Created by tarunon on 2016/12/13. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: E?) -> Observable { + return ObservableOptional(optional: optional) + } + + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the optional element on. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: E?, scheduler: ImmediateSchedulerType) -> Observable { + return ObservableOptionalScheduled(optional: optional, scheduler: scheduler) + } +} + +final private class ObservableOptionalScheduledSink: Sink { + typealias E = O.E + typealias Parent = ObservableOptionalScheduled + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self._parent._scheduler.schedule(self._parent._optional) { (optional: E?) -> Disposable in + if let next = optional { + self.forwardOn(.next(next)) + return self._parent._scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } else { + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class ObservableOptionalScheduled: Producer { + fileprivate let _optional: E? + fileprivate let _scheduler: ImmediateSchedulerType + + init(optional: E?, scheduler: ImmediateSchedulerType) { + self._optional = optional + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class ObservableOptional: Producer { + private let _optional: E? + + init(optional: E?) { + self._optional = optional + } + + override func subscribe(_ observer: O) -> Disposable where O.E == E { + if let element = self._optional { + observer.on(.next(element)) + } + observer.on(.completed) + return Disposables.create() + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Producer.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Producer.swift new file mode 100644 index 0000000..f687d11 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Producer.swift @@ -0,0 +1,92 @@ +// +// Producer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Producer : Observable { + override init() { + super.init() + } + + override func subscribe(_ observer: O) -> Disposable where O.E == Element { + if !CurrentThreadScheduler.isScheduleRequired { + // The returned disposable needs to release all references once it was disposed. + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + else { + return CurrentThreadScheduler.instance.schedule(()) { _ in + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + } + } + + func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + rxAbstractMethod() + } +} + +fileprivate final class SinkDisposer: Cancelable { + fileprivate enum DisposeState: Int32 { + case disposed = 1 + case sinkAndSubscriptionSet = 2 + } + + private let _state = AtomicInt(0) + private var _sink: Disposable? + private var _subscription: Disposable? + + var isDisposed: Bool { + return isFlagSet(self._state, DisposeState.disposed.rawValue) + } + + func setSinkAndSubscription(sink: Disposable, subscription: Disposable) { + self._sink = sink + self._subscription = subscription + + let previousState = fetchOr(self._state, DisposeState.sinkAndSubscriptionSet.rawValue) + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + rxFatalError("Sink and subscription were already set") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + sink.dispose() + subscription.dispose() + self._sink = nil + self._subscription = nil + } + } + + func dispose() { + let previousState = fetchOr(self._state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + guard let sink = self._sink else { + rxFatalError("Sink not set") + } + guard let subscription = self._subscription else { + rxFatalError("Subscription not set") + } + + sink.dispose() + subscription.dispose() + + self._sink = nil + self._subscription = nil + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Range.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Range.swift new file mode 100644 index 0000000..67a4412 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Range.swift @@ -0,0 +1,73 @@ +// +// Range.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where E : RxAbstractInteger { + /** + Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. + + - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) + + - parameter start: The value of the first integer in the sequence. + - parameter count: The number of sequential integers to generate. + - parameter scheduler: Scheduler to run the generator loop on. + - returns: An observable sequence that contains a range of sequential integral numbers. + */ + public static func range(start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return RangeProducer(start: start, count: count, scheduler: scheduler) + } +} + +final private class RangeProducer: Producer { + fileprivate let _start: E + fileprivate let _count: E + fileprivate let _scheduler: ImmediateSchedulerType + + init(start: E, count: E, scheduler: ImmediateSchedulerType) { + guard count >= 0 else { + rxFatalError("count can't be negative") + } + + guard start &+ (count - 1) >= start || count == 0 else { + rxFatalError("overflow of count") + } + + self._start = start + self._count = count + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = RangeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class RangeSink: Sink where O.E: RxAbstractInteger { + typealias Parent = RangeProducer + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self._parent._scheduler.scheduleRecursive(0 as O.E) { i, recurse in + if i < self._parent._count { + self.forwardOn(.next(self._parent._start + i)) + recurse(i + 1) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Reduce.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Reduce.swift new file mode 100644 index 0000000..5b3efd8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Reduce.swift @@ -0,0 +1,109 @@ +// +// Reduce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + +extension ObservableType { + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - parameter mapResult: A function to transform the final accumulator value into the result value. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, E) throws -> A, mapResult: @escaping (A) throws -> R) + -> Observable { + return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult) + } + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce
(_ seed: A, accumulator: @escaping (A, E) throws -> A) + -> Observable { + return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 }) + } +} + +final private class ReduceSink: Sink, ObserverType { + typealias ResultType = O.E + typealias Parent = Reduce + + private let _parent: Parent + private var _accumulation: AccumulateType + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._accumulation = parent._seed + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + self._accumulation = try self._parent._accumulator(self._accumulation, value) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + do { + let result = try self._parent._mapResult(self._accumulation) + self.forwardOn(.next(result)) + self.forwardOn(.completed) + self.dispose() + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Reduce: Producer { + typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType + typealias ResultSelectorType = (AccumulateType) throws -> ResultType + + fileprivate let _source: Observable + fileprivate let _seed: AccumulateType + fileprivate let _accumulator: AccumulatorType + fileprivate let _mapResult: ResultSelectorType + + init(source: Observable, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) { + self._source = source + self._seed = seed + self._accumulator = accumulator + self._mapResult = mapResult + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType { + let sink = ReduceSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Repeat.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Repeat.swift new file mode 100644 index 0000000..f430c90 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Repeat.swift @@ -0,0 +1,57 @@ +// +// Repeat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. + + - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html) + + - parameter element: Element to repeat. + - parameter scheduler: Scheduler to run the producer loop on. + - returns: An observable sequence that repeats the given element infinitely. + */ + public static func repeatElement(_ element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return RepeatElement(element: element, scheduler: scheduler) + } +} + +final private class RepeatElement: Producer { + fileprivate let _element: Element + fileprivate let _scheduler: ImmediateSchedulerType + + init(element: Element, scheduler: ImmediateSchedulerType) { + self._element = element + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = RepeatElementSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + + return (sink: sink, subscription: subscription) + } +} + +final private class RepeatElementSink: Sink { + typealias Parent = RepeatElement + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self._parent._scheduler.scheduleRecursive(self._parent._element) { e, recurse in + self.forwardOn(.next(e)) + recurse(e) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift new file mode 100644 index 0000000..ce82df9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift @@ -0,0 +1,182 @@ +// +// RetryWhen.swift +// RxSwift +// +// Created by Junior B. on 06/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } +} + +final private class RetryTriggerSink + : ObserverType where S.Iterator.Element: ObservableType, S.Iterator.Element.E == O.E { + typealias E = TriggerObservable.E + + typealias Parent = RetryWhenSequenceSinkIter + + fileprivate let _parent: Parent + + init(parent: Parent) { + self._parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self._parent._parent._lastError = nil + self._parent._parent.schedule(.moveNext) + case .error(let e): + self._parent._parent.forwardOn(.error(e)) + self._parent._parent.dispose() + case .completed: + self._parent._parent.forwardOn(.completed) + self._parent._parent.dispose() + } + } +} + +final private class RetryWhenSequenceSinkIter + : ObserverType + , Disposable where S.Iterator.Element: ObservableType, S.Iterator.Element.E == O.E { + typealias E = O.E + typealias Parent = RetryWhenSequenceSink + + fileprivate let _parent: Parent + fileprivate let _errorHandlerSubscription = SingleAssignmentDisposable() + fileprivate let _subscription: Disposable + + init(parent: Parent, subscription: Disposable) { + self._parent = parent + self._subscription = subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self._parent.forwardOn(event) + case .error(let error): + self._parent._lastError = error + + if let failedWith = error as? Error { + // dispose current subscription + self._subscription.dispose() + + let errorHandlerSubscription = self._parent._notifier.subscribe(RetryTriggerSink(parent: self)) + self._errorHandlerSubscription.setDisposable(errorHandlerSubscription) + self._parent._errorSubject.on(.next(failedWith)) + } + else { + self._parent.forwardOn(.error(error)) + self._parent.dispose() + } + case .completed: + self._parent.forwardOn(event) + self._parent.dispose() + } + } + + final func dispose() { + self._subscription.dispose() + self._errorHandlerSubscription.dispose() + } +} + +final private class RetryWhenSequenceSink + : TailRecursiveSink where S.Iterator.Element: ObservableType, S.Iterator.Element.E == O.E { + typealias Element = O.E + typealias Parent = RetryWhenSequence + + let _lock = RecursiveLock() + + fileprivate let _parent: Parent + + fileprivate var _lastError: Swift.Error? + fileprivate let _errorSubject = PublishSubject() + fileprivate let _handler: Observable + fileprivate let _notifier = PublishSubject() + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._handler = parent._notificationHandler(self._errorSubject).asObservable() + super.init(observer: observer, cancel: cancel) + } + + override func done() { + if let lastError = self._lastError { + self.forwardOn(.error(lastError)) + self._lastError = nil + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + // It is important to always return `nil` here because there are sideffects in the `run` method + // that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this + // case. + return nil + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + let subscription = SingleAssignmentDisposable() + let iter = RetryWhenSequenceSinkIter(parent: self, subscription: subscription) + subscription.setDisposable(source.subscribe(iter)) + return iter + } + + override func run(_ sources: SequenceGenerator) -> Disposable { + let triggerSubscription = self._handler.subscribe(self._notifier.asObserver()) + let superSubscription = super.run(sources) + return Disposables.create(superSubscription, triggerSubscription) + } +} + +final private class RetryWhenSequence: Producer where S.Iterator.Element: ObservableType { + typealias Element = S.Iterator.Element.E + + fileprivate let _sources: S + fileprivate let _notificationHandler: (Observable) -> TriggerObservable + + init(sources: S, notificationHandler: @escaping (Observable) -> TriggerObservable) { + self._sources = sources + self._notificationHandler = notificationHandler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = RetryWhenSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run((self._sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sample.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sample.swift new file mode 100644 index 0000000..a930f0d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sample.swift @@ -0,0 +1,133 @@ +// +// Sample.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Samples the source observable sequence using a sampler observable sequence producing sampling ticks. + + Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. + + **In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.** + + - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) + + - parameter sampler: Sampling tick sequence. + - returns: Sampled observable sequence. + */ + public func sample(_ sampler: O) + -> Observable { + return Sample(source: self.asObservable(), sampler: sampler.asObservable()) + } +} + +final private class SamplerSink + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = SampleType + + typealias Parent = SampleSequenceSink + + fileprivate let _parent: Parent + + var _lock: RecursiveLock { + return self._parent._lock + } + + init(parent: Parent) { + self._parent = parent + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next, .completed: + if let element = _parent._element { + self._parent._element = nil + self._parent.forwardOn(.next(element)) + } + + if self._parent._atEnd { + self._parent.forwardOn(.completed) + self._parent.dispose() + } + case .error(let e): + self._parent.forwardOn(.error(e)) + self._parent.dispose() + } + } +} + +final private class SampleSequenceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias Parent = Sample + + fileprivate let _parent: Parent + + let _lock = RecursiveLock() + + // state + fileprivate var _element = nil as Element? + fileprivate var _atEnd = false + + fileprivate let _sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self._sourceSubscription.setDisposable(self._parent._source.subscribe(self)) + let samplerSubscription = self._parent._sampler.subscribe(SamplerSink(parent: self)) + + return Disposables.create(_sourceSubscription, samplerSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self._element = element + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self._atEnd = true + self._sourceSubscription.dispose() + } + } + +} + +final private class Sample: Producer { + fileprivate let _source: Observable + fileprivate let _sampler: Observable + + init(source: Observable, sampler: Observable) { + self._source = source + self._sampler = sampler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Scan.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Scan.swift new file mode 100644 index 0000000..c6df608 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Scan.swift @@ -0,0 +1,101 @@ +// +// Scan.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(into seed: A, accumulator: @escaping (inout A, E) throws -> Void) + -> Observable { + return Scan(source: self.asObservable(), seed: seed, accumulator: accumulator) + } + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(_ seed: A, accumulator: @escaping (A, E) throws -> A) + -> Observable { + return Scan(source: self.asObservable(), seed: seed) { acc, element in + let currentAcc = acc + acc = try accumulator(currentAcc, element) + } + } +} + +final private class ScanSink: Sink, ObserverType { + typealias Accumulate = O.E + typealias Parent = Scan + typealias E = ElementType + + fileprivate let _parent: Parent + fileprivate var _accumulate: Accumulate + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._accumulate = parent._seed + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + try self._parent._accumulator(&self._accumulate, element) + self.forwardOn(.next(self._accumulate)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } + +} + +final private class Scan: Producer { + typealias Accumulator = (inout Accumulate, Element) throws -> Void + + fileprivate let _source: Observable + fileprivate let _seed: Accumulate + fileprivate let _accumulator: Accumulator + + init(source: Observable, seed: Accumulate, accumulator: @escaping Accumulator) { + self._source = source + self._seed = seed + self._accumulator = accumulator + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Accumulate { + let sink = ScanSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sequence.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sequence.swift new file mode 100644 index 0000000..a7f6450 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sequence.swift @@ -0,0 +1,89 @@ +// +// Sequence.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: of + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return ObservableSequence(elements: elements, scheduler: scheduler) + } +} + +extension ObservableType { + /** + Converts an array to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ array: [E], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return ObservableSequence(elements: array, scheduler: scheduler) + } + + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ sequence: S, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable where S.Iterator.Element == E { + return ObservableSequence(elements: sequence, scheduler: scheduler) + } +} + +final private class ObservableSequenceSink: Sink where S.Iterator.Element == O.E { + typealias Parent = ObservableSequence + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self._parent._scheduler.scheduleRecursive(self._parent._elements.makeIterator()) { iterator, recurse in + var mutableIterator = iterator + if let next = mutableIterator.next() { + self.forwardOn(.next(next)) + recurse(mutableIterator) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class ObservableSequence: Producer { + fileprivate let _elements: S + fileprivate let _scheduler: ImmediateSchedulerType + + init(elements: S, scheduler: ImmediateSchedulerType) { + self._elements = elements + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = ObservableSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift new file mode 100644 index 0000000..44e37d9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift @@ -0,0 +1,458 @@ +// +// ShareReplayScope.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/28/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +/// Subject lifetime scope +public enum SubjectLifetimeScope { + /** + **Each connection will have it's own subject instance to store replay events.** + **Connections will be isolated from each another.** + + Configures the underlying implementation to behave equivalent to. + + ``` + source.multicast(makeSubject: { MySubject() }).refCount() + ``` + + **This is the recommended default.** + + This has the following consequences: + * `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state. + * Each connection to source observable sequence will use it's own subject. + * When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared. + + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .whileConnected) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + + ``` + + Notice how time interval is different and `Performing work ...` is printed each time) + + ``` + Performing work ... + next 1495998900.82141 + completed + + Performing work ... + next 1495998900.82359 + completed + + Performing work ... + next 1495998900.82444 + completed + + + ``` + + */ + case whileConnected + + /** + **One subject will store replay events for all connections to source.** + **Connections won't be isolated from each another.** + + Configures the underlying implementation behave equivalent to. + + ``` + source.multicast(MySubject()).refCount() + ``` + + This has the following consequences: + * Using `retry` or `concat` operators after this operator usually isn't advised. + * Each connection to source observable sequence will share the same subject. + * After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will + continue holding a reference to the same subject. + If at some later moment a new observer initiates a new connection to source it can potentially receive + some of the stale events received during previous connection. + * After source sequence terminates any new observer will always immediately receive replayed elements and terminal event. + No new subscriptions to source observable sequence will be attempted. + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .forever) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + ``` + + Notice how time interval is the same, replayed, and `Performing work ...` is printed only once + + ``` + Performing work ... + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + ``` + + */ + case forever +} + +extension ObservableType { + + /** + Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. + + This operator is equivalent to: + * `.whileConnected` + ``` + // Each connection will have it's own subject instance to store replay events. + // Connections will be isolated from each another. + source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() + ``` + * `.forever` + ``` + // One subject will store replay events for all connections to source. + // Connections won't be isolated from each another. + source.multicast(Replay.create(bufferSize: replay)).refCount() + ``` + + It uses optimized versions of the operators for most common operations. + + - parameter replay: Maximum element count of the replay buffer. + - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) + -> Observable { + switch scope { + case .forever: + switch replay { + case 0: return self.multicast(PublishSubject()).refCount() + default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount() + } + case .whileConnected: + switch replay { + case 0: return ShareWhileConnected(source: self.asObservable()) + case 1: return ShareReplay1WhileConnected(source: self.asObservable()) + default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() + } + } + } +} + +fileprivate final class ShareReplay1WhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias E = Element + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareReplay1WhileConnected + private let _parent: Parent + private let _subscription = SingleAssignmentDisposable() + + private let _lock: RecursiveLock + private var _disposed: Bool = false + fileprivate var _observers = Observers() + fileprivate var _element: Element? + + init(parent: Parent, lock: RecursiveLock) { + self._parent = parent + self._lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + self._lock.lock() + let observers = self._synchronized_on(event) + self._lock.unlock() + dispatch(observers, event) + } + + final private func _synchronized_on(_ event: Event) -> Observers { + if self._disposed { + return Observers() + } + + switch event { + case .next(let element): + self._element = element + return self._observers + case .error, .completed: + let observers = self._observers + self._synchronized_dispose() + return observers + } + } + + final func connect() { + self._subscription.setDisposable(self._parent._source.subscribe(self)) + } + + final func _synchronized_subscribe(_ observer: O) -> Disposable where O.E == Element { + self._lock.lock(); defer { self._lock.unlock() } + if let element = self._element { + observer.on(.next(element)) + } + + let disposeKey = self._observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + + final private func _synchronized_dispose() { + self._disposed = true + if self._parent._connection === self { + self._parent._connection = nil + } + self._observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + self._lock.lock() + let shouldDisconnect = self._synchronized_unsubscribe(disposeKey) + self._lock.unlock() + if shouldDisconnect { + self._subscription.dispose() + } + } + + @inline(__always) + final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self._observers.removeKey(disposeKey) == nil { + return false + } + + if self._observers.count == 0 { + self._synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareReplay1WhileConnected + : Observable { + + fileprivate typealias Connection = ShareReplay1WhileConnectedConnection + + fileprivate let _source: Observable + + fileprivate let _lock = RecursiveLock() + + fileprivate var _connection: Connection? + + init(source: Observable) { + self._source = source + } + + override func subscribe(_ observer: O) -> Disposable where O.E == E { + self._lock.lock() + + let connection = self._synchronized_subscribe(observer) + let count = connection._observers.count + + let disposable = connection._synchronized_subscribe(observer) + + self._lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func _synchronized_subscribe(_ observer: O) -> Connection where O.E == E { + let connection: Connection + + if let existingConnection = self._connection { + connection = existingConnection + } + else { + connection = ShareReplay1WhileConnectedConnection( + parent: self, + lock: self._lock) + self._connection = connection + } + + return connection + } +} + +fileprivate final class ShareWhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias E = Element + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareWhileConnected + private let _parent: Parent + private let _subscription = SingleAssignmentDisposable() + + private let _lock: RecursiveLock + private var _disposed: Bool = false + fileprivate var _observers = Observers() + + init(parent: Parent, lock: RecursiveLock) { + self._parent = parent + self._lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + self._lock.lock() + let observers = self._synchronized_on(event) + self._lock.unlock() + dispatch(observers, event) + } + + final private func _synchronized_on(_ event: Event) -> Observers { + if self._disposed { + return Observers() + } + + switch event { + case .next: + return self._observers + case .error, .completed: + let observers = self._observers + self._synchronized_dispose() + return observers + } + } + + final func connect() { + self._subscription.setDisposable(self._parent._source.subscribe(self)) + } + + final func _synchronized_subscribe(_ observer: O) -> Disposable where O.E == Element { + self._lock.lock(); defer { self._lock.unlock() } + + let disposeKey = self._observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + + final private func _synchronized_dispose() { + self._disposed = true + if self._parent._connection === self { + self._parent._connection = nil + } + self._observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + self._lock.lock() + let shouldDisconnect = self._synchronized_unsubscribe(disposeKey) + self._lock.unlock() + if shouldDisconnect { + self._subscription.dispose() + } + } + + @inline(__always) + final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self._observers.removeKey(disposeKey) == nil { + return false + } + + if self._observers.count == 0 { + self._synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareWhileConnected + : Observable { + + fileprivate typealias Connection = ShareWhileConnectedConnection + + fileprivate let _source: Observable + + fileprivate let _lock = RecursiveLock() + + fileprivate var _connection: Connection? + + init(source: Observable) { + self._source = source + } + + override func subscribe(_ observer: O) -> Disposable where O.E == E { + self._lock.lock() + + let connection = self._synchronized_subscribe(observer) + let count = connection._observers.count + + let disposable = connection._synchronized_subscribe(observer) + + self._lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func _synchronized_subscribe(_ observer: O) -> Connection where O.E == E { + let connection: Connection + + if let existingConnection = self._connection { + connection = existingConnection + } + else { + connection = ShareWhileConnectedConnection( + parent: self, + lock: self._lock) + self._connection = connection + } + + return connection + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift new file mode 100644 index 0000000..cf40b65 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift @@ -0,0 +1,105 @@ +// +// SingleAsync.swift +// RxSwift +// +// Created by Junior B. on 09/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + The single operator is similar to first, but throws a `RxError.noElements` or `RxError.moreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single() + -> Observable { + return SingleAsync(source: self.asObservable()) + } + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single(_ predicate: @escaping (E) throws -> Bool) + -> Observable { + return SingleAsync(source: self.asObservable(), predicate: predicate) + } +} + +fileprivate final class SingleAsyncSink : Sink, ObserverType { + typealias ElementType = O.E + typealias Parent = SingleAsync + typealias E = ElementType + + private let _parent: Parent + private var _seenValue: Bool = false + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let forward = try self._parent._predicate?(value) ?? true + if !forward { + return + } + } + catch let error { + self.forwardOn(.error(error as Swift.Error)) + self.dispose() + return + } + + if self._seenValue { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + return + } + + self._seenValue = true + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self._seenValue { + self.forwardOn(.completed) + } else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class SingleAsync: Producer { + typealias Predicate = (Element) throws -> Bool + + fileprivate let _source: Observable + fileprivate let _predicate: Predicate? + + init(source: Observable, predicate: Predicate? = nil) { + self._source = source + self._predicate = predicate + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SingleAsyncSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sink.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sink.swift new file mode 100644 index 0000000..9b1018b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Sink.swift @@ -0,0 +1,75 @@ +// +// Sink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Sink : Disposable { + fileprivate let _observer: O + fileprivate let _cancel: Cancelable + fileprivate let _disposed = AtomicInt(0) + + #if DEBUG + fileprivate let _synchronizationTracker = SynchronizationTracker() + #endif + + init(observer: O, cancel: Cancelable) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self._observer = observer + self._cancel = cancel + } + + final func forwardOn(_ event: Event) { + #if DEBUG + self._synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self._synchronizationTracker.unregister() } + #endif + if isFlagSet(self._disposed, 1) { + return + } + self._observer.on(event) + } + + final func forwarder() -> SinkForward { + return SinkForward(forward: self) + } + + final var disposed: Bool { + return isFlagSet(self._disposed, 1) + } + + func dispose() { + fetchOr(self._disposed, 1) + self._cancel.dispose() + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final class SinkForward: ObserverType { + typealias E = O.E + + private let _forward: Sink + + init(forward: Sink) { + self._forward = forward + } + + final func on(_ event: Event) { + switch event { + case .next: + self._forward._observer.on(event) + case .error, .completed: + self._forward._observer.on(event) + self._forward._cancel.dispose() + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Skip.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Skip.swift new file mode 100644 index 0000000..bc49283 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Skip.swift @@ -0,0 +1,159 @@ +// +// Skip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + public func skip(_ count: Int) + -> Observable { + return SkipCount(source: self.asObservable(), count: count) + } +} + +extension ObservableType { + + /** + Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter duration: Duration for skipping elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// count version + +final private class SkipCountSink: Sink, ObserverType { + typealias Element = O.E + typealias Parent = SkipCount + + let parent: Parent + + var remaining: Int + + init(parent: Parent, observer: O, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self.remaining <= 0 { + self.forwardOn(.next(value)) + } + else { + self.remaining -= 1 + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class SkipCount: Producer { + let source: Observable + let count: Int + + init(source: Observable, count: Int) { + self.source = source + self.count = count + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class SkipTimeSink: Sink, ObserverType where O.E == ElementType { + typealias Parent = SkipTime + typealias Element = ElementType + + let parent: Parent + + // state + var open = false + + init(parent: Parent, observer: O, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if self.open { + self.forwardOn(.next(value)) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self.open = true + } + + func run() -> Disposable { + let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self.parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class SkipTime: Producer { + let source: Observable + let duration: RxTimeInterval + let scheduler: SchedulerType + + init(source: Observable, duration: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift new file mode 100644 index 0000000..7681b14 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift @@ -0,0 +1,139 @@ +// +// SkipUntil.swift +// RxSwift +// +// Created by Yury Korolev on 10/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + public func skipUntil(_ other: O) + -> Observable { + return SkipUntil(source: self.asObservable(), other: other.asObservable()) + } +} + +final private class SkipUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = SkipUntilSink + typealias E = Other + + fileprivate let _parent: Parent + + var _lock: RecursiveLock { + return self._parent._lock + } + + let _subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self._parent = parent + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + self._parent._forwardElements = true + self._subscription.dispose() + case .error(let e): + self._parent.forwardOn(.error(e)) + self._parent.dispose() + case .completed: + self._subscription.dispose() + } + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif + +} + + +final private class SkipUntilSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = O.E + typealias Parent = SkipUntil + + let _lock = RecursiveLock() + fileprivate let _parent: Parent + fileprivate var _forwardElements = false + + fileprivate let _sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + if self._forwardElements { + self.forwardOn(event) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self._forwardElements { + self.forwardOn(event) + } + self.dispose() + } + } + + func run() -> Disposable { + let sourceSubscription = self._parent._source.subscribe(self) + let otherObserver = SkipUntilSinkOther(parent: self) + let otherSubscription = self._parent._other.subscribe(otherObserver) + self._sourceSubscription.setDisposable(sourceSubscription) + otherObserver._subscription.setDisposable(otherSubscription) + + return Disposables.create(_sourceSubscription, otherObserver._subscription) + } +} + +final private class SkipUntil: Producer { + + fileprivate let _source: Observable + fileprivate let _other: Observable + + init(source: Observable, other: Observable) { + self._source = source + self._other = other + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SkipUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift new file mode 100644 index 0000000..a0fbdf5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift @@ -0,0 +1,75 @@ +// +// SkipWhile.swift +// RxSwift +// +// Created by Yury Korolev on 10/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + public func skipWhile(_ predicate: @escaping (E) throws -> Bool) -> Observable { + return SkipWhile(source: self.asObservable(), predicate: predicate) + } +} + +final private class SkipWhileSink: Sink, ObserverType { + typealias Element = O.E + typealias Parent = SkipWhile + + fileprivate let _parent: Parent + fileprivate var _running = false + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self._running { + do { + self._running = try !self._parent._predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + } + + if self._running { + self.forwardOn(.next(value)) + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class SkipWhile: Producer { + typealias Predicate = (Element) throws -> Bool + + fileprivate let _source: Observable + fileprivate let _predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self._source = source + self._predicate = predicate + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SkipWhileSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/StartWith.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/StartWith.swift new file mode 100644 index 0000000..842f4af --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/StartWith.swift @@ -0,0 +1,42 @@ +// +// StartWith.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Prepends a sequence of values to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter elements: Elements to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + public func startWith(_ elements: E ...) + -> Observable { + return StartWith(source: self.asObservable(), elements: elements) + } +} + +final private class StartWith: Producer { + let elements: [Element] + let source: Observable + + init(source: Observable, elements: [Element]) { + self.source = source + self.elements = elements + super.init() + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + for e in self.elements { + observer.on(.next(e)) + } + + return (sink: Disposables.create(), subscription: self.source.subscribe(observer)) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift new file mode 100644 index 0000000..2d0d348 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift @@ -0,0 +1,83 @@ +// +// SubscribeOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + public func subscribeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + return SubscribeOn(source: self, scheduler: scheduler) + } +} + +final private class SubscribeOnSink: Sink, ObserverType where Ob.E == O.E { + typealias Element = O.E + typealias Parent = SubscribeOn + + let parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.forwardOn(event) + + if event.isStopEvent { + self.dispose() + } + } + + func run() -> Disposable { + let disposeEverything = SerialDisposable() + let cancelSchedule = SingleAssignmentDisposable() + + disposeEverything.disposable = cancelSchedule + + let disposeSchedule = self.parent.scheduler.schedule(()) { _ -> Disposable in + let subscription = self.parent.source.subscribe(self) + disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) + return Disposables.create() + } + + cancelSchedule.setDisposable(disposeSchedule) + + return disposeEverything + } +} + +final private class SubscribeOn: Producer { + let source: Ob + let scheduler: ImmediateSchedulerType + + init(source: Ob, scheduler: ImmediateSchedulerType) { + self.source = source + self.scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Ob.E { + let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Switch.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Switch.swift new file mode 100644 index 0000000..5139f0e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Switch.swift @@ -0,0 +1,233 @@ +// +// Switch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (E) throws -> O) + -> Observable { + return FlatMapLatest(source: self.asObservable(), selector: selector) + } +} + +extension ObservableType where E : ObservableConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func switchLatest() -> Observable { + return Switch(source: self.asObservable()) + } +} + +private class SwitchSink + : Sink + , ObserverType where S.E == O.E { + typealias E = SourceType + + fileprivate let _subscriptions: SingleAssignmentDisposable = SingleAssignmentDisposable() + fileprivate let _innerSubscription: SerialDisposable = SerialDisposable() + + let _lock = RecursiveLock() + + // state + fileprivate var _stopped = false + fileprivate var _latest = 0 + fileprivate var _hasLatest = false + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + self._subscriptions.setDisposable(subscription) + return Disposables.create(_subscriptions, _innerSubscription) + } + + func performMap(_ element: SourceType) throws -> S { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: E) -> (Int, Observable)? { + self._lock.lock(); defer { self._lock.unlock() } // { + do { + let observable = try self.performMap(element).asObservable() + self._hasLatest = true + self._latest = self._latest &+ 1 + return (self._latest, observable) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + return nil + // } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let (latest, observable) = self.nextElementArrived(element: element) { + let d = SingleAssignmentDisposable() + self._innerSubscription.disposable = d + + let observer = SwitchSinkIter(parent: self, id: latest, _self: d) + let disposable = observable.subscribe(observer) + d.setDisposable(disposable) + } + case .error(let error): + self._lock.lock(); defer { self._lock.unlock() } + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self._lock.lock(); defer { self._lock.unlock() } + self._stopped = true + + self._subscriptions.dispose() + + if !self._hasLatest { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class SwitchSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where S.E == O.E { + typealias E = S.E + typealias Parent = SwitchSink + + fileprivate let _parent: Parent + fileprivate let _id: Int + fileprivate let _self: Disposable + + var _lock: RecursiveLock { + return self._parent._lock + } + + init(parent: Parent, id: Int, _self: Disposable) { + self._parent = parent + self._id = id + self._self = _self + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: break + case .error, .completed: + self._self.dispose() + } + + if self._parent._latest != self._id { + return + } + + switch event { + case .next: + self._parent.forwardOn(event) + case .error: + self._parent.forwardOn(event) + self._parent.dispose() + case .completed: + self._parent._hasLatest = false + if self._parent._stopped { + self._parent.forwardOn(event) + self._parent.dispose() + } + } + } +} + +// MARK: Specializations + +final private class SwitchIdentitySink: SwitchSink where O.E == S.E { + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: S) throws -> S { + return element + } +} + +final private class MapSwitchSink: SwitchSink where O.E == S.E { + typealias Selector = (SourceType) throws -> S + + fileprivate let _selector: Selector + + init(selector: @escaping Selector, observer: O, cancel: Cancelable) { + self._selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceType) throws -> S { + return try self._selector(element) + } +} + +// MARK: Producers + +final private class Switch: Producer { + fileprivate let _source: Observable + + init(source: Observable) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = SwitchIdentitySink(observer: observer, cancel: cancel) + let subscription = sink.run(self._source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapLatest: Producer { + typealias Selector = (SourceType) throws -> S + + fileprivate let _source: Observable + fileprivate let _selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self._source = source + self._selector = selector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { + let sink = MapSwitchSink(selector: self._selector, observer: observer, cancel: cancel) + let subscription = sink.run(self._source) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift new file mode 100644 index 0000000..2ce6f24 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift @@ -0,0 +1,104 @@ +// +// SwitchIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter switchTo: Observable sequence being returned when source sequence is empty. + - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. + */ + public func ifEmpty(switchTo other: Observable) -> Observable { + return SwitchIfEmpty(source: self.asObservable(), ifEmpty: other) + } +} + +final private class SwitchIfEmpty: Producer { + + private let _source: Observable + private let _ifEmpty: Observable + + init(source: Observable, ifEmpty: Observable) { + self._source = source + self._ifEmpty = ifEmpty + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = SwitchIfEmptySink(ifEmpty: self._ifEmpty, + observer: observer, + cancel: cancel) + let subscription = sink.run(self._source.asObservable()) + + return (sink: sink, subscription: subscription) + } +} + +final private class SwitchIfEmptySink: Sink + , ObserverType { + typealias E = O.E + + private let _ifEmpty: Observable + private var _isEmpty = true + private let _ifEmptySubscription = SingleAssignmentDisposable() + + init(ifEmpty: Observable, observer: O, cancel: Cancelable) { + self._ifEmpty = ifEmpty + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + return Disposables.create(subscription, _ifEmptySubscription) + } + + func on(_ event: Event) { + switch event { + case .next: + self._isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + guard self._isEmpty else { + self.forwardOn(.completed) + self.dispose() + return + } + let ifEmptySink = SwitchIfEmptySinkIter(parent: self) + self._ifEmptySubscription.setDisposable(self._ifEmpty.subscribe(ifEmptySink)) + } + } +} + +final private class SwitchIfEmptySinkIter + : ObserverType { + typealias E = O.E + typealias Parent = SwitchIfEmptySink + + private let _parent: Parent + + init(parent: Parent) { + self._parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self._parent.forwardOn(event) + case .error: + self._parent.forwardOn(event) + self._parent.dispose() + case .completed: + self._parent.forwardOn(event) + self._parent.dispose() + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Take.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Take.swift new file mode 100644 index 0000000..cbfb57f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Take.swift @@ -0,0 +1,180 @@ +// +// Take.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the start of an observable sequence. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter count: The number of elements to return. + - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. + */ + public func take(_ count: Int) + -> Observable { + if count == 0 { + return Observable.empty() + } + else { + return TakeCount(source: self.asObservable(), count: count) + } + } +} + +extension ObservableType { + + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + public func take(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// count version + +final private class TakeCountSink: Sink, ObserverType { + typealias E = O.E + typealias Parent = TakeCount + + private let _parent: Parent + + private var _remaining: Int + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._remaining = parent._count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self._remaining > 0 { + self._remaining -= 1 + + self.forwardOn(.next(value)) + + if self._remaining == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeCount: Producer { + fileprivate let _source: Observable + fileprivate let _count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self._source = source + self._count = count + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class TakeTimeSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where O.E == ElementType { + typealias Parent = TakeTime + typealias E = ElementType + + fileprivate let _parent: Parent + + let _lock = RecursiveLock() + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self._lock.lock(); defer { self._lock.unlock() } + + self.forwardOn(.completed) + self.dispose() + } + + func run() -> Disposable { + let disposeTimer = self._parent._scheduler.scheduleRelative((), dueTime: self._parent._duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self._parent._source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class TakeTime: Producer { + typealias TimeInterval = RxTimeInterval + + fileprivate let _source: Observable + fileprivate let _duration: TimeInterval + fileprivate let _scheduler: SchedulerType + + init(source: Observable, duration: TimeInterval, scheduler: SchedulerType) { + self._source = source + self._scheduler = scheduler + self._duration = duration + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeLast.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeLast.swift new file mode 100644 index 0000000..2267296 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeLast.swift @@ -0,0 +1,78 @@ +// +// TakeLast.swift +// RxSwift +// +// Created by Tomi Koskinen on 25/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the end of an observable sequence. + + This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + + - seealso: [takeLast operator on reactivex.io](http://reactivex.io/documentation/operators/takelast.html) + + - parameter count: Number of elements to take from the end of the source sequence. + - returns: An observable sequence containing the specified number of elements from the end of the source sequence. + */ + public func takeLast(_ count: Int) + -> Observable { + return TakeLast(source: self.asObservable(), count: count) + } +} + +final private class TakeLastSink: Sink, ObserverType { + typealias E = O.E + typealias Parent = TakeLast + + private let _parent: Parent + + private var _elements: Queue + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._elements = Queue(capacity: parent._count + 1) + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self._elements.enqueue(value) + if self._elements.count > self._parent._count { + _ = self._elements.dequeue() + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + for e in self._elements { + self.forwardOn(.next(e)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class TakeLast: Producer { + fileprivate let _source: Observable + fileprivate let _count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self._source = source + self._count = count + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeLastSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift new file mode 100644 index 0000000..b0d6927 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift @@ -0,0 +1,227 @@ +// +// TakeUntil.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + public func takeUntil(_ other: O) + -> Observable { + return TakeUntil(source: self.asObservable(), other: other.asObservable()) + } + + /** + Returns elements from an observable sequence until the specified condition is true. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter behavior: Whether or not to include the last element matching the predicate. + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. + */ + public func takeUntil(_ behavior: TakeUntilBehavior, + predicate: @escaping (E) throws -> Bool) + -> Observable { + return TakeUntilPredicate(source: self.asObservable(), + behavior: behavior, + predicate: predicate) + } +} + +/// Behaviors for the `takeUntil(_ behavior:predicate:)` operator. +public enum TakeUntilBehavior { + /// Include the last element matching the predicate. + case inclusive + + /// Exclude the last element matching the predicate. + case exclusive +} + +// MARK: - TakeUntil Observable +final private class TakeUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = TakeUntilSink + typealias E = Other + + fileprivate let _parent: Parent + + var _lock: RecursiveLock { + return self._parent._lock + } + + fileprivate let _subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self._parent = parent +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + self._parent.forwardOn(.completed) + self._parent.dispose() + case .error(let e): + self._parent.forwardOn(.error(e)) + self._parent.dispose() + case .completed: + self._subscription.dispose() + } + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +final private class TakeUntilSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias E = O.E + typealias Parent = TakeUntil + + fileprivate let _parent: Parent + + let _lock = RecursiveLock() + + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func run() -> Disposable { + let otherObserver = TakeUntilSinkOther(parent: self) + let otherSubscription = self._parent._other.subscribe(otherObserver) + otherObserver._subscription.setDisposable(otherSubscription) + let sourceSubscription = self._parent._source.subscribe(self) + + return Disposables.create(sourceSubscription, otherObserver._subscription) + } +} + +final private class TakeUntil: Producer { + + fileprivate let _source: Observable + fileprivate let _other: Observable + + init(source: Observable, other: Observable) { + self._source = source + self._other = other + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// MARK: - TakeUntil Predicate +final private class TakeUntilPredicateSink + : Sink, ObserverType { + typealias Element = O.E + typealias Parent = TakeUntilPredicate + + fileprivate let _parent: Parent + fileprivate var _running = true + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self._running { + return + } + + do { + self._running = try !self._parent._predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + if self._running { + self.forwardOn(.next(value)) + } else { + if self._parent._behavior == .inclusive { + self.forwardOn(.next(value)) + } + + self.forwardOn(.completed) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeUntilPredicate: Producer { + typealias Predicate = (Element) throws -> Bool + + fileprivate let _source: Observable + fileprivate let _predicate: Predicate + fileprivate let _behavior: TakeUntilBehavior + + init(source: Observable, + behavior: TakeUntilBehavior, + predicate: @escaping Predicate) { + self._source = source + self._behavior = behavior + self._predicate = predicate + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeUntilPredicateSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift new file mode 100644 index 0000000..1e866f8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift @@ -0,0 +1,85 @@ +// +// TakeWhile.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + public func takeWhile(_ predicate: @escaping (E) throws -> Bool) + -> Observable { + return TakeWhile(source: self.asObservable(), predicate: predicate) + } +} + +final private class TakeWhileSink + : Sink + , ObserverType { + typealias Element = O.E + typealias Parent = TakeWhile + + fileprivate let _parent: Parent + + fileprivate var _running = true + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self._running { + return + } + + do { + self._running = try self._parent._predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + if self._running { + self.forwardOn(.next(value)) + } else { + self.forwardOn(.completed) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeWhile: Producer { + typealias Predicate = (Element) throws -> Bool + + fileprivate let _source: Observable + fileprivate let _predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self._source = source + self._predicate = predicate + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TakeWhileSink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Throttle.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Throttle.swift new file mode 100644 index 0000000..c31ae74 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Throttle.swift @@ -0,0 +1,162 @@ +// +// Throttle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date + +extension ObservableType { + + /** + Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. + + This operator makes sure that no two elements are emitted in less then dueTime. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType) + -> Observable { + return Throttle(source: self.asObservable(), dueTime: dueTime, latest: latest, scheduler: scheduler) + } +} + +final private class ThrottleSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = O.E + typealias ParentType = Throttle + + private let _parent: ParentType + + let _lock = RecursiveLock() + + // state + private var _lastUnsentElement: Element? + private var _lastSentTime: Date? + private var _completed: Bool = false + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: O, cancel: Cancelable) { + self._parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self._parent._source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case .next(let element): + let now = self._parent._scheduler.now + + let timeIntervalSinceLast: RxTimeInterval + + if let lastSendingTime = self._lastSentTime { + timeIntervalSinceLast = now.timeIntervalSince(lastSendingTime) + } + else { + timeIntervalSinceLast = self._parent._dueTime + } + + let couldSendNow = timeIntervalSinceLast >= self._parent._dueTime + + if couldSendNow { + self.sendNow(element: element) + return + } + + if !self._parent._latest { + return + } + + let isThereAlreadyInFlightRequest = self._lastUnsentElement != nil + + self._lastUnsentElement = element + + if isThereAlreadyInFlightRequest { + return + } + + let scheduler = self._parent._scheduler + let dueTime = self._parent._dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + + d.setDisposable(scheduler.scheduleRelative(0, dueTime: dueTime - timeIntervalSinceLast, action: self.propagate)) + case .error: + self._lastUnsentElement = nil + self.forwardOn(event) + self.dispose() + case .completed: + if self._lastUnsentElement != nil { + self._completed = true + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } + + private func sendNow(element: Element) { + self._lastUnsentElement = nil + self.forwardOn(.next(element)) + // in case element processing takes a while, this should give some more room + self._lastSentTime = self._parent._scheduler.now + } + + func propagate(_: Int) -> Disposable { + self._lock.lock(); defer { self._lock.unlock() } // { + if let lastUnsentElement = self._lastUnsentElement { + self.sendNow(element: lastUnsentElement) + } + + if self._completed { + self.forwardOn(.completed) + self.dispose() + } + // } + return Disposables.create() + } +} + +final private class Throttle: Producer { + fileprivate let _source: Observable + fileprivate let _dueTime: RxTimeInterval + fileprivate let _latest: Bool + fileprivate let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, latest: Bool, scheduler: SchedulerType) { + self._source = source + self._dueTime = dueTime + self._latest = latest + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = ThrottleSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Timeout.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Timeout.swift new file mode 100644 index 0000000..f37bf76 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Timeout.swift @@ -0,0 +1,151 @@ +// +// Timeout.swift +// RxSwift +// +// Created by Tomi Koskinen on 13/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: An observable sequence with a `RxError.timeout` in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.timeout), scheduler: scheduler) + } + + /** + Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter other: Sequence to return in case of a timeout. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: The source sequence switching to the other sequence in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, other: O, scheduler: SchedulerType) + -> Observable where E == O.E { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) + } +} + +final private class TimeoutSink: Sink, LockOwnerType, ObserverType { + typealias E = O.E + typealias Parent = Timeout + + private let _parent: Parent + + let _lock = RecursiveLock() + + private let _timerD = SerialDisposable() + private let _subscription = SerialDisposable() + + private var _id = 0 + private var _switched = false + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let original = SingleAssignmentDisposable() + self._subscription.disposable = original + + self._createTimeoutTimer() + + original.setDisposable(self._parent._source.subscribe(self)) + + return Disposables.create(_subscription, _timerD) + } + + func on(_ event: Event) { + switch event { + case .next: + var onNextWins = false + + self._lock.performLocked { + onNextWins = !self._switched + if onNextWins { + self._id = self._id &+ 1 + } + } + + if onNextWins { + self.forwardOn(event) + self._createTimeoutTimer() + } + case .error, .completed: + var onEventWins = false + + self._lock.performLocked { + onEventWins = !self._switched + if onEventWins { + self._id = self._id &+ 1 + } + } + + if onEventWins { + self.forwardOn(event) + self.dispose() + } + } + } + + private func _createTimeoutTimer() { + if self._timerD.isDisposed { + return + } + + let nextTimer = SingleAssignmentDisposable() + self._timerD.disposable = nextTimer + + let disposeSchedule = self._parent._scheduler.scheduleRelative(self._id, dueTime: self._parent._dueTime) { state in + + var timerWins = false + + self._lock.performLocked { + self._switched = (state == self._id) + timerWins = self._switched + } + + if timerWins { + self._subscription.disposable = self._parent._other.subscribe(self.forwarder()) + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposeSchedule) + } +} + + +final private class Timeout: Producer { + fileprivate let _source: Observable + fileprivate let _dueTime: RxTimeInterval + fileprivate let _other: Observable + fileprivate let _scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, other: Observable, scheduler: SchedulerType) { + self._source = source + self._dueTime = dueTime + self._other = other + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { + let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Timer.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Timer.swift new file mode 100644 index 0000000..1715e1e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Timer.swift @@ -0,0 +1,116 @@ +// +// Timer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where E : RxAbstractInteger { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence that produces a value after each period. + */ + public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: period, + period: period, + scheduler: scheduler + ) + } +} + +extension ObservableType where E: RxAbstractInteger { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - parameter scheduler: Scheduler to run timers on. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: dueTime, + period: period, + scheduler: scheduler + ) + } +} + +import Foundation + +final private class TimerSink : Sink where O.E : RxAbstractInteger { + typealias Parent = Timer + + private let _parent: Parent + private let _lock = RecursiveLock() + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self._parent._scheduler.schedulePeriodic(0 as O.E, startAfter: self._parent._dueTime, period: self._parent._period!) { state in + self._lock.lock(); defer { self._lock.unlock() } + self.forwardOn(.next(state)) + return state &+ 1 + } + } +} + +final private class TimerOneOffSink: Sink where O.E: RxAbstractInteger { + typealias Parent = Timer + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self._parent._scheduler.scheduleRelative(self, dueTime: self._parent._dueTime) { [unowned self] _ -> Disposable in + self.forwardOn(.next(0)) + self.forwardOn(.completed) + self.dispose() + + return Disposables.create() + } + } +} + +final private class Timer: Producer { + fileprivate let _scheduler: SchedulerType + fileprivate let _dueTime: RxTimeInterval + fileprivate let _period: RxTimeInterval? + + init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) { + self._scheduler = scheduler + self._dueTime = dueTime + self._period = period + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + if self._period != nil { + let sink = TimerSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + else { + let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ToArray.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ToArray.swift new file mode 100644 index 0000000..5cf1aa4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/ToArray.swift @@ -0,0 +1,66 @@ +// +// ToArray.swift +// RxSwift +// +// Created by Junior B. on 20/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + +extension ObservableType { + + /** + Converts an Observable into another Observable that emits the whole sequence as a single array and then terminates. + + For aggregation behavior see `reduce`. + + - seealso: [toArray operator on reactivex.io](http://reactivex.io/documentation/operators/to.html) + + - returns: An observable sequence containing all the emitted elements as array. + */ + public func toArray() + -> Observable<[E]> { + return ToArray(source: self.asObservable()) + } +} + +final private class ToArraySink: Sink, ObserverType where O.E == [SourceType] { + typealias Parent = ToArray + + let _parent: Parent + var _list = [SourceType]() + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self._list.append(value) + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + self.forwardOn(.next(self._list)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class ToArray: Producer<[SourceType]> { + let _source: Observable + + init(source: Observable) { + self._source = source + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [SourceType] { + let sink = ToArraySink(parent: self, observer: observer, cancel: cancel) + let subscription = self._source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Using.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Using.swift new file mode 100644 index 0000000..3651dc9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Using.swift @@ -0,0 +1,90 @@ +// +// Using.swift +// RxSwift +// +// Created by Yury Korolev on 10/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + + - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html) + + - parameter resourceFactory: Factory function to obtain a resource object. + - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. + - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + public static func using(_ resourceFactory: @escaping () throws -> Resource, observableFactory: @escaping (Resource) throws -> Observable) -> Observable { + return Using(resourceFactory: resourceFactory, observableFactory: observableFactory) + } +} + +final private class UsingSink: Sink, ObserverType { + typealias SourceType = O.E + typealias Parent = Using + + private let _parent: Parent + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + var disposable = Disposables.create() + + do { + let resource = try self._parent._resourceFactory() + disposable = resource + let source = try self._parent._observableFactory(resource) + + return Disposables.create( + source.subscribe(self), + disposable + ) + } catch let error { + return Disposables.create( + Observable.error(error).subscribe(self), + disposable + ) + } + } + + func on(_ event: Event) { + switch event { + case let .next(value): + self.forwardOn(.next(value)) + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Using: Producer { + + typealias E = SourceType + + typealias ResourceFactory = () throws -> ResourceType + typealias ObservableFactory = (ResourceType) throws -> Observable + + fileprivate let _resourceFactory: ResourceFactory + fileprivate let _observableFactory: ObservableFactory + + + init(resourceFactory: @escaping ResourceFactory, observableFactory: @escaping ObservableFactory) { + self._resourceFactory = resourceFactory + self._observableFactory = observableFactory + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { + let sink = UsingSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Window.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Window.swift new file mode 100644 index 0000000..5de452c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Window.swift @@ -0,0 +1,169 @@ +// +// Window.swift +// RxSwift +// +// Created by Junior B. on 29/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. + + - seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html) + + - parameter timeSpan: Maximum time length of a window. + - parameter count: Maximum element count of a window. + - parameter scheduler: Scheduler to run windowing timers on. + - returns: An observable sequence of windows (instances of `Observable`). + */ + public func window(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable> { + return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class WindowTimeCountSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType where O.E == Observable { + typealias Parent = WindowTimeCount + typealias E = Element + + private let _parent: Parent + + let _lock = RecursiveLock() + + private var _subject = PublishSubject() + private var _count = 0 + private var _windowId = 0 + + private let _timerD = SerialDisposable() + private let _refCountDisposable: RefCountDisposable + private let _groupDisposable = CompositeDisposable() + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + + _ = self._groupDisposable.insert(self._timerD) + + self._refCountDisposable = RefCountDisposable(disposable: self._groupDisposable) + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + + self.forwardOn(.next(AddRef(source: self._subject, refCount: self._refCountDisposable).asObservable())) + self.createTimer(self._windowId) + + _ = self._groupDisposable.insert(self._parent._source.subscribe(self)) + return self._refCountDisposable + } + + func startNewWindowAndCompleteCurrentOne() { + self._subject.on(.completed) + self._subject = PublishSubject() + + self.forwardOn(.next(AddRef(source: self._subject, refCount: self._refCountDisposable).asObservable())) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + var newWindow = false + var newId = 0 + + switch event { + case .next(let element): + self._subject.on(.next(element)) + + do { + _ = try incrementChecked(&self._count) + } catch let e { + self._subject.on(.error(e as Swift.Error)) + self.dispose() + } + + if self._count == self._parent._count { + newWindow = true + self._count = 0 + self._windowId += 1 + newId = self._windowId + self.startNewWindowAndCompleteCurrentOne() + } + + case .error(let error): + self._subject.on(.error(error)) + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self._subject.on(.completed) + self.forwardOn(.completed) + self.dispose() + } + + if newWindow { + self.createTimer(newId) + } + } + + func createTimer(_ windowId: Int) { + if self._timerD.isDisposed { + return + } + + if self._windowId != windowId { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self._timerD.disposable = nextTimer + + let scheduledRelative = self._parent._scheduler.scheduleRelative(windowId, dueTime: self._parent._timeSpan) { previousWindowId in + + var newId = 0 + + self._lock.performLocked { + if previousWindowId != self._windowId { + return + } + + self._count = 0 + self._windowId = self._windowId &+ 1 + newId = self._windowId + self.startNewWindowAndCompleteCurrentOne() + } + + self.createTimer(newId) + + return Disposables.create() + } + + nextTimer.setDisposable(scheduledRelative) + } +} + +final private class WindowTimeCount: Producer> { + fileprivate let _timeSpan: RxTimeInterval + fileprivate let _count: Int + fileprivate let _scheduler: SchedulerType + fileprivate let _source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self._source = source + self._timeSpan = timeSpan + self._count = count + self._scheduler = scheduler + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Observable { + let sink = WindowTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift new file mode 100644 index 0000000..1a1b594 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift @@ -0,0 +1,149 @@ +// +// WithLatestFrom.swift +// RxSwift +// +// Created by Yury Korolev on 10/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO, resultSelector: @escaping (E, SecondO.E) throws -> ResultType) -> Observable { + return WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: resultSelector) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO) -> Observable { + return WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: { $1 }) + } +} + +final private class WithLatestFromSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ResultType = O.E + typealias Parent = WithLatestFrom + typealias E = FirstType + + fileprivate let _parent: Parent + + var _lock = RecursiveLock() + fileprivate var _latest: SecondType? + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let sndSubscription = SingleAssignmentDisposable() + let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription) + + sndSubscription.setDisposable(self._parent._second.subscribe(sndO)) + let fstSubscription = self._parent._first.subscribe(self) + + return Disposables.create(fstSubscription, sndSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case let .next(value): + guard let latest = self._latest else { return } + do { + let res = try self._parent._resultSelector(value, latest) + + self.forwardOn(.next(res)) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class WithLatestFromSecond + : ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias ResultType = O.E + typealias Parent = WithLatestFromSink + typealias E = SecondType + + private let _parent: Parent + private let _disposable: Disposable + + var _lock: RecursiveLock { + return self._parent._lock + } + + init(parent: Parent, disposable: Disposable) { + self._parent = parent + self._disposable = disposable + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + switch event { + case let .next(value): + self._parent._latest = value + case .completed: + self._disposable.dispose() + case let .error(error): + self._parent.forwardOn(.error(error)) + self._parent.dispose() + } + } +} + +final private class WithLatestFrom: Producer { + typealias ResultSelector = (FirstType, SecondType) throws -> ResultType + + fileprivate let _first: Observable + fileprivate let _second: Observable + fileprivate let _resultSelector: ResultSelector + + init(first: Observable, second: Observable, resultSelector: @escaping ResultSelector) { + self._first = first + self._second = second + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType { + let sink = WithLatestFromSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift new file mode 100644 index 0000000..c2b5819 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift @@ -0,0 +1,169 @@ +// +// Zip+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip(_ collection: C, _ resultSelector: @escaping ([C.Iterator.Element.E]) throws -> E) -> Observable + where C.Iterator.Element: ObservableType { + return ZipCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip(_ collection: C) -> Observable<[E]> + where C.Iterator.Element: ObservableType, C.Iterator.Element.E == E { + return ZipCollectionType(sources: collection, resultSelector: { $0 }) + } + +} + +final private class ZipCollectionTypeSink + : Sink where C.Iterator.Element: ObservableConvertibleType { + typealias R = O.E + typealias Parent = ZipCollectionType + typealias SourceElement = C.Iterator.Element.E + + private let _parent: Parent + + private let _lock = RecursiveLock() + + // state + private var _numberOfValues = 0 + private var _values: [Queue] + private var _isDone: [Bool] + private var _numberOfDone = 0 + private var _subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + self._values = [Queue](repeating: Queue(capacity: 4), count: parent.count) + self._isDone = [Bool](repeating: false, count: parent.count) + self._subscriptions = [SingleAssignmentDisposable]() + self._subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + self._subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self._lock.lock(); defer { self._lock.unlock() } // { + switch event { + case .next(let element): + self._values[atIndex].enqueue(element) + + if self._values[atIndex].count == 1 { + self._numberOfValues += 1 + } + + if self._numberOfValues < self._parent.count { + if self._numberOfDone == self._parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + var arguments = [SourceElement]() + arguments.reserveCapacity(self._parent.count) + + // recalculate number of values + self._numberOfValues = 0 + + for i in 0 ..< self._values.count { + arguments.append(self._values[i].dequeue()!) + if !self._values[i].isEmpty { + self._numberOfValues += 1 + } + } + + let result = try self._parent.resultSelector(arguments) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self._isDone[atIndex] { + return + } + + self._isDone[atIndex] = true + self._numberOfDone += 1 + + if self._numberOfDone == self._parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + self._subscriptions[atIndex].dispose() + } + } + // } + } + + func run() -> Disposable { + var j = 0 + for i in self._parent.sources { + let index = j + let source = i.asObservable() + + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + self._subscriptions[j].setDisposable(disposable) + j += 1 + } + + if self._parent.sources.isEmpty { + self.forwardOn(.completed) + } + + return Disposables.create(_subscriptions) + } +} + +final private class ZipCollectionType: Producer where C.Iterator.Element: ObservableConvertibleType { + typealias ResultSelector = ([C.Iterator.Element.E]) throws -> R + + let sources: C + let resultSelector: ResultSelector + let count: Int + + init(sources: C, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = Int(Int64(self.sources.count)) + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift new file mode 100644 index 0000000..01992f4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift @@ -0,0 +1,990 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// Zip+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.E, O2.E) throws -> E) + -> Observable { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2) + -> Observable<(O1.E, O2.E)> { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class ZipSink2_ : ZipSink { + typealias R = O.E + typealias Parent = Zip2 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self._values1.isEmpty + case 1: return !self._values2.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + + #if swift(>=4.2) + #if !compiler(>=5.0) + return false + #endif + #else + return false + #endif + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self._lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self._lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + + subscription1.setDisposable(self._parent.source1.subscribe(observer1)) + subscription2.setDisposable(self._parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!) + } +} + +final class Zip2 : Producer { + typealias ResultSelector = (E1, E2) throws -> R + + let source1: Observable + let source2: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.E, O2.E, O3.E) throws -> E) + -> Observable { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.E, O2.E, O3.E)> { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class ZipSink3_ : ZipSink { + typealias R = O.E + typealias Parent = Zip3 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self._values1.isEmpty + case 1: return !self._values2.isEmpty + case 2: return !self._values3.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + + #if swift(>=4.2) + #if !compiler(>=5.0) + return false + #endif + #else + return false + #endif + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self._lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self._lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self._lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + + subscription1.setDisposable(self._parent.source1.subscribe(observer1)) + subscription2.setDisposable(self._parent.source2.subscribe(observer2)) + subscription3.setDisposable(self._parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!, self._values3.dequeue()!) + } +} + +final class Zip3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E) throws -> E) + -> Observable { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.E, O2.E, O3.E, O4.E)> { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class ZipSink4_ : ZipSink { + typealias R = O.E + typealias Parent = Zip4 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self._values1.isEmpty + case 1: return !self._values2.isEmpty + case 2: return !self._values3.isEmpty + case 3: return !self._values4.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + + #if swift(>=4.2) + #if !compiler(>=5.0) + return false + #endif + #else + return false + #endif + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self._lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self._lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self._lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self._lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + + subscription1.setDisposable(self._parent.source1.subscribe(observer1)) + subscription2.setDisposable(self._parent.source2.subscribe(observer2)) + subscription3.setDisposable(self._parent.source3.subscribe(observer3)) + subscription4.setDisposable(self._parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!, self._values3.dequeue()!, self._values4.dequeue()!) + } +} + +final class Zip4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E) throws -> E) + -> Observable { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E)> { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class ZipSink5_ : ZipSink { + typealias R = O.E + typealias Parent = Zip5 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self._values1.isEmpty + case 1: return !self._values2.isEmpty + case 2: return !self._values3.isEmpty + case 3: return !self._values4.isEmpty + case 4: return !self._values5.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + + #if swift(>=4.2) + #if !compiler(>=5.0) + return false + #endif + #else + return false + #endif + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self._lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self._lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self._lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self._lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self._lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + + subscription1.setDisposable(self._parent.source1.subscribe(observer1)) + subscription2.setDisposable(self._parent.source2.subscribe(observer2)) + subscription3.setDisposable(self._parent.source3.subscribe(observer3)) + subscription4.setDisposable(self._parent.source4.subscribe(observer4)) + subscription5.setDisposable(self._parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!, self._values3.dequeue()!, self._values4.dequeue()!, self._values5.dequeue()!) + } +} + +final class Zip5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E) throws -> E) + -> Observable { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E)> { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class ZipSink6_ : ZipSink { + typealias R = O.E + typealias Parent = Zip6 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self._values1.isEmpty + case 1: return !self._values2.isEmpty + case 2: return !self._values3.isEmpty + case 3: return !self._values4.isEmpty + case 4: return !self._values5.isEmpty + case 5: return !self._values6.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + + #if swift(>=4.2) + #if !compiler(>=5.0) + return false + #endif + #else + return false + #endif + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self._lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self._lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self._lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self._lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self._lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self._lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + + subscription1.setDisposable(self._parent.source1.subscribe(observer1)) + subscription2.setDisposable(self._parent.source2.subscribe(observer2)) + subscription3.setDisposable(self._parent.source3.subscribe(observer3)) + subscription4.setDisposable(self._parent.source4.subscribe(observer4)) + subscription5.setDisposable(self._parent.source5.subscribe(observer5)) + subscription6.setDisposable(self._parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!, self._values3.dequeue()!, self._values4.dequeue()!, self._values5.dequeue()!, self._values6.dequeue()!) + } +} + +final class Zip6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E) throws -> E) + -> Observable { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E)> { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class ZipSink7_ : ZipSink { + typealias R = O.E + typealias Parent = Zip7 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + var _values7: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self._values1.isEmpty + case 1: return !self._values2.isEmpty + case 2: return !self._values3.isEmpty + case 3: return !self._values4.isEmpty + case 4: return !self._values5.isEmpty + case 5: return !self._values6.isEmpty + case 6: return !self._values7.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + + #if swift(>=4.2) + #if !compiler(>=5.0) + return false + #endif + #else + return false + #endif + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self._lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self._lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self._lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self._lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self._lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self._lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self._lock, parent: self, index: 6, setNextValue: { self._values7.enqueue($0) }, this: subscription7) + + subscription1.setDisposable(self._parent.source1.subscribe(observer1)) + subscription2.setDisposable(self._parent.source2.subscribe(observer2)) + subscription3.setDisposable(self._parent.source3.subscribe(observer3)) + subscription4.setDisposable(self._parent.source4.subscribe(observer4)) + subscription5.setDisposable(self._parent.source5.subscribe(observer5)) + subscription6.setDisposable(self._parent.source6.subscribe(observer6)) + subscription7.setDisposable(self._parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!, self._values3.dequeue()!, self._values4.dequeue()!, self._values5.dequeue()!, self._values6.dequeue()!, self._values7.dequeue()!) + } +} + +final class Zip7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E) throws -> E) + -> Observable { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where E == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.E, O2.E, O3.E, O4.E, O5.E, O6.E, O7.E, O8.E)> { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class ZipSink8_ : ZipSink { + typealias R = O.E + typealias Parent = Zip8 + + let _parent: Parent + + var _values1: Queue = Queue(capacity: 2) + var _values2: Queue = Queue(capacity: 2) + var _values3: Queue = Queue(capacity: 2) + var _values4: Queue = Queue(capacity: 2) + var _values5: Queue = Queue(capacity: 2) + var _values6: Queue = Queue(capacity: 2) + var _values7: Queue = Queue(capacity: 2) + var _values8: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: O, cancel: Cancelable) { + self._parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self._values1.isEmpty + case 1: return !self._values2.isEmpty + case 2: return !self._values3.isEmpty + case 3: return !self._values4.isEmpty + case 4: return !self._values5.isEmpty + case 5: return !self._values6.isEmpty + case 6: return !self._values7.isEmpty + case 7: return !self._values8.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + + #if swift(>=4.2) + #if !compiler(>=5.0) + return false + #endif + #else + return false + #endif + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self._lock, parent: self, index: 0, setNextValue: { self._values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self._lock, parent: self, index: 1, setNextValue: { self._values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self._lock, parent: self, index: 2, setNextValue: { self._values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self._lock, parent: self, index: 3, setNextValue: { self._values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self._lock, parent: self, index: 4, setNextValue: { self._values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self._lock, parent: self, index: 5, setNextValue: { self._values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self._lock, parent: self, index: 6, setNextValue: { self._values7.enqueue($0) }, this: subscription7) + let observer8 = ZipObserver(lock: self._lock, parent: self, index: 7, setNextValue: { self._values8.enqueue($0) }, this: subscription8) + + subscription1.setDisposable(self._parent.source1.subscribe(observer1)) + subscription2.setDisposable(self._parent.source2.subscribe(observer2)) + subscription3.setDisposable(self._parent.source3.subscribe(observer3)) + subscription4.setDisposable(self._parent.source4.subscribe(observer4)) + subscription5.setDisposable(self._parent.source5.subscribe(observer5)) + subscription6.setDisposable(self._parent.source6.subscribe(observer6)) + subscription7.setDisposable(self._parent.source7.subscribe(observer7)) + subscription8.setDisposable(self._parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> R { + return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!, self._values3.dequeue()!, self._values4.dequeue()!, self._values5.dequeue()!, self._values6.dequeue()!, self._values7.dequeue()!, self._values8.dequeue()!) + } +} + +final class Zip8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> R + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let _resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + self._resultSelector = resultSelector + } + + override func run(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { + let sink = ZipSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip.swift new file mode 100644 index 0000000..50edf84 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observables/Zip.swift @@ -0,0 +1,153 @@ +// +// Zip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ZipSinkProtocol : class +{ + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class ZipSink : Sink, ZipSinkProtocol { + typealias Element = O.E + + let _arity: Int + + let _lock = RecursiveLock() + + // state + private var _isDone: [Bool] + + init(arity: Int, observer: O, cancel: Cancelable) { + self._isDone = [Bool](repeating: false, count: arity) + self._arity = arity + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func hasElements(_ index: Int) -> Bool { + rxAbstractMethod() + } + + func next(_ index: Int) { + var hasValueAll = true + + for i in 0 ..< self._arity { + if !self.hasElements(i) { + hasValueAll = false + break + } + } + + if hasValueAll { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + else { + var allOthersDone = true + + let arity = self._isDone.count + for i in 0 ..< arity { + if i != index && !self._isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + self.forwardOn(.completed) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + self._isDone[index] = true + + var allDone = true + + for done in self._isDone where !done { + allDone = false + break + } + + if allDone { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class ZipObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias E = ElementType + typealias ValueSetter = (ElementType) -> Void + + private var _parent: ZipSinkProtocol? + + let _lock: RecursiveLock + + // state + private let _index: Int + private let _this: Disposable + private let _setNextValue: ValueSetter + + init(lock: RecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: @escaping ValueSetter, this: Disposable) { + self._lock = lock + self._parent = parent + self._index = index + self._this = this + self._setNextValue = setNextValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func _synchronized_on(_ event: Event) { + if self._parent != nil { + switch event { + case .next: + break + case .error: + self._this.dispose() + case .completed: + self._this.dispose() + } + } + + if let parent = self._parent { + switch event { + case .next(let value): + self._setNextValue(value) + parent.next(self._index) + case .error(let error): + parent.fail(error) + case .completed: + parent.done(self._index) + } + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObserverType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObserverType.swift new file mode 100644 index 0000000..908941f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/ObserverType.swift @@ -0,0 +1,40 @@ +// +// ObserverType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Supports push-style iteration over an observable sequence. +public protocol ObserverType { + /// The type of elements in sequence that observer can observe. + associatedtype E + + /// Notify observer about sequence event. + /// + /// - parameter event: Event that occurred. + func on(_ event: Event) +} + +/// Convenience API extensions to provide alternate next, error, completed events +extension ObserverType { + + /// Convenience method equivalent to `on(.next(element: E))` + /// + /// - parameter element: Next element to send to observer(s) + public func onNext(_ element: E) { + self.on(.next(element)) + } + + /// Convenience method equivalent to `on(.completed)` + public func onCompleted() { + self.on(.completed) + } + + /// Convenience method equivalent to `on(.error(Swift.Error))` + /// - parameter error: Swift.Error to send to observer(s) + public func onError(_ error: Swift.Error) { + self.on(.error(error)) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift new file mode 100644 index 0000000..765cf11 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift @@ -0,0 +1,32 @@ +// +// AnonymousObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AnonymousObserver : ObserverBase { + typealias Element = ElementType + + typealias EventHandler = (Event) -> Void + + private let _eventHandler : EventHandler + + init(_ eventHandler: @escaping EventHandler) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self._eventHandler = eventHandler + } + + override func onCore(_ event: Event) { + return self._eventHandler(event) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift new file mode 100644 index 0000000..65d05ec --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift @@ -0,0 +1,34 @@ +// +// ObserverBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class ObserverBase : Disposable, ObserverType { + typealias E = ElementType + + private let _isStopped = AtomicInt(0) + + func on(_ event: Event) { + switch event { + case .next: + if load(self._isStopped) == 0 { + self.onCore(event) + } + case .error, .completed: + if fetchOr(self._isStopped, 1) == 0 { + self.onCore(event) + } + } + } + + func onCore(_ event: Event) { + rxAbstractMethod() + } + + func dispose() { + fetchOr(self._isStopped, 1) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift new file mode 100644 index 0000000..e75a380 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift @@ -0,0 +1,151 @@ +// +// TailRecursiveSink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum TailRecursiveSinkCommand { + case moveNext + case dispose +} + +#if DEBUG || TRACE_RESOURCES + public var maxTailRecursiveSinkStackSize = 0 +#endif + +/// This class is usually used with `Generator` version of the operators. +class TailRecursiveSink + : Sink + , InvocableWithValueType where S.Iterator.Element: ObservableConvertibleType, S.Iterator.Element.E == O.E { + typealias Value = TailRecursiveSinkCommand + typealias E = O.E + typealias SequenceGenerator = (generator: S.Iterator, remaining: IntMax?) + + var _generators: [SequenceGenerator] = [] + var _isDisposed = false + var _subscription = SerialDisposable() + + // this is thread safe object + var _gate = AsyncLock>>() + + override init(observer: O, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ sources: SequenceGenerator) -> Disposable { + self._generators.append(sources) + + self.schedule(.moveNext) + + return self._subscription + } + + func invoke(_ command: TailRecursiveSinkCommand) { + switch command { + case .dispose: + self.disposeCommand() + case .moveNext: + self.moveNextCommand() + } + } + + // simple implementation for now + func schedule(_ command: TailRecursiveSinkCommand) { + self._gate.invoke(InvocableScheduledItem(invocable: self, state: command)) + } + + func done() { + self.forwardOn(.completed) + self.dispose() + } + + func extract(_ observable: Observable) -> SequenceGenerator? { + rxAbstractMethod() + } + + // should be done on gate locked + + private func moveNextCommand() { + var next: Observable? + + repeat { + guard let (g, left) = self._generators.last else { + break + } + + if self._isDisposed { + return + } + + self._generators.removeLast() + + var e = g + + guard let nextCandidate = e.next()?.asObservable() else { + continue + } + + // `left` is a hint of how many elements are left in generator. + // In case this is the last element, then there is no need to push + // that generator on stack. + // + // This is an optimization used to make sure in tail recursive case + // there is no memory leak in case this operator is used to generate non terminating + // sequence. + + if let knownOriginalLeft = left { + // `- 1` because generator.next() has just been called + if knownOriginalLeft - 1 >= 1 { + self._generators.append((e, knownOriginalLeft - 1)) + } + } + else { + self._generators.append((e, nil)) + } + + let nextGenerator = self.extract(nextCandidate) + + if let nextGenerator = nextGenerator { + self._generators.append(nextGenerator) + #if DEBUG || TRACE_RESOURCES + if maxTailRecursiveSinkStackSize < self._generators.count { + maxTailRecursiveSinkStackSize = self._generators.count + } + #endif + } + else { + next = nextCandidate + } + } while next == nil + + guard let existingNext = next else { + self.done() + return + } + + let disposable = SingleAssignmentDisposable() + self._subscription.disposable = disposable + disposable.setDisposable(self.subscribeToNext(existingNext)) + } + + func subscribeToNext(_ source: Observable) -> Disposable { + rxAbstractMethod() + } + + func disposeCommand() { + self._isDisposed = true + self._generators.removeAll(keepingCapacity: false) + } + + override func dispose() { + super.dispose() + + self._subscription.dispose() + self._gate.dispose() + + self.schedule(.dispose) + } +} + diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Reactive.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Reactive.swift new file mode 100644 index 0000000..b873996 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Reactive.swift @@ -0,0 +1,74 @@ +// +// Reactive.swift +// RxSwift +// +// Created by Yury Korolev on 5/2/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/** + Use `Reactive` proxy as customization point for constrained protocol extensions. + + General pattern would be: + + // 1. Extend Reactive protocol with constrain on Base + // Read as: Reactive Extension where Base is a SomeType + extension Reactive where Base: SomeType { + // 2. Put any specific reactive extension for SomeType here + } + + With this approach we can have more specialized methods and properties using + `Base` and not just specialized on common base type. + + */ + +public struct Reactive { + /// Base object to extend. + public let base: Base + + /// Creates extensions with base object. + /// + /// - parameter base: Base object. + public init(_ base: Base) { + self.base = base + } +} + +/// A type that has reactive extensions. +public protocol ReactiveCompatible { + /// Extended type + associatedtype CompatibleType + + /// Reactive extensions. + static var rx: Reactive.Type { get set } + + /// Reactive extensions. + var rx: Reactive { get set } +} + +extension ReactiveCompatible { + /// Reactive extensions. + public static var rx: Reactive.Type { + get { + return Reactive.self + } + set { + // this enables using Reactive to "mutate" base type + } + } + + /// Reactive extensions. + public var rx: Reactive { + get { + return Reactive(self) + } + set { + // this enables using Reactive to "mutate" base object + } + } +} + +import class Foundation.NSObject + +/// Extend NSObject with `rx` proxy. +extension NSObject: ReactiveCompatible { } diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Rx.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Rx.swift new file mode 100644 index 0000000..a547a8f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Rx.swift @@ -0,0 +1,141 @@ +// +// Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if TRACE_RESOURCES + fileprivate let resourceCount = AtomicInt(0) + + /// Resource utilization information + public struct Resources { + /// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development. + public static var total: Int32 { + return load(resourceCount) + } + + /// Increments `Resources.total` resource count. + /// + /// - returns: New resource count + public static func incrementTotal() -> Int32 { + return increment(resourceCount) + } + + /// Decrements `Resources.total` resource count + /// + /// - returns: New resource count + public static func decrementTotal() -> Int32 { + return decrement(resourceCount) + } + } +#endif + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +func rxAbstractMethod(file: StaticString = #file, line: UInt = #line) -> Swift.Never { + rxFatalError("Abstract method", file: file, line: line) +} + +func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never { + fatalError(lastMessage(), file: file, line: line) +} + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} + +func incrementChecked(_ i: inout Int) throws -> Int { + if i == Int.max { + throw RxError.overflow + } + defer { i += 1 } + return i +} + +func decrementChecked(_ i: inout Int) throws -> Int { + if i == Int.min { + throw RxError.overflow + } + defer { i -= 1 } + return i +} + +#if DEBUG + import class Foundation.Thread + final class SynchronizationTracker { + private let _lock = RecursiveLock() + + public enum SynchronizationErrorMessages: String { + case variable = "Two different threads are trying to assign the same `Variable.value` unsynchronized.\n This is undefined behavior because the end result (variable value) is nondeterministic and depends on the \n operating system thread scheduler. This will cause random behavior of your program.\n" + case `default` = "Two different unsynchronized threads are trying to send some event simultaneously.\n This is undefined behavior because the ordering of the effects caused by these events is nondeterministic and depends on the \n operating system thread scheduler. This will result in a random behavior of your program.\n" + } + + private var _threads = [UnsafeMutableRawPointer: Int]() + + private func synchronizationError(_ message: String) { + #if FATAL_SYNCHRONIZATION + rxFatalError(message) + #else + print(message) + #endif + } + + func register(synchronizationErrorMessage: SynchronizationErrorMessages) { + self._lock.lock(); defer { self._lock.unlock() } + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + let count = (self._threads[pointer] ?? 0) + 1 + + if count > 1 { + self.synchronizationError( + "⚠️ Reentrancy anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: This could mean that there is some kind of unexpected cyclic dependency in your code,\n" + + " or that the system is not behaving in the expected way.\n" + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observeOn(MainScheduler.asyncInstance)`\n" + + " or by enqueuing sequence events in some other way.\n" + ) + } + + self._threads[pointer] = count + + if self._threads.count > 1 { + self.synchronizationError( + "⚠️ Synchronization anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: " + synchronizationErrorMessage.rawValue + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observeOn(MainScheduler.asyncInstance)`\n" + + " or by synchronizing sequence events in some other way.\n" + ) + } + } + + func unregister() { + self._lock.lock(); defer { self._lock.unlock() } + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + self._threads[pointer] = (self._threads[pointer] ?? 1) - 1 + if self._threads[pointer] == 0 { + self._threads[pointer] = nil + } + } + } + +#endif + +/// RxSwift global hooks +public enum Hooks { + + // Should capture call stack + public static var recordCallStackOnError: Bool = false + +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/RxMutableBox.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/RxMutableBox.swift new file mode 100644 index 0000000..7f3c333 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/RxMutableBox.swift @@ -0,0 +1,27 @@ +// +// RxMutableBox.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Creates mutable reference wrapper for any type. +final class RxMutableBox : CustomDebugStringConvertible { + /// Wrapped value + var value : T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} + +extension RxMutableBox { + /// - returns: Box description. + var debugDescription: String { + return "MutatingBox(\(self.value))" + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/SchedulerType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/SchedulerType.swift new file mode 100644 index 0000000..e09c499 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/SchedulerType.swift @@ -0,0 +1,71 @@ +// +// SchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.TimeInterval +import struct Foundation.Date + +// Type that represents time interval in the context of RxSwift. +public typealias RxTimeInterval = TimeInterval + +/// Type that represents absolute time in the context of RxSwift. +public typealias RxTime = Date + +/// Represents an object that schedules units of work. +public protocol SchedulerType: ImmediateSchedulerType { + + /// - returns: Current time. + var now : RxTime { + get + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable +} + +extension SchedulerType { + + /** + Periodic task will be emulated using recursive scheduling. + + - parameter state: Initial state passed to the action upon the first iteration. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - returns: The disposable object used to cancel the scheduled recurring action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let schedule = SchedulePeriodicRecursive(scheduler: self, startAfter: startAfter, period: period, action: action, state: state) + + return schedule.start() + } + + func scheduleRecursive(_ state: State, dueTime: RxTimeInterval, action: @escaping (State, AnyRecursiveScheduler) -> Void) -> Disposable { + let scheduler = AnyRecursiveScheduler(scheduler: self, action: action) + + scheduler.schedule(state, dueTime: dueTime) + + return Disposables.create(with: scheduler.dispose) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift new file mode 100644 index 0000000..ed2efbb --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -0,0 +1,84 @@ +// +// ConcurrentDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date +import struct Foundation.TimeInterval +import Dispatch + +/// Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems. +/// +/// This scheduler is suitable when some work needs to be performed in background. +public class ConcurrentDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + public var now : Date { + return Date() + } + + let configuration: DispatchQueueConfiguration + + /// Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`. + /// + /// - parameter queue: Target dispatch queue. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + public init(queue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: queue, leeway: leeway) + } + + /// Convenience init for scheduler that wraps one of the global concurrent dispatch queues. + /// + /// - parameter qos: Target global dispatch queue, by quality of service class. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + @available(iOS 8, OSX 10.10, *) + public convenience init(qos: DispatchQoS, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue( + label: "rxswift.queue.\(qos)", + qos: qos, + attributes: [DispatchQueue.Attributes.concurrent], + target: nil), + leeway: leeway + ) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift new file mode 100644 index 0000000..0d65b6c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift @@ -0,0 +1,88 @@ +// +// ConcurrentMainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date +import struct Foundation.TimeInterval +import Dispatch + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is optimized for `subscribeOn` operator. If you want to observe observable sequence elements on main thread using `observeOn` operator, +`MainScheduler` is more suitable for that purpose. +*/ +public final class ConcurrentMainScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + private let _mainScheduler: MainScheduler + private let _mainQueue: DispatchQueue + + /// - returns: Current time. + public var now: Date { + return self._mainScheduler.now as Date + } + + private init(mainScheduler: MainScheduler) { + self._mainQueue = DispatchQueue.main + self._mainScheduler = mainScheduler + } + + /// Singleton instance of `ConcurrentMainScheduler` + public static let instance = ConcurrentMainScheduler(mainScheduler: MainScheduler.instance) + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if DispatchQueue.isMain { + return action(state) + } + + let cancel = SingleAssignmentDisposable() + + self._mainQueue.async { + if cancel.isDisposed { + return + } + + cancel.setDisposable(action(state)) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + return self._mainScheduler.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + return self._mainScheduler.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift new file mode 100644 index 0000000..c7f6b17 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift @@ -0,0 +1,144 @@ +// +// CurrentThreadScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import class Foundation.NSObject +import protocol Foundation.NSCopying +import class Foundation.Thread +import Dispatch + +#if os(Linux) + import struct Foundation.pthread_key_t + import func Foundation.pthread_setspecific + import func Foundation.pthread_getspecific + import func Foundation.pthread_key_create + + fileprivate enum CurrentThreadSchedulerQueueKey { + fileprivate static let instance = "RxSwift.CurrentThreadScheduler.Queue" + } +#else + private class CurrentThreadSchedulerQueueKey: NSObject, NSCopying { + static let instance = CurrentThreadSchedulerQueueKey() + private override init() { + super.init() + } + + override var hash: Int { + return 0 + } + + public func copy(with zone: NSZone? = nil) -> Any { + return self + } + } +#endif + +/// Represents an object that schedules units of work on the current thread. +/// +/// This is the default scheduler for operators that generate elements. +/// +/// This scheduler is also sometimes called `trampoline scheduler`. +public class CurrentThreadScheduler : ImmediateSchedulerType { + typealias ScheduleQueue = RxMutableBox> + + /// The singleton instance of the current thread scheduler. + public static let instance = CurrentThreadScheduler() + + private static var isScheduleRequiredKey: pthread_key_t = { () -> pthread_key_t in + let key = UnsafeMutablePointer.allocate(capacity: 1) + defer { +#if swift(>=4.1) + key.deallocate() +#else + key.deallocate(capacity: 1) +#endif + } + + guard pthread_key_create(key, nil) == 0 else { + rxFatalError("isScheduleRequired key creation failed") + } + + return key.pointee + }() + + private static var scheduleInProgressSentinel: UnsafeRawPointer = { () -> UnsafeRawPointer in + return UnsafeRawPointer(UnsafeMutablePointer.allocate(capacity: 1)) + }() + + static var queue : ScheduleQueue? { + get { + return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKey.instance) + } + set { + Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKey.instance) + } + } + + /// Gets a value that indicates whether the caller must call a `schedule` method. + public static fileprivate(set) var isScheduleRequired: Bool { + get { + return pthread_getspecific(CurrentThreadScheduler.isScheduleRequiredKey) == nil + } + set(isScheduleRequired) { + if pthread_setspecific(CurrentThreadScheduler.isScheduleRequiredKey, isScheduleRequired ? nil : scheduleInProgressSentinel) != 0 { + rxFatalError("pthread_setspecific failed") + } + } + } + + /** + Schedules an action to be executed as soon as possible on current thread. + + If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be + automatically installed and uninstalled after all work is performed. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if CurrentThreadScheduler.isScheduleRequired { + CurrentThreadScheduler.isScheduleRequired = false + + let disposable = action(state) + + defer { + CurrentThreadScheduler.isScheduleRequired = true + CurrentThreadScheduler.queue = nil + } + + guard let queue = CurrentThreadScheduler.queue else { + return disposable + } + + while let latest = queue.value.dequeue() { + if latest.isDisposed { + continue + } + latest.invoke() + } + + return disposable + } + + let existingQueue = CurrentThreadScheduler.queue + + let queue: RxMutableBox> + if let existingQueue = existingQueue { + queue = existingQueue + } + else { + queue = RxMutableBox(Queue(capacity: 1)) + CurrentThreadScheduler.queue = queue + } + + let scheduledItem = ScheduledItem(action: action, state: state) + queue.value.enqueue(scheduledItem) + + return scheduledItem + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift new file mode 100644 index 0000000..11af238 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift @@ -0,0 +1,22 @@ +// +// HistoricalScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date + +/// Provides a virtual time scheduler that uses `Date` for absolute time and `NSTimeInterval` for relative time. +public class HistoricalScheduler : VirtualTimeScheduler { + + /** + Creates a new historical scheduler with initial clock value. + + - parameter initialClock: Initial value for virtual clock. + */ + public init(initialClock: RxTime = Date(timeIntervalSince1970: 0)) { + super.init(initialClock: initialClock, converter: HistoricalSchedulerTimeConverter()) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift new file mode 100644 index 0000000..930ca37 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift @@ -0,0 +1,67 @@ +// +// HistoricalSchedulerTimeConverter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.Date + +/// Converts historical virtual time into real time. +/// +/// Since historical virtual time is also measured in `Date`, this converter is identity function. +public struct HistoricalSchedulerTimeConverter : VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + public typealias VirtualTimeUnit = RxTime + + /// Virtual time unit used to represent differences of virtual times. + public typealias VirtualTimeIntervalUnit = RxTimeInterval + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime { + return virtualTime + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit { + return time + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval { + return virtualTimeInterval + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTimeInterval(_ timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit { + return timeInterval + } + + /** + Offsets `Date` by time interval. + + - parameter time: Time. + - parameter timeInterval: Time interval offset. + - returns: Time offsetted by time interval. + */ + public func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit { + return time.addingTimeInterval(offset) + } + + /// Compares two `Date`s. + public func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison { + switch lhs.compare(rhs as Date) { + case .orderedAscending: + return .lessThan + case .orderedSame: + return .equal + case .orderedDescending: + return .greaterThan + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift new file mode 100644 index 0000000..792a0be --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift @@ -0,0 +1,104 @@ +// +// DispatchQueueConfiguration.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/23/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import struct Foundation.TimeInterval + +struct DispatchQueueConfiguration { + let queue: DispatchQueue + let leeway: DispatchTimeInterval +} + +private func dispatchInterval(_ interval: Foundation.TimeInterval) -> DispatchTimeInterval { + precondition(interval >= 0.0) + // TODO: Replace 1000 with something that actually works + // NSEC_PER_MSEC returns 1000000 + return DispatchTimeInterval.milliseconds(Int(interval * 1000.0)) +} + +extension DispatchQueueConfiguration { + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + self.queue.async { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + return cancel + } + + func scheduleRelative(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let deadline = DispatchTime.now() + dispatchInterval(dueTime) + + let compositeDisposable = CompositeDisposable() + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: deadline, leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceputal change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if compositeDisposable.isDisposed { + return + } + _ = compositeDisposable.insert(action(state)) + cancelTimer.dispose() + }) + timer.resume() + + _ = compositeDisposable.insert(cancelTimer) + + return compositeDisposable + } + + func schedulePeriodic(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let initial = DispatchTime.now() + dispatchInterval(startAfter) + + var timerState = state + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: initial, repeating: dispatchInterval(period), leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceputal change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if cancelTimer.isDisposed { + return + } + timerState = action(timerState) + }) + timer.resume() + + return cancelTimer + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift new file mode 100644 index 0000000..f31469e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift @@ -0,0 +1,22 @@ +// +// InvocableScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct InvocableScheduledItem : InvocableType { + + let _invocable: I + let _state: I.Value + + init(invocable: I, state: I.Value) { + self._invocable = invocable + self._state = state + } + + func invoke() { + self._invocable.invoke(self._state) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift new file mode 100644 index 0000000..0dba433 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift @@ -0,0 +1,17 @@ +// +// InvocableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol InvocableType { + func invoke() +} + +protocol InvocableWithValueType { + associatedtype Value + + func invoke(_ value: Value) +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift new file mode 100644 index 0000000..6e7a0c1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift @@ -0,0 +1,35 @@ +// +// ScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct ScheduledItem + : ScheduledItemType + , InvocableType { + typealias Action = (T) -> Disposable + + private let _action: Action + private let _state: T + + private let _disposable = SingleAssignmentDisposable() + + var isDisposed: Bool { + return self._disposable.isDisposed + } + + init(action: @escaping Action, state: T) { + self._action = action + self._state = state + } + + func invoke() { + self._disposable.setDisposable(self._action(self._state)) + } + + func dispose() { + self._disposable.dispose() + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift new file mode 100644 index 0000000..d2b16ca --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift @@ -0,0 +1,13 @@ +// +// ScheduledItemType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ScheduledItemType + : Cancelable + , InvocableType { + func invoke() +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift new file mode 100644 index 0000000..8fb0907 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift @@ -0,0 +1,80 @@ +// +// MainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +#if !os(Linux) + import Foundation +#endif + +/** +Abstracts work that needs to be performed on `DispatchQueue.main`. In case `schedule` methods are called from `DispatchQueue.main`, it will perform action immediately without scheduling. + +This scheduler is usually used to perform UI work. + +Main scheduler is a specialization of `SerialDispatchQueueScheduler`. + +This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn` +operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose. +*/ +public final class MainScheduler : SerialDispatchQueueScheduler { + + private let _mainQueue: DispatchQueue + + let numberEnqueued = AtomicInt(0) + + /// Initializes new instance of `MainScheduler`. + public init() { + self._mainQueue = DispatchQueue.main + super.init(serialQueue: self._mainQueue) + } + + /// Singleton instance of `MainScheduler` + public static let instance = MainScheduler() + + /// Singleton instance of `MainScheduler` that always schedules work asynchronously + /// and doesn't perform optimizations for calls scheduled from main queue. + public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: DispatchQueue.main) + + /// In case this method is called on a background thread it will throw an exception. + public class func ensureExecutingOnScheduler(errorMessage: String? = nil) { + if !DispatchQueue.isMain { + rxFatalError(errorMessage ?? "Executing on background thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.") + } + } + + /// In case this method is running on a background thread it will throw an exception. + public class func ensureRunningOnMainThread(errorMessage: String? = nil) { + #if !os(Linux) // isMainThread is not implemented in Linux Foundation + guard Thread.isMainThread else { + rxFatalError(errorMessage ?? "Running on background thread.") + } + #endif + } + + override func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let previousNumberEnqueued = increment(self.numberEnqueued) + + if DispatchQueue.isMain && previousNumberEnqueued == 0 { + let disposable = action(state) + decrement(self.numberEnqueued) + return disposable + } + + let cancel = SingleAssignmentDisposable() + + self._mainQueue.async { + if !cancel.isDisposed { + _ = action(state) + } + + decrement(self.numberEnqueued) + } + + return cancel + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift new file mode 100644 index 0000000..81ba59f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift @@ -0,0 +1,56 @@ +// +// OperationQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import class Foundation.Operation +import class Foundation.OperationQueue +import class Foundation.BlockOperation +import Dispatch + +/// Abstracts the work that needs to be performed on a specific `NSOperationQueue`. +/// +/// This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. +public class OperationQueueScheduler: ImmediateSchedulerType { + public let operationQueue: OperationQueue + public let queuePriority: Operation.QueuePriority + + /// Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. + /// + /// - parameter operationQueue: Operation queue targeted to perform work on. + /// - parameter queuePriority: Queue priority which will be assigned to new operations. + public init(operationQueue: OperationQueue, queuePriority: Operation.QueuePriority = .normal) { + self.operationQueue = operationQueue + self.queuePriority = queuePriority + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + let operation = BlockOperation { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + operation.queuePriority = self.queuePriority + + self.operationQueue.addOperation(operation) + + return cancel + } + +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift new file mode 100644 index 0000000..9e9b4ff --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift @@ -0,0 +1,220 @@ +// +// RecursiveScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private enum ScheduleState { + case initial + case added(CompositeDisposable.DisposeKey) + case done +} + +/// Type erased recursive scheduler. +final class AnyRecursiveScheduler { + + typealias Action = (State, AnyRecursiveScheduler) -> Void + + private let _lock = RecursiveLock() + + // state + private let _group = CompositeDisposable() + + private var _scheduler: SchedulerType + private var _action: Action? + + init(scheduler: SchedulerType, action: @escaping Action) { + self._action = action + self._scheduler = scheduler + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the recursive action. + */ + func schedule(_ state: State, dueTime: RxTimeInterval) { + var scheduleState: ScheduleState = .initial + + let d = self._scheduler.scheduleRelative(state, dueTime: dueTime) { state -> Disposable in + // best effort + if self._group.isDisposed { + return Disposables.create() + } + + let action = self._lock.calculateLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self._group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self._action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self._lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self._group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self._scheduler.schedule(state) { state -> Disposable in + // best effort + if self._group.isDisposed { + return Disposables.create() + } + + let action = self._lock.calculateLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self._group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self._action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self._lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self._group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self._lock.performLocked { + self._action = nil + } + self._group.dispose() + } +} + +/// Type erased recursive scheduler. +final class RecursiveImmediateScheduler { + typealias Action = (_ state: State, _ recurse: (State) -> Void) -> Void + + private var _lock = SpinLock() + private let _group = CompositeDisposable() + + private var _action: Action? + private let _scheduler: ImmediateSchedulerType + + init(action: @escaping Action, scheduler: ImmediateSchedulerType) { + self._action = action + self._scheduler = scheduler + } + + // immediate scheduling + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self._scheduler.schedule(state) { state -> Disposable in + // best effort + if self._group.isDisposed { + return Disposables.create() + } + + let action = self._lock.calculateLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self._group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self._action + } + + if let action = action { + action(state, self.schedule) + } + + return Disposables.create() + } + + self._lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self._group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self._lock.performLocked { + self._action = nil + } + self._group.dispose() + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift new file mode 100644 index 0000000..5b7b840 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift @@ -0,0 +1,61 @@ +// +// SchedulerServices+Emulation.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum SchedulePeriodicRecursiveCommand { + case tick + case dispatchStart +} + +final class SchedulePeriodicRecursive { + typealias RecursiveAction = (State) -> State + typealias RecursiveScheduler = AnyRecursiveScheduler + + private let _scheduler: SchedulerType + private let _startAfter: RxTimeInterval + private let _period: RxTimeInterval + private let _action: RecursiveAction + + private var _state: State + private let _pendingTickCount = AtomicInt(0) + + init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping RecursiveAction, state: State) { + self._scheduler = scheduler + self._startAfter = startAfter + self._period = period + self._action = action + self._state = state + } + + func start() -> Disposable { + return self._scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.tick, dueTime: self._startAfter, action: self.tick) + } + + func tick(_ command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) { + // Tries to emulate periodic scheduling as best as possible. + // The problem that could arise is if handling periodic ticks take too long, or + // tick interval is short. + switch command { + case .tick: + scheduler.schedule(.tick, dueTime: self._period) + + // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediately. + // Else work will be scheduled after previous enqueued work completes. + if increment(self._pendingTickCount) == 0 { + self.tick(.dispatchStart, scheduler: scheduler) + } + + case .dispatchStart: + self._state = self._action(self._state) + // Start work and schedule check is this last batch of work + if decrement(self._pendingTickCount) > 1 { + // This gives priority to scheduler emulation, it's not perfect, but helps + scheduler.schedule(SchedulePeriodicRecursiveCommand.dispatchStart) + } + } + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift new file mode 100644 index 0000000..8adb57b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -0,0 +1,132 @@ +// +// SerialDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import struct Foundation.TimeInterval +import struct Foundation.Date +import Dispatch + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure +that even if concurrent dispatch queue is passed, it's transformed into a serial one. + +It is extremely important that this scheduler is serial, because +certain operator perform optimizations that rely on that property. + +Because there is no way of detecting is passed dispatch queue serial or +concurrent, for every queue that is being passed, worst case (concurrent) +will be assumed, and internal serial proxy dispatch queue will be created. + +This scheduler can also be used with internal serial queue alone. + +In case some customization need to be made on it before usage, +internal serial queue can be customized using `serialQueueConfiguration` +callback. +*/ +public class SerialDispatchQueueScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + /// - returns: Current time. + public var now : Date { + return Date() + } + + let configuration: DispatchQueueConfiguration + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps `serialQueue`. + + - parameter serialQueue: Target dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + init(serialQueue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. + + Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. + + - parameter internalSerialQueueName: Name of internal serial dispatch queue. + - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + let queue = DispatchQueue(label: internalSerialQueueName, attributes: []) + serialQueueConfiguration?(queue) + self.init(serialQueue: queue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. + + - parameter queue: Possibly concurrent dispatch queue used to perform work. + - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + // Swift 3.0 IUO + let serialQueue = DispatchQueue(label: internalSerialQueueName, + attributes: [], + target: queue) + self.init(serialQueue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps on of the global concurrent dispatch queues. + + - parameter qos: Identifier for global dispatch queue with specified quality of service class. + - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + @available(iOS 8, OSX 10.10, *) + public convenience init(qos: DispatchQoS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue.global(qos: qos.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.scheduleInternal(state, action: action) + } + + func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift new file mode 100644 index 0000000..a17475a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift @@ -0,0 +1,95 @@ +// +// VirtualTimeConverterType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Parametrization for virtual time used by `VirtualTimeScheduler`s. +public protocol VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + associatedtype VirtualTimeUnit + + /// Virtual time unit used to represent differences of virtual times. + associatedtype VirtualTimeIntervalUnit + + /** + Converts virtual time to real time. + + - parameter virtualTime: Virtual time to convert to `Date`. + - returns: `Date` corresponding to virtual time. + */ + func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime + + /** + Converts real time to virtual time. + + - parameter time: `Date` to convert to virtual time. + - returns: Virtual time corresponding to `Date`. + */ + func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. + - returns: `NSTimeInterval` corresponding to virtual time interval. + */ + func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval + + /** + Converts from `NSTimeInterval` to virtual time interval. + + - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. + - returns: Virtual time interval corresponding to time interval. + */ + func convertToVirtualTimeInterval(_ timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit + + /** + Offsets virtual time by virtual time interval. + + - parameter time: Virtual time. + - parameter offset: Virtual time interval. + - returns: Time corresponding to time offsetted by virtual time interval. + */ + func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit + + /** + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. + */ + func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison +} + +/** + Virtual time comparison result. + + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. +*/ +public enum VirtualTimeComparison { + /// lhs < rhs. + case lessThan + /// lhs == rhs. + case equal + /// lhs > rhs. + case greaterThan +} + +extension VirtualTimeComparison { + /// lhs < rhs. + var lessThen: Bool { + return self == .lessThan + } + + /// lhs > rhs + var greaterThan: Bool { + return self == .greaterThan + } + + /// lhs == rhs + var equal: Bool { + return self == .equal + } +} diff --git a/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift new file mode 100644 index 0000000..037df95 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift @@ -0,0 +1,269 @@ +// +// VirtualTimeScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for virtual time schedulers using a priority queue for scheduled items. +open class VirtualTimeScheduler + : SchedulerType { + + public typealias VirtualTime = Converter.VirtualTimeUnit + public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit + + private var _running : Bool + + private var _clock: VirtualTime + + fileprivate var _schedulerQueue : PriorityQueue> + private var _converter: Converter + + private var _nextId = 0 + + /// - returns: Current time. + public var now: RxTime { + return self._converter.convertFromVirtualTime(self.clock) + } + + /// - returns: Scheduler's absolute time clock value. + public var clock: VirtualTime { + return self._clock + } + + /// Creates a new virtual time scheduler. + /// + /// - parameter initialClock: Initial value for the clock. + public init(initialClock: VirtualTime, converter: Converter) { + self._clock = initialClock + self._running = false + self._converter = converter + self._schedulerQueue = PriorityQueue(hasHigherPriority: { + switch converter.compareVirtualTime($0.time, $1.time) { + case .lessThan: + return true + case .equal: + return $0.id < $1.id + case .greaterThan: + return false + } + }, isEqual: { $0 === $1 }) + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.scheduleRelative(state, dueTime: 0.0) { a in + return action(a) + } + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.now.addingTimeInterval(dueTime) + let absoluteTime = self._converter.convertToVirtualTime(time) + let adjustedTime = self.adjustScheduledTime(absoluteTime) + return self.scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) + } + + /** + Schedules an action to be executed after relative time has passed. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelativeVirtual(_ state: StateType, dueTime: VirtualTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self._converter.offsetVirtualTime(self.clock, offset: dueTime) + return self.scheduleAbsoluteVirtual(state, time: time, action: action) + } + + /** + Schedules an action to be executed at absolute virtual time. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleAbsoluteVirtual(_ state: StateType, time: Converter.VirtualTimeUnit, action: @escaping (StateType) -> Disposable) -> Disposable { + MainScheduler.ensureExecutingOnScheduler() + + let compositeDisposable = CompositeDisposable() + + let item = VirtualSchedulerItem(action: { + let dispose = action(state) + return dispose + }, time: time, id: self._nextId) + + self._nextId += 1 + + self._schedulerQueue.enqueue(item) + + _ = compositeDisposable.insert(item) + + return compositeDisposable + } + + /// Adjusts time of scheduling before adding item to schedule queue. + open func adjustScheduledTime(_ time: Converter.VirtualTimeUnit) -> Converter.VirtualTimeUnit { + return time + } + + /// Starts the virtual time scheduler. + public func start() { + MainScheduler.ensureExecutingOnScheduler() + + if self._running { + return + } + + self._running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self._converter.compareVirtualTime(next.time, self.clock).greaterThan { + self._clock = next.time + } + + next.invoke() + self._schedulerQueue.remove(next) + } while self._running + + self._running = false + } + + func findNext() -> VirtualSchedulerItem? { + while let front = self._schedulerQueue.peek() { + if front.isDisposed { + self._schedulerQueue.remove(front) + continue + } + + return front + } + + return nil + } + + /// Advances the scheduler's clock to the specified time, running all work till that point. + /// + /// - parameter virtualTime: Absolute time to advance the scheduler's clock to. + public func advanceTo(_ virtualTime: VirtualTime) { + MainScheduler.ensureExecutingOnScheduler() + + if self._running { + fatalError("Scheduler is already running") + } + + self._running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self._converter.compareVirtualTime(next.time, virtualTime).greaterThan { + break + } + + if self._converter.compareVirtualTime(next.time, self.clock).greaterThan { + self._clock = next.time + } + + next.invoke() + self._schedulerQueue.remove(next) + } while self._running + + self._clock = virtualTime + self._running = false + } + + /// Advances the scheduler's clock by the specified relative time. + public func sleep(_ virtualInterval: VirtualTimeInterval) { + MainScheduler.ensureExecutingOnScheduler() + + let sleepTo = self._converter.offsetVirtualTime(self.clock, offset: virtualInterval) + if self._converter.compareVirtualTime(sleepTo, self.clock).lessThen { + fatalError("Can't sleep to past.") + } + + self._clock = sleepTo + } + + /// Stops the virtual time scheduler. + public func stop() { + MainScheduler.ensureExecutingOnScheduler() + + self._running = false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// MARK: description + +extension VirtualTimeScheduler: CustomDebugStringConvertible { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + return self._schedulerQueue.debugDescription + } +} + +final class VirtualSchedulerItem

+ +

+ + +[![Build Status](http://img.shields.io/travis/SDWebImage/SDWebImage/master.svg?style=flat)](https://travis-ci.org/SDWebImage/SDWebImage) +[![Pod Version](http://img.shields.io/cocoapods/v/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) +[![Pod Platform](http://img.shields.io/cocoapods/p/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/) +[![Pod License](http://img.shields.io/cocoapods/l/SDWebImage.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0.html) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg)](https://github.com/SDWebImage/SDWebImage) +[![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen.svg)](https://swift.org/package-manager/) +[![Mac Catalyst compatible](https://img.shields.io/badge/Catalyst-compatible-brightgreen.svg)](https://developer.apple.com/documentation/xcode/creating_a_mac_version_of_your_ipad_app/) +[![codecov](https://codecov.io/gh/SDWebImage/SDWebImage/branch/master/graph/badge.svg)](https://codecov.io/gh/SDWebImage/SDWebImage) + +This library provides an async image downloader with cache support. For convenience, we added categories for UI elements like `UIImageView`, `UIButton`, `MKAnnotationView`. + +## Features + +- [x] Categories for `UIImageView`, `UIButton`, `MKAnnotationView` adding web image and cache management +- [x] An asynchronous image downloader +- [x] An asynchronous memory + disk image caching with automatic cache expiration handling +- [x] A background image decompression to avoid frame rate drop +- [x] [Progressive image loading](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#progressive-animation) (including animated image, like GIF showing in Web browser) +- [x] [Thumbnail image decoding](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#thumbnail-decoding-550) to save CPU && Memory for large images +- [x] [Extendable image coder](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#custom-coder-420) to support massive image format, like WebP +- [x] [Full-stack solution for animated images](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#animated-image-50) which keep a balance between CPU && Memory +- [x] [Customizable and composable transformations](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#transformer-50) can be applied to the images right after download +- [x] [Customizable and multiple caches system](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#custom-cache-50) +- [x] [Customizable and multiple loaders system](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#custom-loader-50) to expand the capabilities, like [Photos Library](https://github.com/SDWebImage/SDWebImagePhotosPlugin) +- [x] [Image loading indicators](https://github.com/SDWebImage/SDWebImage/wiki/How-to-use#use-view-indicator-50) +- [x] [Image loading transition animation](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#image-transition-430) +- [x] A guarantee that the same URL won't be downloaded several times +- [x] A guarantee that bogus URLs won't be retried again and again +- [x] A guarantee that main thread will never be blocked +- [x] Modern Objective-C and better Swift support +- [x] Performances! + +## Supported Image Formats + +- Image formats supported by UIImage (JPEG, PNG, HEIC, ...), including GIF/APNG/HEIC animation +- WebP format, including animated WebP (use the [SDWebImageWebPCoder](https://github.com/SDWebImage/SDWebImageWebPCoder) project) +- Support extendable coder plugins for new image formats like BPG, AVIF. And vector format like PDF, SVG. See all the list in [Image coder plugin List](https://github.com/SDWebImage/SDWebImage/wiki/Coder-Plugin-List) + +## Additional modules + +In order to keep SDWebImage focused and limited to the core features, but also allow extensibility and custom behaviors, during the 5.0 refactoring we focused on modularizing the library. +As such, we have moved/built new modules to [SDWebImage org](https://github.com/SDWebImage). + +#### SwiftUI +[SwiftUI](https://developer.apple.com/xcode/swiftui/) is an innovative UI framework written in Swift to build user interfaces across all Apple platforms. + +We support SwiftUI by building with the functions (caching, loading and animation) powered by SDWebImage. You can have a try with [SDWebImageSwiftUI](https://github.com/SDWebImage/SDWebImageSwiftUI) + +#### Coders for additional image formats +- [SDWebImageWebPCoder](https://github.com/SDWebImage/SDWebImageWebPCoder) - coder for WebP image format. Based on [libwebp](https://chromium.googlesource.com/webm/libwebp) +- [SDWebImageHEIFCoder](https://github.com/SDWebImage/SDWebImageHEIFCoder) - coder to support HEIF image without Apple's `Image/IO framework`, iOS 8+/macOS 10.10+ support. +- [SDWebImageBPGCoder](https://github.com/SDWebImage/SDWebImageBPGCoder) - coder for BPG format +- [SDWebImageFLIFCoder](https://github.com/SDWebImage/SDWebImageFLIFCoder) - coder for FLIF format +- [SDWebImageAVIFCoder](https://github.com/SDWebImage/SDWebImageAVIFCoder) - coder for AVIF (AV1-based) format +- [SDWebImagePDFCoder](https://github.com/SDWebImage/SDWebImagePDFCoder) - coder for PDF vector format image +- [SDWebImageSVGCoder](https://github.com/SDWebImage/SDWebImageSVGCoder) - coder for SVG vector format image +- and more from community! + +#### Loaders +- [SDWebImagePhotosPlugin](https://github.com/SDWebImage/SDWebImagePhotosPlugin) - plugin to support loading images from Photos (using `Photos.framework`) +- [SDWebImageLinkPlugin](https://github.com/SDWebImage/SDWebImageLinkPlugin) - plugin to support loading images from rich link url, as well as `LPLinkView` (using `LinkPresentation.framework`) + +#### Integration with 3rd party libraries +- [SDWebImageFLPlugin](https://github.com/SDWebImage/SDWebImageFLPlugin) - plugin to support [FLAnimatedImage](https://github.com/Flipboard/FLAnimatedImage) as the engine for animated GIFs +- [SDWebImageYYPlugin](https://github.com/SDWebImage/SDWebImageYYPlugin) - plugin to integrate [YYImage](https://github.com/ibireme/YYImage) & [YYCache](https://github.com/ibireme/YYCache) for image rendering & caching + +#### Make our lives easier +- [libwebp-Xcode](https://github.com/SDWebImage/libwebp-Xcode) - A wrapper for [libwebp](https://chromium.googlesource.com/webm/libwebp) + an Xcode project. +- [libheif-Xcode](https://github.com/SDWebImage/libheif-Xcode) - A wrapper for [libheif](https://github.com/strukturag/libheif) + an Xcode project. +- and more third-party C/C++ image codec libraries with CocoaPods/Carthage support. + +You can use those directly, or create similar components of your own. + +## Requirements + +- iOS 8.0 or later +- tvOS 9.0 or later +- watchOS 2.0 or later +- macOS 10.10 or later (10.15 for Catalyst) +- Xcode 10.0 or later + +#### Backwards compatibility + +- For iOS 7, macOS 10.9 or Xcode < 8, use [any 4.x version up to 4.4.6](https://github.com/SDWebImage/SDWebImage/releases/tag/4.4.6) +- For macOS 10.8, use [any 4.x version up to 4.3.0](https://github.com/SDWebImage/SDWebImage/releases/tag/4.3.0) +- For iOS 5 and 6, use [any 3.x version up to 3.7.6](https://github.com/SDWebImage/SDWebImage/tag/3.7.6) +- For iOS < 5.0, please use the last [2.0 version](https://github.com/SDWebImage/SDWebImage/tree/2.0-compat). + +## Getting Started + +- Read this Readme doc +- Read the [How to use section](https://github.com/SDWebImage/SDWebImage#how-to-use) +- Read the [Latest Documentation](https://sdwebimage.github.io/) and [CocoaDocs for old version](http://cocoadocs.org/docsets/SDWebImage/) +- Try the example by downloading the project from Github or even easier using CocoaPods try `pod try SDWebImage` +- Read the [Installation Guide](https://github.com/SDWebImage/SDWebImage/wiki/Installation-Guide) +- Read the [SDWebImage 5.0 Migration Guide](https://github.com/SDWebImage/SDWebImage/blob/master/Docs/SDWebImage-5.0-Migration-guide.md) to get an idea of the changes from 4.x to 5.x +- Read the [SDWebImage 4.0 Migration Guide](https://github.com/SDWebImage/SDWebImage/blob/master/Docs/SDWebImage-4.0-Migration-guide.md) to get an idea of the changes from 3.x to 4.x +- Read the [Common Problems](https://github.com/SDWebImage/SDWebImage/wiki/Common-Problems) to find the solution for common problems +- Go to the [Wiki Page](https://github.com/SDWebImage/SDWebImage/wiki) for more information such as [Advanced Usage](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage) + +## Who Uses It +- Find out [who uses SDWebImage](https://github.com/SDWebImage/SDWebImage/wiki/Who-Uses-SDWebImage) and add your app to the list. + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/sdwebimage). (Tag 'sdwebimage') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/sdwebimage). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. + +## Contribution + +- If you **want to contribute**, read the [Contributing Guide](https://github.com/SDWebImage/SDWebImage/blob/master/.github/CONTRIBUTING.md) +- For **development contribution guide**, read the [How-To-Contribute](https://github.com/SDWebImage/SDWebImage/wiki/How-to-Contribute) + +## How To Use + +* Objective-C + +```objective-c +#import +... +[imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] + placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; +``` + +* Swift + +```swift +import SDWebImage + +imageView.sd_setImage(with: URL(string: "http://www.domain.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png")) +``` + +- For details about how to use the library and clear examples, see [The detailed How to use](https://github.com/SDWebImage/SDWebImage/blob/master/Docs/HowToUse.md) + +## Animated Images (GIF) support + +In 5.0, we introduced a brand new mechanism for supporting animated images. This includes animated image loading, rendering, decoding, and also supports customizations (for advanced users). +This animated image solution is available for `iOS`/`tvOS`/`macOS`. The `SDAnimatedImage` is subclass of `UIImage/NSImage`, and `SDAnimatedImageView` is subclass of `UIImageView/NSImageView`, to make them compatible with the common frameworks APIs. See [Animated Image](https://github.com/SDWebImage/SDWebImage/wiki/Advanced-Usage#animated-image-50) for more detailed information. + +#### FLAnimatedImage integration has its own dedicated repo +In order to clean up things and make our core project do less things, we decided that the `FLAnimatedImage` integration does not belong here. From 5.0, this will still be available, but under a dedicated repo [SDWebImageFLPlugin](https://github.com/SDWebImage/SDWebImageFLPlugin). + +## Installation + +There are four ways to use SDWebImage in your project: +- using CocoaPods +- using Carthage +- using Swift Package Manager +- manual install (build frameworks or embed Xcode Project) + +### Installation with CocoaPods + +[CocoaPods](http://cocoapods.org/) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects. See the [Get Started](http://cocoapods.org/#get_started) section for more details. + +#### Podfile +``` +platform :ios, '8.0' +pod 'SDWebImage', '~> 5.0' +``` + +##### Swift and static framework + +Swift project previously have to use `use_frameworks!` to make all Pods into dynamic framework to let CocoaPods works. + +However, start with `CocoaPods 1.5.0+` (with `Xcode 9+`), which supports to build both Objective-C && Swift code into static framework. You can use modular headers to use SDWebImage as static framework, without the need of `use_frameworks!`: + +``` +platform :ios, '8.0' +# Uncomment the next line when you want all Pods as static framework +# use_modular_headers! +pod 'SDWebImage', :modular_headers => true +``` + +See more on [CocoaPods 1.5.0 — Swift Static Libraries](http://blog.cocoapods.org/CocoaPods-1.5.0/) + +If not, you still need to add `use_frameworks!` to use SDWebImage as dynamic framework: + +``` +platform :ios, '8.0' +use_frameworks! +pod 'SDWebImage' +``` + +#### Subspecs + +There are 2 subspecs available now: `Core` and `MapKit` (this means you can install only some of the SDWebImage modules. By default, you get just `Core`, so if you need `MapKit`, you need to specify it). + +Podfile example: + +``` +pod 'SDWebImage/MapKit' +``` + +### Installation with Carthage (iOS 8+) + +[Carthage](https://github.com/Carthage/Carthage) is a lightweight dependency manager for Swift and Objective-C. It leverages CocoaTouch modules and is less invasive than CocoaPods. + +To install with carthage, follow the instruction on [Carthage](https://github.com/Carthage/Carthage) + +Carthage users can point to this repository and use whichever generated framework they'd like: SDWebImage, SDWebImageMapKit or both. + +Make the following entry in your Cartfile: `github "SDWebImage/SDWebImage"` +Then run `carthage update` +If this is your first time using Carthage in the project, you'll need to go through some additional steps as explained [over at Carthage](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application). + +> NOTE: At this time, Carthage does not provide a way to build only specific repository subcomponents (or equivalent of CocoaPods's subspecs). All components and their dependencies will be built with the above command. However, you don't need to copy frameworks you aren't using into your project. For instance, if you aren't using `SDWebImageMapKit`, feel free to delete that framework from the Carthage Build directory after `carthage update` completes. + +### Installation with Swift Package Manager (Xcode 11+) + +[Swift Package Manager](https://swift.org/package-manager/) (SwiftPM) is a tool for managing the distribution of Swift code as well as C-family dependency. From Xcode 11, SwiftPM got natively integrated with Xcode. + +SDWebImage support SwiftPM from version 5.1.0. To use SwiftPM, you should use Xcode 11 to open your project. Click `File` -> `Swift Packages` -> `Add Package Dependency`, enter [SDWebImage repo's URL](https://github.com/SDWebImage/SDWebImage.git). Or you can login Xcode with your GitHub account and just type `SDWebImage` to search. + +After select the package, you can choose the dependency type (tagged version, branch or commit). Then Xcode will setup all the stuff for you. + +If you're a framework author and use SDWebImage as a dependency, update your `Package.swift` file: + +```swift +let package = Package( + // 5.1.0 ..< 6.0.0 + dependencies: [ + .package(url: "https://github.com/SDWebImage/SDWebImage.git", from: "5.1.0") + ], + // ... +) +``` + +### Manual Installation Guide + +See more on [Manual install Guide](https://github.com/SDWebImage/SDWebImage/wiki/Installation-Guide#manual-installation-guide) + +### Import headers in your source files + +In the source files where you need to use the library, import the umbrella header file: + +```objective-c +#import +``` + +### Build Project + +At this point your workspace should build without error. If you are having problem, post to the Issue and the +community can help you solve it. + +## Author +- [Olivier Poitrey](https://github.com/rs) + +## Collaborators +- [Konstantinos K.](https://github.com/mythodeia) +- [Bogdan Poplauschi](https://github.com/bpoplauschi) +- [Chester Liu](https://github.com/skyline75489) +- [DreamPiggy](https://github.com/dreampiggy) +- [Wu Zhong](https://github.com/zhongwuzw) + +## Credits + +Thank you to all the people who have already contributed to SDWebImage. + +[![Contributors](https://opencollective.com/SDWebImage/contributors.svg?width=890)](https://github.com/SDWebImage/SDWebImage/graphs/contributors) + +## Licenses + +All source code is licensed under the [MIT License](https://github.com/SDWebImage/SDWebImage/blob/master/LICENSE). + +## Architecture + +#### High Level Diagram +

+ +

+ +#### Overall Class Diagram +

+ +

+ +#### Top Level API Diagram +

+ +

+ +#### Main Sequence Diagram +

+ +

+ +#### More detailed diagrams +- [Manager API Diagram](https://raw.githubusercontent.com/SDWebImage/SDWebImage/master/Docs/Diagrams/SDWebImageManagerClassDiagram.png) +- [Coders API Diagram](https://raw.githubusercontent.com/SDWebImage/SDWebImage/master/Docs/Diagrams/SDWebImageCodersClassDiagram.png) +- [Loader API Diagram](https://raw.githubusercontent.com/SDWebImage/SDWebImage/master/Docs/Diagrams/SDWebImageLoaderClassDiagram.png) +- [Cache API Diagram](https://raw.githubusercontent.com/SDWebImage/SDWebImage/master/Docs/Diagrams/SDWebImageCacheClassDiagram.png) + diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.h new file mode 100644 index 0000000..5b8035b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.h @@ -0,0 +1,340 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_MAC + +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with NSButton. + */ +@interface NSButton (WebCache) + +#pragma mark - Image + +/** + * Get the current image URL. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentImageURL; + +/** + * Set the button `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the button `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +#pragma mark - Alternate Image + +/** + * Get the current alternateImage URL. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentAlternateImageURL; + +/** + * Set the button `alternateImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the button `alternateImage` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @see sd_setAlternateImageWithURL:placeholderImage:options: + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the button `alternateImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the button `alternateImage` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the button `alternateImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `alternateImage` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the button `alternateImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `alternateImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while alternateImage is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `alternateImage` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the alternateImage. + * @param placeholder The alternateImage to be set initially, until the alternateImage request finishes. + * @param options The options to use when downloading the alternateImage. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while alternateImage is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the alternateImage parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the alternateImage was retrieved from the local cache or from the network. + * The fourth parameter is the original alternateImage url. + */ +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +#pragma mark - Cancel + +/** + * Cancel the current image download + */ +- (void)sd_cancelCurrentImageLoad; + +/** + * Cancel the current alternateImage download + */ +- (void)sd_cancelCurrentAlternateImageLoad; + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.m new file mode 100644 index 0000000..300e5a3 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSButton+WebCache.m @@ -0,0 +1,172 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "NSButton+WebCache.h" + +#if SD_MAC + +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCache.h" +#import "SDInternalMacros.h" + +static NSString * const SDAlternateImageOperationKey = @"NSButtonAlternateImageOperation"; + +@implementation NSButton (WebCache) + +#pragma mark - Image + +- (void)sd_setImageWithURL:(nullable NSURL *)url { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + self.sd_currentImageURL = url; + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:context + setImageBlock:nil + progress:progressBlock + completed:^(NSImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - Alternate Image + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url { + [self sd_setAlternateImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setAlternateImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setAlternateImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setAlternateImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + self.sd_currentAlternateImageURL = url; + + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextSetImageOperationKey] = SDAlternateImageOperationKey; + @weakify(self); + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:mutableContext + setImageBlock:^(NSImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) { + @strongify(self); + self.alternateImage = image; + } + progress:progressBlock + completed:^(NSImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - Cancel + +- (void)sd_cancelCurrentImageLoad { + [self sd_cancelImageLoadOperationWithKey:NSStringFromClass([self class])]; +} + +- (void)sd_cancelCurrentAlternateImageLoad { + [self sd_cancelImageLoadOperationWithKey:SDAlternateImageOperationKey]; +} + +#pragma mar - Private + +- (NSURL *)sd_currentImageURL { + return objc_getAssociatedObject(self, @selector(sd_currentImageURL)); +} + +- (void)setSd_currentImageURL:(NSURL *)sd_currentImageURL { + objc_setAssociatedObject(self, @selector(sd_currentImageURL), sd_currentImageURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (NSURL *)sd_currentAlternateImageURL { + return objc_getAssociatedObject(self, @selector(sd_currentAlternateImageURL)); +} + +- (void)setSd_currentAlternateImageURL:(NSURL *)sd_currentAlternateImageURL { + objc_setAssociatedObject(self, @selector(sd_currentAlternateImageURL), sd_currentAlternateImageURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.h new file mode 100644 index 0000000..5bbb4ae --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.h @@ -0,0 +1,57 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Fabrice Aneche + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/** + You can use switch case like normal enum. It's also recommended to add a default case. You should not assume anything about the raw value. + For custom coder plugin, it can also extern the enum for supported format. See `SDImageCoder` for more detailed information. + */ +typedef NSInteger SDImageFormat NS_TYPED_EXTENSIBLE_ENUM; +static const SDImageFormat SDImageFormatUndefined = -1; +static const SDImageFormat SDImageFormatJPEG = 0; +static const SDImageFormat SDImageFormatPNG = 1; +static const SDImageFormat SDImageFormatGIF = 2; +static const SDImageFormat SDImageFormatTIFF = 3; +static const SDImageFormat SDImageFormatWebP = 4; +static const SDImageFormat SDImageFormatHEIC = 5; +static const SDImageFormat SDImageFormatHEIF = 6; + +/** + NSData category about the image content type and UTI. + */ +@interface NSData (ImageContentType) + +/** + * Return image format + * + * @param data the input image data + * + * @return the image format as `SDImageFormat` (enum) + */ ++ (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data; + +/** + * Convert SDImageFormat to UTType + * + * @param format Format as SDImageFormat + * @return The UTType as CFStringRef + */ ++ (nonnull CFStringRef)sd_UTTypeFromImageFormat:(SDImageFormat)format CF_RETURNS_NOT_RETAINED NS_SWIFT_NAME(sd_UTType(from:)); + +/** + * Convert UTTyppe to SDImageFormat + * + * @param uttype The UTType as CFStringRef + * @return The Format as SDImageFormat + */ ++ (SDImageFormat)sd_imageFormatFromUTType:(nonnull CFStringRef)uttype; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.m new file mode 100644 index 0000000..34dd4aa --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSData+ImageContentType.m @@ -0,0 +1,129 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Fabrice Aneche + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "NSData+ImageContentType.h" +#if SD_MAC +#import +#else +#import +#endif +#import "SDImageHEICCoderInternal.h" + +// Currently Image/IO does not support WebP +#define kSDUTTypeWebP ((__bridge CFStringRef)@"public.webp") + +@implementation NSData (ImageContentType) + ++ (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data { + if (!data) { + return SDImageFormatUndefined; + } + + // File signatures table: http://www.garykessler.net/library/file_sigs.html + uint8_t c; + [data getBytes:&c length:1]; + switch (c) { + case 0xFF: + return SDImageFormatJPEG; + case 0x89: + return SDImageFormatPNG; + case 0x47: + return SDImageFormatGIF; + case 0x49: + case 0x4D: + return SDImageFormatTIFF; + case 0x52: { + if (data.length >= 12) { + //RIFF....WEBP + NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; + if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { + return SDImageFormatWebP; + } + } + break; + } + case 0x00: { + if (data.length >= 12) { + //....ftypheic ....ftypheix ....ftyphevc ....ftyphevx + NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(4, 8)] encoding:NSASCIIStringEncoding]; + if ([testString isEqualToString:@"ftypheic"] + || [testString isEqualToString:@"ftypheix"] + || [testString isEqualToString:@"ftyphevc"] + || [testString isEqualToString:@"ftyphevx"]) { + return SDImageFormatHEIC; + } + //....ftypmif1 ....ftypmsf1 + if ([testString isEqualToString:@"ftypmif1"] || [testString isEqualToString:@"ftypmsf1"]) { + return SDImageFormatHEIF; + } + } + break; + } + } + return SDImageFormatUndefined; +} + ++ (nonnull CFStringRef)sd_UTTypeFromImageFormat:(SDImageFormat)format { + CFStringRef UTType; + switch (format) { + case SDImageFormatJPEG: + UTType = kUTTypeJPEG; + break; + case SDImageFormatPNG: + UTType = kUTTypePNG; + break; + case SDImageFormatGIF: + UTType = kUTTypeGIF; + break; + case SDImageFormatTIFF: + UTType = kUTTypeTIFF; + break; + case SDImageFormatWebP: + UTType = kSDUTTypeWebP; + break; + case SDImageFormatHEIC: + UTType = kSDUTTypeHEIC; + break; + case SDImageFormatHEIF: + UTType = kSDUTTypeHEIF; + break; + default: + // default is kUTTypePNG + UTType = kUTTypePNG; + break; + } + return UTType; +} + ++ (SDImageFormat)sd_imageFormatFromUTType:(CFStringRef)uttype { + if (!uttype) { + return SDImageFormatUndefined; + } + SDImageFormat imageFormat; + if (CFStringCompare(uttype, kUTTypeJPEG, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatJPEG; + } else if (CFStringCompare(uttype, kUTTypePNG, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatPNG; + } else if (CFStringCompare(uttype, kUTTypeGIF, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatGIF; + } else if (CFStringCompare(uttype, kUTTypeTIFF, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatTIFF; + } else if (CFStringCompare(uttype, kSDUTTypeWebP, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatWebP; + } else if (CFStringCompare(uttype, kSDUTTypeHEIC, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatHEIC; + } else if (CFStringCompare(uttype, kSDUTTypeHEIF, 0) == kCFCompareEqualTo) { + imageFormat = SDImageFormatHEIF; + } else { + imageFormat = SDImageFormatUndefined; + } + return imageFormat; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.h new file mode 100644 index 0000000..0a562cc --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.h @@ -0,0 +1,67 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_MAC + +/** + This category is provided to easily write cross-platform(AppKit/UIKit) code. For common usage, see `UIImage+Metadata.h`. + */ +@interface NSImage (Compatibility) + +/** +The underlying Core Graphics image object. This will actually use `CGImageForProposedRect` with the image size. + */ +@property (nonatomic, readonly, nullable) CGImageRef CGImage; +/** + The underlying Core Image data. This will actually use `bestRepresentationForRect` with the image size to find the `NSCIImageRep`. + */ +@property (nonatomic, readonly, nullable) CIImage *CIImage; +/** + The scale factor of the image. This wil actually use `bestRepresentationForRect` with image size and pixel size to calculate the scale factor. If failed, use the default value 1.0. Should be greater than or equal to 1.0. + */ +@property (nonatomic, readonly) CGFloat scale; + +// These are convenience methods to make AppKit's `NSImage` match UIKit's `UIImage` behavior. The scale factor should be greater than or equal to 1.0. + +/** + Returns an image object with the scale factor and orientation. The representation is created from the Core Graphics image object. + @note The difference between this and `initWithCGImage:size` is that `initWithCGImage:size` will actually create a `NSCGImageSnapshotRep` representation and always use `backingScaleFactor` as scale factor. So we should avoid it and use `NSBitmapImageRep` with `initWithCGImage:` instead. + @note The difference between this and UIKit's `UIImage` equivalent method is the way to process orientation. If the provided image orientation is not equal to Up orientation, this method will firstly rotate the CGImage to the correct orientation to work compatible with `NSImageView`. However, UIKit will not actually rotate CGImage and just store it as `imageOrientation` property. + + @param cgImage A Core Graphics image object + @param scale The image scale factor + @param orientation The orientation of the image data + @return The image object + */ +- (nonnull instancetype)initWithCGImage:(nonnull CGImageRef)cgImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation; + +/** + Initializes and returns an image object with the specified Core Image object. The representation is `NSCIImageRep`. + + @param ciImage A Core Image image object + @param scale The image scale factor + @param orientation The orientation of the image data + @return The image object + */ +- (nonnull instancetype)initWithCIImage:(nonnull CIImage *)ciImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation; + +/** + Returns an image object with the scale factor. The representation is created from the image data. + @note The difference between these this and `initWithData:` is that `initWithData:` will always use `backingScaleFactor` as scale factor. + + @param data The image data + @param scale The image scale factor + @return The image object + */ +- (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale; + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.m new file mode 100644 index 0000000..7de0c70 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/NSImage+Compatibility.m @@ -0,0 +1,120 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "NSImage+Compatibility.h" + +#if SD_MAC + +#import "SDImageCoderHelper.h" + +@implementation NSImage (Compatibility) + +- (nullable CGImageRef)CGImage { + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + CGImageRef cgImage = [self CGImageForProposedRect:&imageRect context:nil hints:nil]; + return cgImage; +} + +- (nullable CIImage *)CIImage { + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + if (![imageRep isKindOfClass:NSCIImageRep.class]) { + return nil; + } + return ((NSCIImageRep *)imageRep).CIImage; +} + +- (CGFloat)scale { + CGFloat scale = 1; + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + CGFloat width = imageRep.size.width; + CGFloat height = imageRep.size.height; + NSUInteger pixelWidth = imageRep.pixelsWide; + NSUInteger pixelHeight = imageRep.pixelsHigh; + if (width > 0 && height > 0) { + CGFloat widthScale = pixelWidth / width; + CGFloat heightScale = pixelHeight / height; + if (widthScale == heightScale && widthScale >= 1) { + // Protect because there may be `NSImageRepMatchesDevice` (0) + scale = widthScale; + } + } + + return scale; +} + +- (instancetype)initWithCGImage:(nonnull CGImageRef)cgImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation { + NSBitmapImageRep *imageRep; + if (orientation != kCGImagePropertyOrientationUp) { + // AppKit design is different from UIKit. Where CGImage based image rep does not respect to any orientation. Only data based image rep which contains the EXIF metadata can automatically detect orientation. + // This should be nonnull, until the memory is exhausted cause `CGBitmapContextCreate` failed. + CGImageRef rotatedCGImage = [SDImageCoderHelper CGImageCreateDecoded:cgImage orientation:orientation]; + imageRep = [[NSBitmapImageRep alloc] initWithCGImage:rotatedCGImage]; + CGImageRelease(rotatedCGImage); + } else { + imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage]; + } + if (scale < 1) { + scale = 1; + } + CGFloat pixelWidth = imageRep.pixelsWide; + CGFloat pixelHeight = imageRep.pixelsHigh; + NSSize size = NSMakeSize(pixelWidth / scale, pixelHeight / scale); + self = [self initWithSize:size]; + if (self) { + imageRep.size = size; + [self addRepresentation:imageRep]; + } + return self; +} + +- (instancetype)initWithCIImage:(nonnull CIImage *)ciImage scale:(CGFloat)scale orientation:(CGImagePropertyOrientation)orientation { + NSCIImageRep *imageRep; + if (orientation != kCGImagePropertyOrientationUp) { + CIImage *rotatedCIImage = [ciImage imageByApplyingOrientation:orientation]; + imageRep = [[NSCIImageRep alloc] initWithCIImage:rotatedCIImage]; + } else { + imageRep = [[NSCIImageRep alloc] initWithCIImage:ciImage]; + } + if (scale < 1) { + scale = 1; + } + CGFloat pixelWidth = imageRep.pixelsWide; + CGFloat pixelHeight = imageRep.pixelsHigh; + NSSize size = NSMakeSize(pixelWidth / scale, pixelHeight / scale); + self = [self initWithSize:size]; + if (self) { + imageRep.size = size; + [self addRepresentation:imageRep]; + } + return self; +} + +- (instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale { + NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithData:data]; + if (!imageRep) { + return nil; + } + if (scale < 1) { + scale = 1; + } + CGFloat pixelWidth = imageRep.pixelsWide; + CGFloat pixelHeight = imageRep.pixelsHigh; + NSSize size = NSMakeSize(pixelWidth / scale, pixelHeight / scale); + self = [self initWithSize:size]; + if (self) { + imageRep.size = size; + [self addRepresentation:imageRep]; + } + return self; +} + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.h new file mode 100644 index 0000000..a1e2fb1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.h @@ -0,0 +1,114 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDImageCoder.h" + + +/** + This is the protocol for SDAnimatedImage class only but not for SDAnimatedImageCoder. If you want to provide a custom animated image class with full advanced function, you can conform to this instead of the base protocol. + */ +@protocol SDAnimatedImage + +@required +/** + Initializes and returns the image object with the specified data, scale factor and possible animation decoding options. + @note We use this to create animated image instance for normal animation decoding. + + @param data The data object containing the image data. + @param scale The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property. + @param options A dictionary containing any animation decoding options. + @return An initialized object + */ +- (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale options:(nullable SDImageCoderOptions *)options; + +/** + Initializes the image with an animated coder. You can use the coder to decode the image frame later. + @note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding. + + @param animatedCoder An animated coder which conform `SDAnimatedImageCoder` protocol + @param scale The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property. + @return An initialized object + */ +- (nullable instancetype)initWithAnimatedCoder:(nonnull id)animatedCoder scale:(CGFloat)scale; + +@optional +// These methods are used for optional advanced feature, like image frame preloading. +/** + Pre-load all animated image frame into memory. Then later frame image request can directly return the frame for index without decoding. + This method may be called on background thread. + + @note If one image instance is shared by lots of imageViews, the CPU performance for large animated image will drop down because the request frame index will be random (not in order) and the decoder should take extra effort to keep it re-entrant. You can use this to reduce CPU usage if need. Attention this will consume more memory usage. + */ +- (void)preloadAllFrames; + +/** + Unload all animated image frame from memory if are already pre-loaded. Then later frame image request need decoding. You can use this to free up the memory usage if need. + */ +- (void)unloadAllFrames; + +/** + Returns a Boolean value indicating whether all animated image frames are already pre-loaded into memory. + */ +@property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded; + +/** + Return the animated image coder if the image is created with `initWithAnimatedCoder:scale:` method. + @note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding. + */ +@property (nonatomic, strong, readonly, nullable) id animatedCoder; + +@end + +/** + The image class which supports animating on `SDAnimatedImageView`. You can also use it on normal UIImageView/NSImageView. + */ +@interface SDAnimatedImage : UIImage + +// This class override these methods from UIImage(NSImage), and it supports NSSecureCoding. +// You should use these methods to create a new animated image. Use other methods just call super instead. +// Pay attention, when the animated image frame count <= 1, all the `SDAnimatedImageProvider` protocol methods will return nil or 0 value, you'd better check the frame count before usage and keep fallback. ++ (nullable instancetype)imageNamed:(nonnull NSString *)name; // Cache in memory, no Asset Catalog support +#if __has_include() ++ (nullable instancetype)imageNamed:(nonnull NSString *)name inBundle:(nullable NSBundle *)bundle compatibleWithTraitCollection:(nullable UITraitCollection *)traitCollection; // Cache in memory, no Asset Catalog support +#else ++ (nullable instancetype)imageNamed:(nonnull NSString *)name inBundle:(nullable NSBundle *)bundle; // Cache in memory, no Asset Catalog support +#endif ++ (nullable instancetype)imageWithContentsOfFile:(nonnull NSString *)path; ++ (nullable instancetype)imageWithData:(nonnull NSData *)data; ++ (nullable instancetype)imageWithData:(nonnull NSData *)data scale:(CGFloat)scale; +- (nullable instancetype)initWithContentsOfFile:(nonnull NSString *)path; +- (nullable instancetype)initWithData:(nonnull NSData *)data; +- (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale; + +/** + Current animated image format. + */ +@property (nonatomic, assign, readonly) SDImageFormat animatedImageFormat; + +/** + Current animated image data, you can use this to grab the compressed format data and create another animated image instance. + If this image instance is an animated image created by using animated image coder (which means using the API listed above or using `initWithAnimatedCoder:scale:`), this property is non-nil. + */ +@property (nonatomic, copy, readonly, nullable) NSData *animatedImageData; + +/** + The scale factor of the image. + + @note For UIKit, this just call super instead. + @note For AppKit, `NSImage` can contains multiple image representations with different scales. However, this class does not do that from the design. We processs the scale like UIKit. This wil actually be calculated from image size and pixel size. + */ +@property (nonatomic, readonly) CGFloat scale; + +// By default, animated image frames are returned by decoding just in time without keeping into memory. But you can choose to preload them into memory as well, See the decsription in `SDAnimatedImage` protocol. +// After preloaded, there is no huge difference on performance between this and UIImage's `animatedImageWithImages:duration:`. But UIImage's animation have some issues such like blanking and pausing during segue when using in `UIImageView`. It's recommend to use only if need. +- (void)preloadAllFrames; +- (void)unloadAllFrames; +@property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.m new file mode 100644 index 0000000..ce5d5d2 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImage.m @@ -0,0 +1,300 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImage.h" +#import "NSImage+Compatibility.h" +#import "SDImageCoder.h" +#import "SDImageCodersManager.h" +#import "SDImageFrame.h" +#import "UIImage+MemoryCacheCost.h" +#import "SDImageAssetManager.h" +#import "objc/runtime.h" + +static CGFloat SDImageScaleFromPath(NSString *string) { + if (string.length == 0 || [string hasSuffix:@"/"]) return 1; + NSString *name = string.stringByDeletingPathExtension; + __block CGFloat scale = 1; + + NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:@"@[0-9]+\\.?[0-9]*x$" options:NSRegularExpressionAnchorsMatchLines error:nil]; + [pattern enumerateMatchesInString:name options:kNilOptions range:NSMakeRange(0, name.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { + if (result.range.location >= 3) { + scale = [string substringWithRange:NSMakeRange(result.range.location + 1, result.range.length - 2)].doubleValue; + } + }]; + + return scale; +} + +@interface SDAnimatedImage () + +@property (nonatomic, strong) id animatedCoder; +@property (nonatomic, assign, readwrite) SDImageFormat animatedImageFormat; +@property (atomic, copy) NSArray *loadedAnimatedImageFrames; // Mark as atomic to keep thread-safe +@property (nonatomic, assign, getter=isAllFramesLoaded) BOOL allFramesLoaded; + +@end + +@implementation SDAnimatedImage +@dynamic scale; // call super + +#pragma mark - UIImage override method ++ (instancetype)imageNamed:(NSString *)name { +#if __has_include() + return [self imageNamed:name inBundle:nil compatibleWithTraitCollection:nil]; +#else + return [self imageNamed:name inBundle:nil]; +#endif +} + +#if __has_include() ++ (instancetype)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle compatibleWithTraitCollection:(UITraitCollection *)traitCollection { + if (!traitCollection) { + traitCollection = UIScreen.mainScreen.traitCollection; + } + CGFloat scale = traitCollection.displayScale; + return [self imageNamed:name inBundle:bundle scale:scale]; +} +#else ++ (instancetype)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle { + return [self imageNamed:name inBundle:bundle scale:0]; +} +#endif + +// 0 scale means automatically check ++ (instancetype)imageNamed:(NSString *)name inBundle:(NSBundle *)bundle scale:(CGFloat)scale { + if (!name) { + return nil; + } + if (!bundle) { + bundle = [NSBundle mainBundle]; + } + SDImageAssetManager *assetManager = [SDImageAssetManager sharedAssetManager]; + SDAnimatedImage *image = (SDAnimatedImage *)[assetManager imageForName:name]; + if ([image isKindOfClass:[SDAnimatedImage class]]) { + return image; + } + NSString *path = [assetManager getPathForName:name bundle:bundle preferredScale:&scale]; + if (!path) { + return image; + } + NSData *data = [NSData dataWithContentsOfFile:path]; + if (!data) { + return image; + } + image = [[self alloc] initWithData:data scale:scale]; + if (image) { + [assetManager storeImage:image forName:name]; + } + + return image; +} + ++ (instancetype)imageWithContentsOfFile:(NSString *)path { + return [[self alloc] initWithContentsOfFile:path]; +} + ++ (instancetype)imageWithData:(NSData *)data { + return [[self alloc] initWithData:data]; +} + ++ (instancetype)imageWithData:(NSData *)data scale:(CGFloat)scale { + return [[self alloc] initWithData:data scale:scale]; +} + +- (instancetype)initWithContentsOfFile:(NSString *)path { + NSData *data = [NSData dataWithContentsOfFile:path]; + return [self initWithData:data scale:SDImageScaleFromPath(path)]; +} + +- (instancetype)initWithData:(NSData *)data { + return [self initWithData:data scale:1]; +} + +- (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale { + return [self initWithData:data scale:scale options:nil]; +} + +- (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale options:(SDImageCoderOptions *)options { + if (!data || data.length == 0) { + return nil; + } + data = [data copy]; // avoid mutable data + id animatedCoder = nil; + for (idcoder in [SDImageCodersManager sharedManager].coders) { + if ([coder conformsToProtocol:@protocol(SDAnimatedImageCoder)]) { + if ([coder canDecodeFromData:data]) { + if (!options) { + options = @{SDImageCoderDecodeScaleFactor : @(scale)}; + } + animatedCoder = [[[coder class] alloc] initWithAnimatedImageData:data options:options]; + break; + } + } + } + if (!animatedCoder) { + return nil; + } + return [self initWithAnimatedCoder:animatedCoder scale:scale]; +} + +- (instancetype)initWithAnimatedCoder:(id)animatedCoder scale:(CGFloat)scale { + if (!animatedCoder) { + return nil; + } + UIImage *image = [animatedCoder animatedImageFrameAtIndex:0]; + if (!image) { + return nil; + } +#if SD_MAC + self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:kCGImagePropertyOrientationUp]; +#else + self = [super initWithCGImage:image.CGImage scale:MAX(scale, 1) orientation:image.imageOrientation]; +#endif + if (self) { + // Only keep the animated coder if frame count > 1, save RAM usage for non-animated image format (APNG/WebP) + if (animatedCoder.animatedImageFrameCount > 1) { + _animatedCoder = animatedCoder; + } + NSData *data = [animatedCoder animatedImageData]; + SDImageFormat format = [NSData sd_imageFormatForImageData:data]; + _animatedImageFormat = format; + } + return self; +} + +#pragma mark - Preload +- (void)preloadAllFrames { + if (!_animatedCoder) { + return; + } + if (!self.isAllFramesLoaded) { + NSMutableArray *frames = [NSMutableArray arrayWithCapacity:self.animatedImageFrameCount]; + for (size_t i = 0; i < self.animatedImageFrameCount; i++) { + UIImage *image = [self animatedImageFrameAtIndex:i]; + NSTimeInterval duration = [self animatedImageDurationAtIndex:i]; + SDImageFrame *frame = [SDImageFrame frameWithImage:image duration:duration]; // through the image should be nonnull, used as nullable for `animatedImageFrameAtIndex:` + [frames addObject:frame]; + } + self.loadedAnimatedImageFrames = frames; + self.allFramesLoaded = YES; + } +} + +- (void)unloadAllFrames { + if (!_animatedCoder) { + return; + } + if (self.isAllFramesLoaded) { + self.loadedAnimatedImageFrames = nil; + self.allFramesLoaded = NO; + } +} + +#pragma mark - NSSecureCoding +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + self = [super initWithCoder:aDecoder]; + if (self) { + _animatedImageFormat = [aDecoder decodeIntegerForKey:NSStringFromSelector(@selector(animatedImageFormat))]; + NSData *animatedImageData = [aDecoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(animatedImageData))]; + if (!animatedImageData) { + return self; + } + CGFloat scale = self.scale; + id animatedCoder = nil; + for (idcoder in [SDImageCodersManager sharedManager].coders) { + if ([coder conformsToProtocol:@protocol(SDAnimatedImageCoder)]) { + if ([coder canDecodeFromData:animatedImageData]) { + animatedCoder = [[[coder class] alloc] initWithAnimatedImageData:animatedImageData options:@{SDImageCoderDecodeScaleFactor : @(scale)}]; + break; + } + } + } + if (!animatedCoder) { + return self; + } + if (animatedCoder.animatedImageFrameCount > 1) { + _animatedCoder = animatedCoder; + } + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [super encodeWithCoder:aCoder]; + [aCoder encodeInteger:self.animatedImageFormat forKey:NSStringFromSelector(@selector(animatedImageFormat))]; + NSData *animatedImageData = self.animatedImageData; + if (animatedImageData) { + [aCoder encodeObject:animatedImageData forKey:NSStringFromSelector(@selector(animatedImageData))]; + } +} + ++ (BOOL)supportsSecureCoding { + return YES; +} + +#pragma mark - SDAnimatedImageProvider + +- (NSData *)animatedImageData { + return [self.animatedCoder animatedImageData]; +} + +- (NSUInteger)animatedImageLoopCount { + return [self.animatedCoder animatedImageLoopCount]; +} + +- (NSUInteger)animatedImageFrameCount { + return [self.animatedCoder animatedImageFrameCount]; +} + +- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { + if (index >= self.animatedImageFrameCount) { + return nil; + } + if (self.isAllFramesLoaded) { + SDImageFrame *frame = [self.loadedAnimatedImageFrames objectAtIndex:index]; + return frame.image; + } + return [self.animatedCoder animatedImageFrameAtIndex:index]; +} + +- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { + if (index >= self.animatedImageFrameCount) { + return 0; + } + if (self.isAllFramesLoaded) { + SDImageFrame *frame = [self.loadedAnimatedImageFrames objectAtIndex:index]; + return frame.duration; + } + return [self.animatedCoder animatedImageDurationAtIndex:index]; +} + +@end + +@implementation SDAnimatedImage (MemoryCacheCost) + +- (NSUInteger)sd_memoryCost { + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_memoryCost)); + if (value != nil) { + return value.unsignedIntegerValue; + } + + CGImageRef imageRef = self.CGImage; + if (!imageRef) { + return 0; + } + NSUInteger bytesPerFrame = CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef); + NSUInteger frameCount = 1; + if (self.isAllFramesLoaded) { + frameCount = self.animatedImageFrameCount; + } + frameCount = frameCount > 0 ? frameCount : 1; + NSUInteger cost = bytesPerFrame * frameCount; + return cost; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.h new file mode 100644 index 0000000..b6fa88d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.h @@ -0,0 +1,90 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" +#import "SDImageCoder.h" + +/// A player to control the playback of animated image, which can be used to drive Animated ImageView or any rendering usage, like CALayer/WatchKit/SwiftUI rendering. +@interface SDAnimatedImagePlayer : NSObject + +/// Current playing frame image. This value is KVO Compliance. +@property (nonatomic, readonly, nullable) UIImage *currentFrame; + +/// Current frame index, zero based. This value is KVO Compliance. +@property (nonatomic, readonly) NSUInteger currentFrameIndex; + +/// Current loop count since its latest animating. This value is KVO Compliance. +@property (nonatomic, readonly) NSUInteger currentLoopCount; + +/// Total frame count for niamted image rendering. Defaults is animated image's frame count. +/// @note For progressive animation, you can update this value when your provider receive more frames. +@property (nonatomic, assign) NSUInteger totalFrameCount; + +/// Total loop count for animated image rendering. Default is animated image's loop count. +@property (nonatomic, assign) NSUInteger totalLoopCount; + +/// The animation playback rate. Default is 1.0 +/// `1.0` means the normal speed. +/// `0.0` means stopping the animation. +/// `0.0-1.0` means the slow speed. +/// `> 1.0` means the fast speed. +/// `< 0.0` is not supported currently and stop animation. (may support reverse playback in the future) +@property (nonatomic, assign) double playbackRate; + +/// Provide a max buffer size by bytes. This is used to adjust frame buffer count and can be useful when the decoding cost is expensive (such as Animated WebP software decoding). Default is 0. +/// `0` means automatically adjust by calculating current memory usage. +/// `1` means without any buffer cache, each of frames will be decoded and then be freed after rendering. (Lowest Memory and Highest CPU) +/// `NSUIntegerMax` means cache all the buffer. (Lowest CPU and Highest Memory) +@property (nonatomic, assign) NSUInteger maxBufferSize; + +/// You can specify a runloop mode to let it rendering. +/// Default is NSRunLoopCommonModes on multi-core device, NSDefaultRunLoopMode on single-core device +@property (nonatomic, copy, nonnull) NSRunLoopMode runLoopMode; + +/// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil. +/// The provider can be any protocol implementation, like `SDAnimatedImage`, `SDImageGIFCoder`, etc. +/// @note This provider can represent mutable content, like prorgessive animated loading. But you need to update the frame count by yourself +/// @param provider The animated provider +- (nullable instancetype)initWithProvider:(nonnull id)provider; + +/// Create a player with animated image provider. If the provider's `animatedImageFrameCount` is less than 1, returns nil. +/// The provider can be any protocol implementation, like `SDAnimatedImage` or `SDImageGIFCoder`, etc. +/// @note This provider can represent mutable content, like prorgessive animated loading. But you need to update the frame count by yourself +/// @param provider The animated provider ++ (nullable instancetype)playerWithProvider:(nonnull id)provider; + +/// The handler block when current frame and index changed. +@property (nonatomic, copy, nullable) void (^animationFrameHandler)(NSUInteger index, UIImage * _Nonnull frame); + +/// The handler block when one loop count finished. +@property (nonatomic, copy, nullable) void (^animationLoopHandler)(NSUInteger loopCount); + +/// Return the status whehther animation is playing. +@property (nonatomic, readonly) BOOL isPlaying; + +/// Start the animation. Or resume the previously paused animation. +- (void)startPlaying; + +/// Pause the aniamtion. Keep the current frame index and loop count. +- (void)pausePlaying; + +/// Stop the animation. Reset the current frame index and loop count. +- (void)stopPlaying; + +/// Seek to the desired frame index and loop count. +/// @note This can be used for advanced control like progressive loading, or skipping specify frames. +/// @param index The frame index +/// @param loopCount The loop count +- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount; + +/// Clear the frame cache buffer. The frame cache buffer size can be controled by `maxBufferSize`. +/// By default, when stop or pause the animation, the frame buffer is still kept to ready for the next restart +- (void)clearFrameBuffer; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.m new file mode 100644 index 0000000..39658b4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImagePlayer.m @@ -0,0 +1,390 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDAnimatedImagePlayer.h" +#import "NSImage+Compatibility.h" +#import "SDDisplayLink.h" +#import "SDDeviceHelper.h" +#import "SDInternalMacros.h" + +@interface SDAnimatedImagePlayer () { + NSRunLoopMode _runLoopMode; +} + +@property (nonatomic, strong, readwrite) UIImage *currentFrame; +@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex; +@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount; +@property (nonatomic, strong) id animatedProvider; +@property (nonatomic, strong) NSMutableDictionary *frameBuffer; +@property (nonatomic, assign) NSTimeInterval currentTime; +@property (nonatomic, assign) BOOL bufferMiss; +@property (nonatomic, assign) BOOL needsDisplayWhenImageBecomesAvailable; +@property (nonatomic, assign) NSUInteger maxBufferCount; +@property (nonatomic, strong) NSOperationQueue *fetchQueue; +@property (nonatomic, strong) dispatch_semaphore_t lock; +@property (nonatomic, strong) SDDisplayLink *displayLink; + +@end + +@implementation SDAnimatedImagePlayer + +- (instancetype)initWithProvider:(id)provider { + self = [super init]; + if (self) { + NSUInteger animatedImageFrameCount = provider.animatedImageFrameCount; + // Check the frame count + if (animatedImageFrameCount <= 1) { + return nil; + } + self.totalFrameCount = animatedImageFrameCount; + // Get the current frame and loop count. + self.totalLoopCount = provider.animatedImageLoopCount; + self.animatedProvider = provider; + self.playbackRate = 1.0; +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + ++ (instancetype)playerWithProvider:(id)provider { + SDAnimatedImagePlayer *player = [[SDAnimatedImagePlayer alloc] initWithProvider:provider]; + return player; +} + +#pragma mark - Life Cycle + +- (void)dealloc { +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif +} + +- (void)didReceiveMemoryWarning:(NSNotification *)notification { + [_fetchQueue cancelAllOperations]; + [_fetchQueue addOperationWithBlock:^{ + NSNumber *currentFrameIndex = @(self.currentFrameIndex); + SD_LOCK(self.lock); + NSArray *keys = self.frameBuffer.allKeys; + // only keep the next frame for later rendering + for (NSNumber * key in keys) { + if (![key isEqualToNumber:currentFrameIndex]) { + [self.frameBuffer removeObjectForKey:key]; + } + } + SD_UNLOCK(self.lock); + }]; +} + +#pragma mark - Private +- (NSOperationQueue *)fetchQueue { + if (!_fetchQueue) { + _fetchQueue = [[NSOperationQueue alloc] init]; + _fetchQueue.maxConcurrentOperationCount = 1; + } + return _fetchQueue; +} + +- (NSMutableDictionary *)frameBuffer { + if (!_frameBuffer) { + _frameBuffer = [NSMutableDictionary dictionary]; + } + return _frameBuffer; +} + +- (dispatch_semaphore_t)lock { + if (!_lock) { + _lock = dispatch_semaphore_create(1); + } + return _lock; +} + +- (SDDisplayLink *)displayLink { + if (!_displayLink) { + _displayLink = [SDDisplayLink displayLinkWithTarget:self selector:@selector(displayDidRefresh:)]; + [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode]; + [_displayLink stop]; + } + return _displayLink; +} + +- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode { + if ([_runLoopMode isEqual:runLoopMode]) { + return; + } + if (_displayLink) { + if (_runLoopMode) { + [_displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runLoopMode]; + } + if (runLoopMode.length > 0) { + [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:runLoopMode]; + } + } + _runLoopMode = [runLoopMode copy]; +} + +- (NSRunLoopMode)runLoopMode { + if (!_runLoopMode) { + _runLoopMode = [[self class] defaultRunLoopMode]; + } + return _runLoopMode; +} + +#pragma mark - State Control + +- (void)setupCurrentFrame { + if (self.currentFrameIndex != 0) { + return; + } + if ([self.animatedProvider isKindOfClass:[UIImage class]]) { + UIImage *image = (UIImage *)self.animatedProvider; + // Use the poster image if available + #if SD_MAC + UIImage *posterFrame = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp]; + #else + UIImage *posterFrame = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation]; + #endif + if (posterFrame) { + self.currentFrame = posterFrame; + SD_LOCK(self.lock); + self.frameBuffer[@(self.currentFrameIndex)] = self.currentFrame; + SD_UNLOCK(self.lock); + [self handleFrameChange]; + } + } +} + +- (void)resetCurrentFrameIndex { + self.currentFrame = nil; + self.currentFrameIndex = 0; + self.currentLoopCount = 0; + self.currentTime = 0; + self.bufferMiss = NO; + self.needsDisplayWhenImageBecomesAvailable = NO; + [self handleFrameChange]; +} + +- (void)clearFrameBuffer { + SD_LOCK(self.lock); + [_frameBuffer removeAllObjects]; + SD_UNLOCK(self.lock); +} + +#pragma mark - Animation Control +- (void)startPlaying { + [self.displayLink start]; + // Calculate max buffer size + [self calculateMaxBufferCount]; + // Setup frame + if (self.currentFrameIndex == 0 && !self.currentFrame) { + [self setupCurrentFrame]; + } +} + +- (void)stopPlaying { + [_fetchQueue cancelAllOperations]; + // Using `_displayLink` here because when UIImageView dealloc, it may trigger `[self stopAnimating]`, we already release the display link in SDAnimatedImageView's dealloc method. + [_displayLink stop]; + [self resetCurrentFrameIndex]; +} + +- (void)pausePlaying { + [_fetchQueue cancelAllOperations]; + [_displayLink stop]; +} + +- (BOOL)isPlaying { + return _displayLink.isRunning; +} + +- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount { + if (index >= self.totalFrameCount) { + return; + } + self.currentFrameIndex = index; + self.currentLoopCount = loopCount; + [self handleFrameChange]; +} + +#pragma mark - Core Render +- (void)displayDidRefresh:(SDDisplayLink *)displayLink { + // If for some reason a wild call makes it through when we shouldn't be animating, bail. + // Early return! + if (!self.isPlaying) { + return; + } + + NSUInteger totalFrameCount = self.totalFrameCount; + if (totalFrameCount <= 1) { + // Total frame count less than 1, wrong configuration and stop animating + [self stopPlaying]; + return; + } + + NSTimeInterval playbackRate = self.playbackRate; + if (playbackRate <= 0) { + // Does not support <= 0 play rate + [self stopPlaying]; + return; + } + + // Calculate refresh duration + NSTimeInterval duration = self.displayLink.duration; + + NSUInteger currentFrameIndex = self.currentFrameIndex; + NSUInteger nextFrameIndex = (currentFrameIndex + 1) % totalFrameCount; + + // Check if we need to display new frame firstly + BOOL bufferFull = NO; + if (self.needsDisplayWhenImageBecomesAvailable) { + UIImage *currentFrame; + SD_LOCK(self.lock); + currentFrame = self.frameBuffer[@(currentFrameIndex)]; + SD_UNLOCK(self.lock); + + // Update the current frame + if (currentFrame) { + SD_LOCK(self.lock); + // Remove the frame buffer if need + if (self.frameBuffer.count > self.maxBufferCount) { + self.frameBuffer[@(currentFrameIndex)] = nil; + } + // Check whether we can stop fetch + if (self.frameBuffer.count == totalFrameCount) { + bufferFull = YES; + } + SD_UNLOCK(self.lock); + + // Update the current frame immediately + self.currentFrame = currentFrame; + [self handleFrameChange]; + + self.bufferMiss = NO; + self.needsDisplayWhenImageBecomesAvailable = NO; + } + else { + self.bufferMiss = YES; + } + } + + // Check if we have the frame buffer + if (!self.bufferMiss) { + // Then check if timestamp is reached + self.currentTime += duration; + NSTimeInterval currentDuration = [self.animatedProvider animatedImageDurationAtIndex:currentFrameIndex]; + currentDuration = currentDuration / playbackRate; + if (self.currentTime < currentDuration) { + // Current frame timestamp not reached, return + return; + } + + // Otherwise, we shoudle be ready to display next frame + self.needsDisplayWhenImageBecomesAvailable = YES; + self.currentFrameIndex = nextFrameIndex; + self.currentTime -= currentDuration; + NSTimeInterval nextDuration = [self.animatedProvider animatedImageDurationAtIndex:nextFrameIndex]; + nextDuration = nextDuration / playbackRate; + if (self.currentTime > nextDuration) { + // Do not skip frame + self.currentTime = nextDuration; + } + + // Update the loop count when last frame rendered + if (nextFrameIndex == 0) { + // Update the loop count + self.currentLoopCount++; + [self handleLoopChnage]; + + // if reached the max loop count, stop animating, 0 means loop indefinitely + NSUInteger maxLoopCount = self.totalLoopCount; + if (maxLoopCount != 0 && (self.currentLoopCount >= maxLoopCount)) { + [self stopPlaying]; + return; + } + } + } + + // Since we support handler, check animating state again + if (!self.isPlaying) { + return; + } + + // Check if we should prefetch next frame or current frame + // When buffer miss, means the decode speed is slower than render speed, we fetch current miss frame + // Or, most cases, the decode speed is faster than render speed, we fetch next frame + NSUInteger fetchFrameIndex = self.bufferMiss? currentFrameIndex : nextFrameIndex; + UIImage *fetchFrame; + SD_LOCK(self.lock); + fetchFrame = self.bufferMiss? nil : self.frameBuffer[@(nextFrameIndex)]; + SD_UNLOCK(self.lock); + + if (!fetchFrame && !bufferFull && self.fetchQueue.operationCount == 0) { + // Prefetch next frame in background queue + id animatedProvider = self.animatedProvider; + @weakify(self); + NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ + @strongify(self); + if (!self) { + return; + } + UIImage *frame = [animatedProvider animatedImageFrameAtIndex:fetchFrameIndex]; + + BOOL isAnimating = self.displayLink.isRunning; + if (isAnimating) { + SD_LOCK(self.lock); + self.frameBuffer[@(fetchFrameIndex)] = frame; + SD_UNLOCK(self.lock); + } + }]; + [self.fetchQueue addOperation:operation]; + } +} + +- (void)handleFrameChange { + if (self.animationFrameHandler) { + self.animationFrameHandler(self.currentFrameIndex, self.currentFrame); + } +} + +- (void)handleLoopChnage { + if (self.animationLoopHandler) { + self.animationLoopHandler(self.currentLoopCount); + } +} + +#pragma mark - Util +- (void)calculateMaxBufferCount { + NSUInteger bytes = CGImageGetBytesPerRow(self.currentFrame.CGImage) * CGImageGetHeight(self.currentFrame.CGImage); + if (bytes == 0) bytes = 1024; + + NSUInteger max = 0; + if (self.maxBufferSize > 0) { + max = self.maxBufferSize; + } else { + // Calculate based on current memory, these factors are by experience + NSUInteger total = [SDDeviceHelper totalMemory]; + NSUInteger free = [SDDeviceHelper freeMemory]; + max = MIN(total * 0.2, free * 0.6); + } + + NSUInteger maxBufferCount = (double)max / (double)bytes; + if (!maxBufferCount) { + // At least 1 frame + maxBufferCount = 1; + } + + self.maxBufferCount = maxBufferCount; +} + ++ (NSString *)defaultRunLoopMode { + // Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations. + return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.h new file mode 100644 index 0000000..be52f8c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.h @@ -0,0 +1,23 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_MAC + +/** + A subclass of `NSBitmapImageRep` to fix that GIF duration issue because `NSBitmapImageRep` will reset `NSImageCurrentFrameDuration` by using `kCGImagePropertyGIFDelayTime` but not `kCGImagePropertyGIFUnclampedDelayTime`. + This also fix the GIF loop count issue, which will use the Netscape standard (See http://www6.uniovi.es/gifanim/gifabout.htm) to only place once when the `kCGImagePropertyGIFLoopCount` is nil. This is what modern browser's behavior. + Built in GIF coder use this instead of `NSBitmapImageRep` for better GIF rendering. If you do not want this, only enable `SDImageIOCoder`, which just call `NSImage` API and actually use `NSBitmapImageRep` for GIF image. + This also support APNG format using `SDImageAPNGCoder`. Which provide full alpha-channel support and the correct duration match the `kCGImagePropertyAPNGUnclampedDelayTime`. + */ +@interface SDAnimatedImageRep : NSBitmapImageRep + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.m new file mode 100644 index 0000000..d0da9ba --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageRep.m @@ -0,0 +1,114 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImageRep.h" + +#if SD_MAC + +#import "SDImageIOAnimatedCoderInternal.h" +#import "SDImageGIFCoder.h" +#import "SDImageAPNGCoder.h" +#import "SDImageHEICCoder.h" +#import "SDImageHEICCoderInternal.h" + +@implementation SDAnimatedImageRep { + CGImageSourceRef _imageSource; +} + +- (void)dealloc { + if (_imageSource) { + CFRelease(_imageSource); + _imageSource = NULL; + } +} + +// `NSBitmapImageRep`'s `imageRepWithData:` is not designed initlizer ++ (instancetype)imageRepWithData:(NSData *)data { + SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:data]; + return imageRep; +} + +// We should override init method for `NSBitmapImageRep` to do initlize about animated image format +- (instancetype)initWithData:(NSData *)data { + self = [super initWithData:data]; + if (self) { + CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef) data, NULL); + if (!imageSource) { + return self; + } + _imageSource = imageSource; + NSUInteger frameCount = CGImageSourceGetCount(imageSource); + if (frameCount <= 1) { + return self; + } + CFStringRef type = CGImageSourceGetType(imageSource); + if (!type) { + return self; + } + if (CFStringCompare(type, kUTTypeGIF, 0) == kCFCompareEqualTo) { + // GIF + // Fix the `NSBitmapImageRep` GIF loop count calculation issue + // Which will use 0 when there are no loop count information metadata in GIF data + NSUInteger loopCount = [SDImageGIFCoder imageLoopCountWithSource:imageSource]; + [self setProperty:NSImageLoopCount withValue:@(loopCount)]; + } else if (CFStringCompare(type, kUTTypePNG, 0) == kCFCompareEqualTo) { + // APNG + // Do initilize about frame count, current frame/duration and loop count + [self setProperty:NSImageFrameCount withValue:@(frameCount)]; + [self setProperty:NSImageCurrentFrame withValue:@(0)]; + NSUInteger loopCount = [SDImageAPNGCoder imageLoopCountWithSource:imageSource]; + [self setProperty:NSImageLoopCount withValue:@(loopCount)]; + } else if (CFStringCompare(type, kSDUTTypeHEICS, 0) == kCFCompareEqualTo) { + // HEIC + // Do initilize about frame count, current frame/duration and loop count + [self setProperty:NSImageFrameCount withValue:@(frameCount)]; + [self setProperty:NSImageCurrentFrame withValue:@(0)]; + NSUInteger loopCount = [SDImageHEICCoder imageLoopCountWithSource:imageSource]; + [self setProperty:NSImageLoopCount withValue:@(loopCount)]; + } + } + return self; +} + +// `NSBitmapImageRep` will use `kCGImagePropertyGIFDelayTime` whenever you call `setProperty:withValue:` with `NSImageCurrentFrame` to change the current frame. We override it and use the actual `kCGImagePropertyGIFUnclampedDelayTime` if need. +- (void)setProperty:(NSBitmapImageRepPropertyKey)property withValue:(id)value { + [super setProperty:property withValue:value]; + if ([property isEqualToString:NSImageCurrentFrame]) { + // Access the image source + CGImageSourceRef imageSource = _imageSource; + if (!imageSource) { + return; + } + // Check format type + CFStringRef type = CGImageSourceGetType(imageSource); + if (!type) { + return; + } + NSUInteger index = [value unsignedIntegerValue]; + NSTimeInterval frameDuration = 0; + if (CFStringCompare(type, kUTTypeGIF, 0) == kCFCompareEqualTo) { + // GIF + frameDuration = [SDImageGIFCoder frameDurationAtIndex:index source:imageSource]; + } else if (CFStringCompare(type, kUTTypePNG, 0) == kCFCompareEqualTo) { + // APNG + frameDuration = [SDImageAPNGCoder frameDurationAtIndex:index source:imageSource]; + } else if (CFStringCompare(type, kSDUTTypeHEICS, 0) == kCFCompareEqualTo) { + // HEIC + frameDuration = [SDImageHEICCoder frameDurationAtIndex:index source:imageSource]; + } + if (!frameDuration) { + return; + } + // Reset super frame duration with the actual frame duration + [super setProperty:NSImageCurrentFrameDuration withValue:@(frameDuration)]; + } +} + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.h new file mode 100644 index 0000000..af46476 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.h @@ -0,0 +1,168 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImageView.h" + +#if SD_UIKIT || SD_MAC + +#import "SDWebImageManager.h" + +/** + Integrates SDWebImage async downloading and caching of remote images with SDAnimatedImageView. + */ +@interface SDAnimatedImageView (WebCache) + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.m new file mode 100644 index 0000000..beb56b2 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView+WebCache.m @@ -0,0 +1,79 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImageView+WebCache.h" + +#if SD_UIKIT || SD_MAC + +#import "UIView+WebCache.h" +#import "SDAnimatedImage.h" + +@implementation SDAnimatedImageView (WebCache) + +- (void)sd_setImageWithURL:(nullable NSURL *)url { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + Class animatedImageClass = [SDAnimatedImage class]; + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextAnimatedImageClass] = animatedImageClass; + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:mutableContext + setImageBlock:nil + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.h new file mode 100644 index 0000000..2d9ac66 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.h @@ -0,0 +1,92 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT || SD_MAC + +#import "SDAnimatedImage.h" + +/** + A drop-in replacement for UIImageView/NSImageView, you can use this for animated image rendering. + Call `setImage:` with `UIImage(NSImage)` which conform to `SDAnimatedImage` protocol will start animated image rendering. Call with normal UIImage(NSImage) will back to normal UIImageView(NSImageView) rendering + For UIKit: use `-startAnimating`, `-stopAnimating` to control animating. `isAnimating` to check animation state. + For AppKit: use `-setAnimates:` to control animating, `animates` to check animation state. This view is layer-backed. + */ +@interface SDAnimatedImageView : UIImageView + +/** + Current display frame image. This value is KVO Compliance. + */ +@property (nonatomic, strong, readonly, nullable) UIImage *currentFrame; +/** + Current frame index, zero based. This value is KVO Compliance. + */ +@property (nonatomic, assign, readonly) NSUInteger currentFrameIndex; +/** + Current loop count since its latest animating. This value is KVO Compliance. + */ +@property (nonatomic, assign, readonly) NSUInteger currentLoopCount; +/** + YES to choose `animationRepeatCount` property for animation loop count. No to use animated image's `animatedImageLoopCount` instead. + Default is NO. + */ +@property (nonatomic, assign) BOOL shouldCustomLoopCount; +/** + Total loop count for animated image rendering. Default is animated image's loop count. + If you need to set custom loop count, set `shouldCustomLoopCount` to YES and change this value. + This class override UIImageView's `animationRepeatCount` property on iOS, use this property as well. + */ +@property (nonatomic, assign) NSInteger animationRepeatCount; +/** + The animation playback rate. Default is 1.0. + `1.0` means the normal speed. + `0.0` means stopping the animation. + `0.0-1.0` means the slow speed. + `> 1.0` means the fast speed. + `< 0.0` is not supported currently and stop animation. (may support reverse playback in the future) + */ +@property (nonatomic, assign) double playbackRate; +/** + Provide a max buffer size by bytes. This is used to adjust frame buffer count and can be useful when the decoding cost is expensive (such as Animated WebP software decoding). Default is 0. + `0` means automatically adjust by calculating current memory usage. + `1` means without any buffer cache, each of frames will be decoded and then be freed after rendering. (Lowest Memory and Highest CPU) + `NSUIntegerMax` means cache all the buffer. (Lowest CPU and Highest Memory) + */ +@property (nonatomic, assign) NSUInteger maxBufferSize; +/** + Whehter or not to enable incremental image load for animated image. This is for the animated image which `sd_isIncremental` is YES (See `UIImage+Metadata.h`). If enable, animated image rendering will stop at the last frame available currently, and continue when another `setImage:` trigger, where the new animated image's `animatedImageData` should be updated from the previous one. If the `sd_isIncremental` is NO. The incremental image load stop. + @note If you are confused about this description, open Chrome browser to view some large GIF images with low network speed to see the animation behavior. + @note The best practice to use incremental load is using `initWithAnimatedCoder:scale:` in `SDAnimatedImage` with animated coder which conform to `SDProgressiveImageCoder` as well. Then call incremental update and incremental decode method to produce the image. + Default is YES. Set to NO to only render the static poster for incremental animated image. + */ +@property (nonatomic, assign) BOOL shouldIncrementalLoad; + +/** + Whether or not to clear the frame buffer cache when animation stopped. See `maxBufferSize` + This is useful when you want to limit the memory usage during frequently visibility changes (such as image view inside a list view, then push and pop) + Default is NO. + */ +@property (nonatomic, assign) BOOL clearBufferWhenStopped; + +/** + Whether or not to reset the current frame index when animation stopped. + For some of use case, you may want to reset the frame index to 0 when stop, but some other want to keep the current frame index. + Default is NO. + */ +@property (nonatomic, assign) BOOL resetFrameIndexWhenStopped; + +/** + You can specify a runloop mode to let it rendering. + Default is NSRunLoopCommonModes on multi-core device, NSDefaultRunLoopMode on single-core device + @note This is useful for some cases, for example, always specify NSDefaultRunLoopMode, if you want to pause the animation when user scroll (for Mac user, drag the mouse or touchpad) + */ +@property (nonatomic, copy, nonnull) NSRunLoopMode runLoopMode; +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.m new file mode 100644 index 0000000..e973438 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDAnimatedImageView.m @@ -0,0 +1,505 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAnimatedImageView.h" + +#if SD_UIKIT || SD_MAC + +#import "SDAnimatedImagePlayer.h" +#import "UIImage+Metadata.h" +#import "NSImage+Compatibility.h" +#import "SDInternalMacros.h" +#import "objc/runtime.h" + +@interface SDAnimatedImageView () { + BOOL _initFinished; // Extra flag to mark the `commonInit` is called + NSRunLoopMode _runLoopMode; + NSUInteger _maxBufferSize; + double _playbackRate; +} + +@property (nonatomic, strong, readwrite) UIImage *currentFrame; +@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex; +@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount; +@property (nonatomic, assign) BOOL shouldAnimate; +@property (nonatomic, assign) BOOL isProgressive; +@property (nonatomic,strong) SDAnimatedImagePlayer *player; // The animation player. +@property (nonatomic) CALayer *imageViewLayer; // The actual rendering layer. + +@end + +@implementation SDAnimatedImageView +#if SD_UIKIT +@dynamic animationRepeatCount; // we re-use this property from `UIImageView` super class on iOS. +#endif + +#pragma mark - Initializers + +#if SD_MAC ++ (instancetype)imageViewWithImage:(NSImage *)image +{ + NSRect frame = NSMakeRect(0, 0, image.size.width, image.size.height); + SDAnimatedImageView *imageView = [[SDAnimatedImageView alloc] initWithFrame:frame]; + [imageView setImage:image]; + return imageView; +} +#else +// -initWithImage: isn't documented as a designated initializer of UIImageView, but it actually seems to be. +// Using -initWithImage: doesn't call any of the other designated initializers. +- (instancetype)initWithImage:(UIImage *)image +{ + self = [super initWithImage:image]; + if (self) { + [self commonInit]; + } + return self; +} + +// -initWithImage:highlightedImage: also isn't documented as a designated initializer of UIImageView, but it doesn't call any other designated initializers. +- (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage +{ + self = [super initWithImage:image highlightedImage:highlightedImage]; + if (self) { + [self commonInit]; + } + return self; +} +#endif + +- (instancetype)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + [self commonInit]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if (self) { + [self commonInit]; + } + return self; +} + +- (void)commonInit +{ + // Pay attention that UIKit's `initWithImage:` will trigger a `setImage:` during initialization before this `commonInit`. + // So the properties which rely on this order, should using lazy-evaluation or do extra check in `setImage:`. + self.shouldCustomLoopCount = NO; + self.shouldIncrementalLoad = YES; + self.playbackRate = 1.0; +#if SD_MAC + self.wantsLayer = YES; +#endif + // Mark commonInit finished + _initFinished = YES; +} + +#pragma mark - Accessors +#pragma mark Public + +- (void)setImage:(UIImage *)image +{ + if (self.image == image) { + return; + } + + // Check Progressive rendering + [self updateIsProgressiveWithImage:image]; + + if (!self.isProgressive) { + // Stop animating + self.player = nil; + self.currentFrame = nil; + self.currentFrameIndex = 0; + self.currentLoopCount = 0; + } + + // We need call super method to keep function. This will impliedly call `setNeedsDisplay`. But we have no way to avoid this when using animated image. So we call `setNeedsDisplay` again at the end. + super.image = image; + if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)]) { + if (!self.player) { + id provider; + // Check progressive loading + if (self.isProgressive) { + provider = [self progressiveAnimatedCoderForImage:image]; + } else { + provider = (id)image; + } + // Create animted player + self.player = [SDAnimatedImagePlayer playerWithProvider:provider]; + } else { + // Update Frame Count + self.player.totalFrameCount = [(id)image animatedImageFrameCount]; + } + + if (!self.player) { + // animated player nil means the image format is not supported, or frame count <= 1 + return; + } + + // Custom Loop Count + if (self.shouldCustomLoopCount) { + self.player.totalLoopCount = self.animationRepeatCount; + } + + // RunLoop Mode + self.player.runLoopMode = self.runLoopMode; + + // Max Buffer Size + self.player.maxBufferSize = self.maxBufferSize; + + // Play Rate + self.player.playbackRate = self.playbackRate; + + // Setup handler + @weakify(self); + self.player.animationFrameHandler = ^(NSUInteger index, UIImage * frame) { + @strongify(self); + self.currentFrameIndex = index; + self.currentFrame = frame; + [self.imageViewLayer setNeedsDisplay]; + }; + self.player.animationLoopHandler = ^(NSUInteger loopCount) { + @strongify(self); + // Progressive image reach the current last frame index. Keep the state and pause animating. Wait for later restart + if (self.isProgressive) { + NSUInteger lastFrameIndex = self.player.totalFrameCount - 1; + [self.player seekToFrameAtIndex:lastFrameIndex loopCount:0]; + [self.player pausePlaying]; + } else { + self.currentLoopCount = loopCount; + } + }; + + // Ensure disabled highlighting; it's not supported (see `-setHighlighted:`). + super.highlighted = NO; + + // Start animating + [self startAnimating]; + + [self.imageViewLayer setNeedsDisplay]; + } +} + +#pragma mark - Configuration + +- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode +{ + _runLoopMode = [runLoopMode copy]; + self.player.runLoopMode = runLoopMode; +} + +- (NSRunLoopMode)runLoopMode +{ + if (!_runLoopMode) { + _runLoopMode = [[self class] defaultRunLoopMode]; + } + return _runLoopMode; +} + ++ (NSString *)defaultRunLoopMode { + // Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations. + return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode; +} + +- (void)setMaxBufferSize:(NSUInteger)maxBufferSize +{ + _maxBufferSize = maxBufferSize; + self.player.maxBufferSize = maxBufferSize; +} + +- (NSUInteger)maxBufferSize { + return _maxBufferSize; // Defaults to 0 +} + +- (void)setPlaybackRate:(double)playbackRate +{ + _playbackRate = playbackRate; + self.player.playbackRate = playbackRate; +} + +- (double)playbackRate +{ + if (!_initFinished) { + return 1.0; // Defaults to 1.0 + } + return _playbackRate; +} + +- (BOOL)shouldIncrementalLoad +{ + if (!_initFinished) { + return YES; // Defaults to YES + } + return _initFinished; +} + +#pragma mark - UIView Method Overrides +#pragma mark Observing View-Related Changes + +#if SD_MAC +- (void)viewDidMoveToSuperview +#else +- (void)didMoveToSuperview +#endif +{ +#if SD_MAC + [super viewDidMoveToSuperview]; +#else + [super didMoveToSuperview]; +#endif + + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} + +#if SD_MAC +- (void)viewDidMoveToWindow +#else +- (void)didMoveToWindow +#endif +{ +#if SD_MAC + [super viewDidMoveToWindow]; +#else + [super didMoveToWindow]; +#endif + + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} + +#if SD_MAC +- (void)setAlphaValue:(CGFloat)alphaValue +#else +- (void)setAlpha:(CGFloat)alpha +#endif +{ +#if SD_MAC + [super setAlphaValue:alphaValue]; +#else + [super setAlpha:alpha]; +#endif + + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} + +- (void)setHidden:(BOOL)hidden +{ + [super setHidden:hidden]; + + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} + +#pragma mark - UIImageView Method Overrides +#pragma mark Image Data + +- (void)setAnimationRepeatCount:(NSInteger)animationRepeatCount +{ +#if SD_UIKIT + [super setAnimationRepeatCount:animationRepeatCount]; +#else + _animationRepeatCount = animationRepeatCount; +#endif + + if (self.shouldCustomLoopCount) { + self.player.totalLoopCount = animationRepeatCount; + } +} + +- (void)startAnimating +{ + if (self.player) { + [self updateShouldAnimate]; + if (self.shouldAnimate) { + [self.player startPlaying]; + } + } else { +#if SD_UIKIT + [super startAnimating]; +#endif + } +} + +- (void)stopAnimating +{ + if (self.player) { + if (self.resetFrameIndexWhenStopped) { + [self.player stopPlaying]; + } else { + [self.player pausePlaying]; + } + if (self.clearBufferWhenStopped) { + [self.player clearFrameBuffer]; + } + } else { +#if SD_UIKIT + [super stopAnimating]; +#endif + } +} + +#if SD_UIKIT +- (BOOL)isAnimating +{ + if (self.player) { + return self.player.isPlaying; + } else { + return [super isAnimating]; + } +} +#endif + +#if SD_MAC +- (void)setAnimates:(BOOL)animates +{ + [super setAnimates:animates]; + if (animates) { + [self startAnimating]; + } else { + [self stopAnimating]; + } +} +#endif + +#pragma mark Highlighted Image Unsupport + +- (void)setHighlighted:(BOOL)highlighted +{ + // Highlighted image is unsupported for animated images, but implementing it breaks the image view when embedded in a UICollectionViewCell. + if (!self.player) { + [super setHighlighted:highlighted]; + } +} + + +#pragma mark - Private Methods +#pragma mark Animation + +// Don't repeatedly check our window & superview in `-displayDidRefresh:` for performance reasons. +// Just update our cached value whenever the animated image or visibility (window, superview, hidden, alpha) is changed. +- (void)updateShouldAnimate +{ +#if SD_MAC + BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alphaValue > 0.0; +#else + BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alpha > 0.0; +#endif + self.shouldAnimate = self.player && isVisible; +} + +// Update progressive status only after `setImage:` call. +- (void)updateIsProgressiveWithImage:(UIImage *)image +{ + self.isProgressive = NO; + if (!self.shouldIncrementalLoad) { + // Early return + return; + } + // We must use `image.class conformsToProtocol:` instead of `image conformsToProtocol:` here + // Because UIKit on macOS, using internal hard-coded override method, which returns NO + id currentAnimatedCoder = [self progressiveAnimatedCoderForImage:image]; + if (currentAnimatedCoder) { + UIImage *previousImage = self.image; + if (!previousImage) { + // If current animated coder supports progressive, and no previous image to check, start progressive loading + self.isProgressive = YES; + } else { + id previousAnimatedCoder = [self progressiveAnimatedCoderForImage:previousImage]; + if (previousAnimatedCoder == currentAnimatedCoder) { + // If current animated coder is the same as previous, start progressive loading + self.isProgressive = YES; + } + } + } +} + +// Check if image can represent a `Progressive Animated Image` during loading +- (id)progressiveAnimatedCoderForImage:(UIImage *)image +{ + if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)] && image.sd_isIncremental && [image respondsToSelector:@selector(animatedCoder)]) { + id animatedCoder = [(id)image animatedCoder]; + if ([animatedCoder conformsToProtocol:@protocol(SDProgressiveImageCoder)]) { + return (id)animatedCoder; + } + } + return nil; +} + + +#pragma mark Providing the Layer's Content +#pragma mark - CALayerDelegate + +- (void)displayLayer:(CALayer *)layer +{ + UIImage *currentFrame = self.currentFrame; + if (currentFrame) { + layer.contentsScale = currentFrame.scale; + layer.contents = (__bridge id)currentFrame.CGImage; + } +} + +#if SD_MAC +// NSImageView use a subview. We need this subview's layer for actual rendering. +// Why using this design may because of properties like `imageAlignment` and `imageScaling`, which it's not available for UIImageView.contentMode (it's impossible to align left and keep aspect ratio at the same time) +- (NSView *)imageView { + NSImageView *imageView = imageView = objc_getAssociatedObject(self, NSSelectorFromString(@"_imageView")); + if (!imageView) { + // macOS 10.14 + imageView = objc_getAssociatedObject(self, NSSelectorFromString(@"_imageSubview")); + } + return imageView; +} + +// on macOS, it's the imageView subview's layer (we use layer-hosting view to let CALayerDelegate works) +- (CALayer *)imageViewLayer { + NSView *imageView = self.imageView; + if (!imageView) { + return nil; + } + if (!_imageViewLayer) { + _imageViewLayer = [CALayer new]; + _imageViewLayer.delegate = self; + imageView.layer = _imageViewLayer; + imageView.wantsLayer = YES; + } + return _imageViewLayer; +} +#else +// on iOS, it's the imageView itself's layer +- (CALayer *)imageViewLayer { + return self.layer; +} + +#endif + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.h new file mode 100644 index 0000000..dc5e1fa --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.h @@ -0,0 +1,145 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +@class SDImageCacheConfig; +/** + A protocol to allow custom disk cache used in SDImageCache. + */ +@protocol SDDiskCache + +// All of these method are called from the same global queue to avoid blocking on main queue and thread-safe problem. But it's also recommend to ensure thread-safe yourself using lock or other ways. +@required +/** + Create a new disk cache based on the specified path. You can check `maxDiskSize` and `maxDiskAge` used for disk cache. + + @param cachePath Full path of a directory in which the cache will write data. + Once initialized you should not read and write to this directory. + @param config The cache config to be used to create the cache. + + @return A new cache object, or nil if an error occurs. + */ +- (nullable instancetype)initWithCachePath:(nonnull NSString *)cachePath config:(nonnull SDImageCacheConfig *)config; + +/** + Returns a boolean value that indicates whether a given key is in cache. + This method may blocks the calling thread until file read finished. + + @param key A string identifying the data. If nil, just return NO. + @return Whether the key is in cache. + */ +- (BOOL)containsDataForKey:(nonnull NSString *)key; + +/** + Returns the data associated with a given key. + This method may blocks the calling thread until file read finished. + + @param key A string identifying the data. If nil, just return nil. + @return The value associated with key, or nil if no value is associated with key. + */ +- (nullable NSData *)dataForKey:(nonnull NSString *)key; + +/** + Sets the value of the specified key in the cache. + This method may blocks the calling thread until file write finished. + + @param data The data to be stored in the cache. + @param key The key with which to associate the value. If nil, this method has no effect. + */ +- (void)setData:(nullable NSData *)data forKey:(nonnull NSString *)key; + +/** + Returns the extended data associated with a given key. + This method may blocks the calling thread until file read finished. + + @param key A string identifying the data. If nil, just return nil. + @return The value associated with key, or nil if no value is associated with key. + */ +- (nullable NSData *)extendedDataForKey:(nonnull NSString *)key; + +/** + Set extended data with a given key. + + @discussion You can set any extended data to exist cache key. Without override the exist disk file data. + on UNIX, the common way for this is to use the Extended file attributes (xattr) + + @param extendedData The extended data (pass nil to remove). + @param key The key with which to associate the value. If nil, this method has no effect. +*/ +- (void)setExtendedData:(nullable NSData *)extendedData forKey:(nonnull NSString *)key; + +/** + Removes the value of the specified key in the cache. + This method may blocks the calling thread until file delete finished. + + @param key The key identifying the value to be removed. If nil, this method has no effect. + */ +- (void)removeDataForKey:(nonnull NSString *)key; + +/** + Empties the cache. + This method may blocks the calling thread until file delete finished. + */ +- (void)removeAllData; + +/** + Removes the expired data from the cache. You can choose the data to remove base on `ageLimit`, `countLimit` and `sizeLimit` options. + */ +- (void)removeExpiredData; + +/** + The cache path for key + + @param key A string identifying the value + @return The cache path for key. Or nil if the key can not associate to a path + */ +- (nullable NSString *)cachePathForKey:(nonnull NSString *)key; + +/** + Returns the number of data in this cache. + This method may blocks the calling thread until file read finished. + + @return The total data count. + */ +- (NSUInteger)totalCount; + +/** + Returns the total size (in bytes) of data in this cache. + This method may blocks the calling thread until file read finished. + + @return The total data size in bytes. + */ +- (NSUInteger)totalSize; + +@end + +/** + The built-in disk cache. + */ +@interface SDDiskCache : NSObject +/** + Cache Config object - storing all kind of settings. + */ +@property (nonatomic, strong, readonly, nonnull) SDImageCacheConfig *config; + +- (nonnull instancetype)init NS_UNAVAILABLE; + +/** + Move the cache directory from old location to new location, the old location will be removed after finish. + If the old location does not exist, does nothing. + If the new location does not exist, only do a movement of directory. + If the new location does exist, will move and merge the files from old location. + If the new location does exist, but is not a directory, will remove it and do a movement of directory. + + @param srcPath old location of cache directory + @param dstPath new location of cache directory + */ +- (void)moveCacheDirectoryFromPath:(nonnull NSString *)srcPath toPath:(nonnull NSString *)dstPath; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.m new file mode 100644 index 0000000..d7308dc --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDDiskCache.m @@ -0,0 +1,326 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDDiskCache.h" +#import "SDImageCacheConfig.h" +#import "SDFileAttributeHelper.h" +#import + +static NSString * const SDDiskCacheExtendedAttributeName = @"com.hackemist.SDDiskCache"; + +@interface SDDiskCache () + +@property (nonatomic, copy) NSString *diskCachePath; +@property (nonatomic, strong, nonnull) NSFileManager *fileManager; + +@end + +@implementation SDDiskCache + +- (instancetype)init { + NSAssert(NO, @"Use `initWithCachePath:` with the disk cache path"); + return nil; +} + +#pragma mark - SDcachePathForKeyDiskCache Protocol +- (instancetype)initWithCachePath:(NSString *)cachePath config:(nonnull SDImageCacheConfig *)config { + if (self = [super init]) { + _diskCachePath = cachePath; + _config = config; + [self commonInit]; + } + return self; +} + +- (void)commonInit { + if (self.config.fileManager) { + self.fileManager = self.config.fileManager; + } else { + self.fileManager = [NSFileManager new]; + } +} + +- (BOOL)containsDataForKey:(NSString *)key { + NSParameterAssert(key); + NSString *filePath = [self cachePathForKey:key]; + BOOL exists = [self.fileManager fileExistsAtPath:filePath]; + + // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name + // checking the key with and without the extension + if (!exists) { + exists = [self.fileManager fileExistsAtPath:filePath.stringByDeletingPathExtension]; + } + + return exists; +} + +- (NSData *)dataForKey:(NSString *)key { + NSParameterAssert(key); + NSString *filePath = [self cachePathForKey:key]; + NSData *data = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil]; + if (data) { + return data; + } + + // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name + // checking the key with and without the extension + data = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil]; + if (data) { + return data; + } + + return nil; +} + +- (void)setData:(NSData *)data forKey:(NSString *)key { + NSParameterAssert(data); + NSParameterAssert(key); + if (![self.fileManager fileExistsAtPath:self.diskCachePath]) { + [self.fileManager createDirectoryAtPath:self.diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; + } + + // get cache Path for image key + NSString *cachePathForKey = [self cachePathForKey:key]; + // transform to NSUrl + NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey]; + + [data writeToURL:fileURL options:self.config.diskCacheWritingOptions error:nil]; + + // disable iCloud backup + if (self.config.shouldDisableiCloud) { + // ignore iCloud backup resource value error + [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; + } +} + +- (NSData *)extendedDataForKey:(NSString *)key { + NSParameterAssert(key); + + // get cache Path for image key + NSString *cachePathForKey = [self cachePathForKey:key]; + + NSData *extendedData = [SDFileAttributeHelper extendedAttribute:SDDiskCacheExtendedAttributeName atPath:cachePathForKey traverseLink:NO error:nil]; + + return extendedData; +} + +- (void)setExtendedData:(NSData *)extendedData forKey:(NSString *)key { + NSParameterAssert(key); + // get cache Path for image key + NSString *cachePathForKey = [self cachePathForKey:key]; + + if (!extendedData) { + // Remove + [SDFileAttributeHelper removeExtendedAttribute:SDDiskCacheExtendedAttributeName atPath:cachePathForKey traverseLink:NO error:nil]; + } else { + // Override + [SDFileAttributeHelper setExtendedAttribute:SDDiskCacheExtendedAttributeName value:extendedData atPath:cachePathForKey traverseLink:NO overwrite:YES error:nil]; + } +} + +- (void)removeDataForKey:(NSString *)key { + NSParameterAssert(key); + NSString *filePath = [self cachePathForKey:key]; + [self.fileManager removeItemAtPath:filePath error:nil]; +} + +- (void)removeAllData { + [self.fileManager removeItemAtPath:self.diskCachePath error:nil]; + [self.fileManager createDirectoryAtPath:self.diskCachePath + withIntermediateDirectories:YES + attributes:nil + error:NULL]; +} + +- (void)removeExpiredData { + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + + // Compute content date key to be used for tests + NSURLResourceKey cacheContentDateKey = NSURLContentModificationDateKey; + switch (self.config.diskCacheExpireType) { + case SDImageCacheConfigExpireTypeAccessDate: + cacheContentDateKey = NSURLContentAccessDateKey; + break; + case SDImageCacheConfigExpireTypeModificationDate: + cacheContentDateKey = NSURLContentModificationDateKey; + break; + case SDImageCacheConfigExpireTypeCreationDate: + cacheContentDateKey = NSURLCreationDateKey; + break; + case SDImageCacheConfigExpireTypeChangeDate: + cacheContentDateKey = NSURLAttributeModificationDateKey; + break; + default: + break; + } + + NSArray *resourceKeys = @[NSURLIsDirectoryKey, cacheContentDateKey, NSURLTotalFileAllocatedSizeKey]; + + // This enumerator prefetches useful properties for our cache files. + NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL + includingPropertiesForKeys:resourceKeys + options:NSDirectoryEnumerationSkipsHiddenFiles + errorHandler:NULL]; + + NSDate *expirationDate = (self.config.maxDiskAge < 0) ? nil: [NSDate dateWithTimeIntervalSinceNow:-self.config.maxDiskAge]; + NSMutableDictionary *> *cacheFiles = [NSMutableDictionary dictionary]; + NSUInteger currentCacheSize = 0; + + // Enumerate all of the files in the cache directory. This loop has two purposes: + // + // 1. Removing files that are older than the expiration date. + // 2. Storing file attributes for the size-based cleanup pass. + NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init]; + for (NSURL *fileURL in fileEnumerator) { + NSError *error; + NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error]; + + // Skip directories and errors. + if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) { + continue; + } + + // Remove files that are older than the expiration date; + NSDate *modifiedDate = resourceValues[cacheContentDateKey]; + if (expirationDate && [[modifiedDate laterDate:expirationDate] isEqualToDate:expirationDate]) { + [urlsToDelete addObject:fileURL]; + continue; + } + + // Store a reference to this file and account for its total size. + NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; + currentCacheSize += totalAllocatedSize.unsignedIntegerValue; + cacheFiles[fileURL] = resourceValues; + } + + for (NSURL *fileURL in urlsToDelete) { + [self.fileManager removeItemAtURL:fileURL error:nil]; + } + + // If our remaining disk cache exceeds a configured maximum size, perform a second + // size-based cleanup pass. We delete the oldest files first. + NSUInteger maxDiskSize = self.config.maxDiskSize; + if (maxDiskSize > 0 && currentCacheSize > maxDiskSize) { + // Target half of our maximum cache size for this cleanup pass. + const NSUInteger desiredCacheSize = maxDiskSize / 2; + + // Sort the remaining cache files by their last modification time or last access time (oldest first). + NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent + usingComparator:^NSComparisonResult(id obj1, id obj2) { + return [obj1[cacheContentDateKey] compare:obj2[cacheContentDateKey]]; + }]; + + // Delete files until we fall below our desired cache size. + for (NSURL *fileURL in sortedFiles) { + if ([self.fileManager removeItemAtURL:fileURL error:nil]) { + NSDictionary *resourceValues = cacheFiles[fileURL]; + NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; + currentCacheSize -= totalAllocatedSize.unsignedIntegerValue; + + if (currentCacheSize < desiredCacheSize) { + break; + } + } + } + } +} + +- (nullable NSString *)cachePathForKey:(NSString *)key { + NSParameterAssert(key); + return [self cachePathForKey:key inPath:self.diskCachePath]; +} + +- (NSUInteger)totalSize { + NSUInteger size = 0; + NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtPath:self.diskCachePath]; + for (NSString *fileName in fileEnumerator) { + NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName]; + NSDictionary *attrs = [self.fileManager attributesOfItemAtPath:filePath error:nil]; + size += [attrs fileSize]; + } + return size; +} + +- (NSUInteger)totalCount { + NSUInteger count = 0; + NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtPath:self.diskCachePath]; + count = fileEnumerator.allObjects.count; + return count; +} + +#pragma mark - Cache paths + +- (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path { + NSString *filename = SDDiskCacheFileNameForKey(key); + return [path stringByAppendingPathComponent:filename]; +} + +- (void)moveCacheDirectoryFromPath:(nonnull NSString *)srcPath toPath:(nonnull NSString *)dstPath { + NSParameterAssert(srcPath); + NSParameterAssert(dstPath); + // Check if old path is equal to new path + if ([srcPath isEqualToString:dstPath]) { + return; + } + BOOL isDirectory; + // Check if old path is directory + if (![self.fileManager fileExistsAtPath:srcPath isDirectory:&isDirectory] || !isDirectory) { + return; + } + // Check if new path is directory + if (![self.fileManager fileExistsAtPath:dstPath isDirectory:&isDirectory] || !isDirectory) { + if (!isDirectory) { + // New path is not directory, remove file + [self.fileManager removeItemAtPath:dstPath error:nil]; + } + NSString *dstParentPath = [dstPath stringByDeletingLastPathComponent]; + // Creates any non-existent parent directories as part of creating the directory in path + if (![self.fileManager fileExistsAtPath:dstParentPath]) { + [self.fileManager createDirectoryAtPath:dstParentPath withIntermediateDirectories:YES attributes:nil error:NULL]; + } + // New directory does not exist, rename directory + [self.fileManager moveItemAtPath:srcPath toPath:dstPath error:nil]; + } else { + // New directory exist, merge the files + NSDirectoryEnumerator *dirEnumerator = [self.fileManager enumeratorAtPath:srcPath]; + NSString *file; + while ((file = [dirEnumerator nextObject])) { + [self.fileManager moveItemAtPath:[srcPath stringByAppendingPathComponent:file] toPath:[dstPath stringByAppendingPathComponent:file] error:nil]; + } + // Remove the old path + [self.fileManager removeItemAtPath:srcPath error:nil]; + } +} + +#pragma mark - Hash + +#define SD_MAX_FILE_EXTENSION_LENGTH (NAME_MAX - CC_MD5_DIGEST_LENGTH * 2 - 1) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +static inline NSString * _Nonnull SDDiskCacheFileNameForKey(NSString * _Nullable key) { + const char *str = key.UTF8String; + if (str == NULL) { + str = ""; + } + unsigned char r[CC_MD5_DIGEST_LENGTH]; + CC_MD5(str, (CC_LONG)strlen(str), r); + NSURL *keyURL = [NSURL URLWithString:key]; + NSString *ext = keyURL ? keyURL.pathExtension : key.pathExtension; + // File system has file name length limit, we need to check if ext is too long, we don't add it to the filename + if (ext.length > SD_MAX_FILE_EXTENSION_LENGTH) { + ext = nil; + } + NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@", + r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], + r[11], r[12], r[13], r[14], r[15], ext.length == 0 ? @"" : [NSString stringWithFormat:@".%@", ext]]; + return filename; +} +#pragma clang diagnostic pop + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.h new file mode 100644 index 0000000..900acd7 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.h @@ -0,0 +1,73 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDWebImageCompat.h" + +/** + These following class are provided to use `UIGraphicsImageRenderer` with polyfill, which allows write cross-platform(AppKit/UIKit) code and avoid runtime version check. + Compared to `UIGraphicsBeginImageContext`, `UIGraphicsImageRenderer` use dynamic bitmap from your draw code to generate CGContext, not always use ARGB8888, which is more performant on RAM usage. + Which means, if you draw CGImage/CIImage which contains grayscale only, the underlaying bitmap context use grayscale, it's managed by system and not a fixed type. (actually, the `kCGContextTypeAutomatic`) + For usage, See more in Apple's documentation: https://developer.apple.com/documentation/uikit/uigraphicsimagerenderer + For UIKit on iOS/tvOS 10+, these method just use the same `UIGraphicsImageRenderer` API. + For others (macOS/watchOS or iOS/tvOS 10-), these method use the `SDImageGraphics.h` to implements the same behavior (but without dynamic bitmap support) +*/ + +typedef void (^SDGraphicsImageDrawingActions)(CGContextRef _Nonnull context); +typedef NS_ENUM(NSInteger, SDGraphicsImageRendererFormatRange) { + SDGraphicsImageRendererFormatRangeUnspecified = -1, + SDGraphicsImageRendererFormatRangeAutomatic = 0, + SDGraphicsImageRendererFormatRangeExtended, + SDGraphicsImageRendererFormatRangeStandard +}; + +/// A set of drawing attributes that represent the configuration of an image renderer context. +@interface SDGraphicsImageRendererFormat : NSObject + +/// The display scale of the image renderer context. +/// The default value is equal to the scale of the main screen. +@property (nonatomic) CGFloat scale; + +/// A Boolean value indicating whether the underlying Core Graphics context has an alpha channel. +/// The default value is NO. +@property (nonatomic) BOOL opaque; + +/// Specifying whether the bitmap context should use extended color. +/// For iOS 12+, the value is from system `preferredRange` property +/// For iOS 10-11, the value is from system `prefersExtendedRange` property +/// For iOS 9-, the value is `.standard` +@property (nonatomic) SDGraphicsImageRendererFormatRange preferredRange; + +/// Init the default format. See each properties's default value. +- (nonnull instancetype)init; + +/// Returns a new format best suited for the main screen’s current configuration. ++ (nonnull instancetype)preferredFormat; + +@end + +/// A graphics renderer for creating Core Graphics-backed images. +@interface SDGraphicsImageRenderer : NSObject + +/// Creates an image renderer for drawing images of a given size. +/// @param size The size of images output from the renderer, specified in points. +/// @return An initialized image renderer. +- (nonnull instancetype)initWithSize:(CGSize)size; + +/// Creates a new image renderer with a given size and format. +/// @param size The size of images output from the renderer, specified in points. +/// @param format A SDGraphicsImageRendererFormat object that encapsulates the format used to create the renderer context. +/// @return An initialized image renderer. +- (nonnull instancetype)initWithSize:(CGSize)size format:(nonnull SDGraphicsImageRendererFormat *)format; + +/// Creates an image by following a set of drawing instructions. +/// @param actions A SDGraphicsImageDrawingActions block that, when invoked by the renderer, executes a set of drawing instructions to create the output image. +/// @note You should not retain or use the context outside the block, it's non-escaping. +/// @return A UIImage object created by the supplied drawing actions. +- (nonnull UIImage *)imageWithActions:(nonnull NS_NOESCAPE SDGraphicsImageDrawingActions)actions; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.m new file mode 100644 index 0000000..869de2c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDGraphicsImageRenderer.m @@ -0,0 +1,241 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDGraphicsImageRenderer.h" +#import "SDImageGraphics.h" + +@interface SDGraphicsImageRendererFormat () +#if SD_UIKIT +@property (nonatomic, strong) UIGraphicsImageRendererFormat *uiformat API_AVAILABLE(ios(10.0), tvos(10.0)); +#endif +@end + +@implementation SDGraphicsImageRendererFormat +@synthesize scale = _scale; +@synthesize opaque = _opaque; +@synthesize preferredRange = _preferredRange; + +#pragma mark - Property +- (CGFloat)scale { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + return self.uiformat.scale; + } else { + return _scale; + } +#else + return _scale; +#endif +} + +- (void)setScale:(CGFloat)scale { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + self.uiformat.scale = scale; + } else { + _scale = scale; + } +#else + _scale = scale; +#endif +} + +- (BOOL)opaque { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + return self.uiformat.opaque; + } else { + return _opaque; + } +#else + return _opaque; +#endif +} + +- (void)setOpaque:(BOOL)opaque { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + self.uiformat.opaque = opaque; + } else { + _opaque = opaque; + } +#else + _opaque = opaque; +#endif +} + +- (SDGraphicsImageRendererFormatRange)preferredRange { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + if (@available(iOS 12.0, tvOS 12.0, *)) { + return (SDGraphicsImageRendererFormatRange)self.uiformat.preferredRange; + } else { + BOOL prefersExtendedRange = self.uiformat.prefersExtendedRange; + if (prefersExtendedRange) { + return SDGraphicsImageRendererFormatRangeExtended; + } else { + return SDGraphicsImageRendererFormatRangeStandard; + } + } + } else { + return _preferredRange; + } +#else + return _preferredRange; +#endif +} + +- (void)setPreferredRange:(SDGraphicsImageRendererFormatRange)preferredRange { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + if (@available(iOS 12.0, tvOS 12.0, *)) { + self.uiformat.preferredRange = (UIGraphicsImageRendererFormatRange)preferredRange; + } else { + switch (preferredRange) { + case SDGraphicsImageRendererFormatRangeExtended: + self.uiformat.prefersExtendedRange = YES; + break; + case SDGraphicsImageRendererFormatRangeStandard: + self.uiformat.prefersExtendedRange = NO; + default: + // Automatic means default + break; + } + } + } else { + _preferredRange = preferredRange; + } +#else + _preferredRange = preferredRange; +#endif +} + +- (instancetype)init { + self = [super init]; + if (self) { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.10, *)) { + UIGraphicsImageRendererFormat *uiformat = [[UIGraphicsImageRendererFormat alloc] init]; + self.uiformat = uiformat; + } else { +#endif +#if SD_WATCH + CGFloat screenScale = [WKInterfaceDevice currentDevice].screenScale; +#elif SD_UIKIT + CGFloat screenScale = [UIScreen mainScreen].scale; +#elif SD_MAC + CGFloat screenScale = [NSScreen mainScreen].backingScaleFactor; +#endif + self.scale = screenScale; + self.opaque = NO; + self.preferredRange = SDGraphicsImageRendererFormatRangeStandard; +#if SD_UIKIT + } +#endif + } + return self; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (instancetype)initForMainScreen { + self = [super init]; + if (self) { +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.0, *)) { + UIGraphicsImageRendererFormat *uiformat; + // iOS 11.0.0 GM does have `preferredFormat`, but iOS 11 betas did not (argh!) + if ([UIGraphicsImageRenderer respondsToSelector:@selector(preferredFormat)]) { + uiformat = [UIGraphicsImageRendererFormat preferredFormat]; + } else { + uiformat = [UIGraphicsImageRendererFormat defaultFormat]; + } + self.uiformat = uiformat; + } else { +#endif +#if SD_WATCH + CGFloat screenScale = [WKInterfaceDevice currentDevice].screenScale; +#elif SD_UIKIT + CGFloat screenScale = [UIScreen mainScreen].scale; +#elif SD_MAC + CGFloat screenScale = [NSScreen mainScreen].backingScaleFactor; +#endif + self.scale = screenScale; + self.opaque = NO; + self.preferredRange = SDGraphicsImageRendererFormatRangeStandard; +#if SD_UIKIT + } +#endif + } + return self; +} +#pragma clang diagnostic pop + ++ (instancetype)preferredFormat { + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] initForMainScreen]; + return format; +} + +@end + +@interface SDGraphicsImageRenderer () +@property (nonatomic, assign) CGSize size; +@property (nonatomic, strong) SDGraphicsImageRendererFormat *format; +#if SD_UIKIT +@property (nonatomic, strong) UIGraphicsImageRenderer *uirenderer API_AVAILABLE(ios(10.0), tvos(10.0)); +#endif +@end + +@implementation SDGraphicsImageRenderer + +- (instancetype)initWithSize:(CGSize)size { + return [self initWithSize:size format:SDGraphicsImageRendererFormat.preferredFormat]; +} + +- (instancetype)initWithSize:(CGSize)size format:(SDGraphicsImageRendererFormat *)format { + NSParameterAssert(format); + self = [super init]; + if (self) { + self.size = size; + self.format = format; +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.0, *)) { + UIGraphicsImageRendererFormat *uiformat = format.uiformat; + self.uirenderer = [[UIGraphicsImageRenderer alloc] initWithSize:size format:uiformat]; + } +#endif + } + return self; +} + +- (UIImage *)imageWithActions:(NS_NOESCAPE SDGraphicsImageDrawingActions)actions { + NSParameterAssert(actions); +#if SD_UIKIT + if (@available(iOS 10.0, tvOS 10.0, *)) { + UIGraphicsImageDrawingActions uiactions = ^(UIGraphicsImageRendererContext *rendererContext) { + if (actions) { + actions(rendererContext.CGContext); + } + }; + return [self.uirenderer imageWithActions:uiactions]; + } else { +#endif + SDGraphicsBeginImageContextWithOptions(self.size, self.format.opaque, self.format.scale); + CGContextRef context = SDGraphicsGetCurrentContext(); + if (actions) { + actions(context); + } + UIImage *image = SDGraphicsGetImageFromCurrentImageContext(); + SDGraphicsEndImageContext(); + return image; +#if SD_UIKIT + } +#endif +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.h new file mode 100644 index 0000000..f73742c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.h @@ -0,0 +1,19 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageIOAnimatedCoder.h" + +/** + Built in coder using ImageIO that supports APNG encoding/decoding + */ +@interface SDImageAPNGCoder : SDImageIOAnimatedCoder + +@property (nonatomic, class, readonly, nonnull) SDImageAPNGCoder *sharedCoder; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.m new file mode 100644 index 0000000..a0700ab --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageAPNGCoder.m @@ -0,0 +1,65 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageAPNGCoder.h" +#if SD_MAC +#import +#else +#import +#endif + +// iOS 8 Image/IO framework binary does not contains these APNG contants, so we define them. Thanks Apple :) +// We can not use runtime @available check for this issue, because it's a global symbol and should be loaded during launch time by dyld. So hack if the min deployment target version < iOS 9.0, whatever it running on iOS 9+ or not. +#if (__IPHONE_OS_VERSION_MIN_REQUIRED && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_9_0) +const CFStringRef kCGImagePropertyAPNGLoopCount = (__bridge CFStringRef)@"LoopCount"; +const CFStringRef kCGImagePropertyAPNGDelayTime = (__bridge CFStringRef)@"DelayTime"; +const CFStringRef kCGImagePropertyAPNGUnclampedDelayTime = (__bridge CFStringRef)@"UnclampedDelayTime"; +#endif + +@implementation SDImageAPNGCoder + ++ (instancetype)sharedCoder { + static SDImageAPNGCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDImageAPNGCoder alloc] init]; + }); + return coder; +} + +#pragma mark - Subclass Override + ++ (SDImageFormat)imageFormat { + return SDImageFormatPNG; +} + ++ (NSString *)imageUTType { + return (__bridge NSString *)kUTTypePNG; +} + ++ (NSString *)dictionaryProperty { + return (__bridge NSString *)kCGImagePropertyPNGDictionary; +} + ++ (NSString *)unclampedDelayTimeProperty { + return (__bridge NSString *)kCGImagePropertyAPNGUnclampedDelayTime; +} + ++ (NSString *)delayTimeProperty { + return (__bridge NSString *)kCGImagePropertyAPNGDelayTime; +} + ++ (NSString *)loopCountProperty { + return (__bridge NSString *)kCGImagePropertyAPNGLoopCount; +} + ++ (NSUInteger)defaultLoopCount { + return 0; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCache.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCache.h new file mode 100644 index 0000000..688d3fc --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCache.h @@ -0,0 +1,369 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDImageCacheConfig.h" +#import "SDImageCacheDefine.h" +#import "SDMemoryCache.h" +#import "SDDiskCache.h" + +/// Image Cache Options +typedef NS_OPTIONS(NSUInteger, SDImageCacheOptions) { + /** + * By default, we do not query image data when the image is already cached in memory. This mask can force to query image data at the same time. However, this query is asynchronously unless you specify `SDImageCacheQueryMemoryDataSync` + */ + SDImageCacheQueryMemoryData = 1 << 0, + /** + * By default, when you only specify `SDImageCacheQueryMemoryData`, we query the memory image data asynchronously. Combined this mask as well to query the memory image data synchronously. + */ + SDImageCacheQueryMemoryDataSync = 1 << 1, + /** + * By default, when the memory cache miss, we query the disk cache asynchronously. This mask can force to query disk cache (when memory cache miss) synchronously. + @note These 3 query options can be combined together. For the full list about these masks combination, see wiki page. + */ + SDImageCacheQueryDiskDataSync = 1 << 2, + /** + * By default, images are decoded respecting their original size. On iOS, this flag will scale down the + * images to a size compatible with the constrained memory of devices. + */ + SDImageCacheScaleDownLargeImages = 1 << 3, + /** + * By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation. + * However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image. + */ + SDImageCacheAvoidDecodeImage = 1 << 4, + /** + * By default, we decode the animated image. This flag can force decode the first frame only and produece the static image. + */ + SDImageCacheDecodeFirstFrameOnly = 1 << 5, + /** + * By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. This flag actually trigger `preloadAllAnimatedImageFrames = YES` after image load from disk cache + */ + SDImageCachePreloadAllFrames = 1 << 6, + /** + * By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available, to behave as a fallback solution. + * Using this option, can ensure we always produce image with your provided class. If failed, a error with code `SDWebImageErrorBadImageData` will been used. + * Note this options is not compatible with `SDImageCacheDecodeFirstFrameOnly`, which always produce a UIImage/NSImage. + */ + SDImageCacheMatchAnimatedImageClass = 1 << 7, +}; + +/** + * SDImageCache maintains a memory cache and a disk cache. Disk cache write operations are performed + * asynchronous so it doesn’t add unnecessary latency to the UI. + */ +@interface SDImageCache : NSObject + +#pragma mark - Properties + +/** + * Cache Config object - storing all kind of settings. + * The property is copy so change of currrent config will not accidentally affect other cache's config. + */ +@property (nonatomic, copy, nonnull, readonly) SDImageCacheConfig *config; + +/** + * The memory cache implementation object used for current image cache. + * By default we use `SDMemoryCache` class, you can also use this to call your own implementation class method. + * @note To customize this class, check `SDImageCacheConfig.memoryCacheClass` property. + */ +@property (nonatomic, strong, readonly, nonnull) id memoryCache; + +/** + * The disk cache implementation object used for current image cache. + * By default we use `SDMemoryCache` class, you can also use this to call your own implementation class method. + * @note To customize this class, check `SDImageCacheConfig.diskCacheClass` property. + * @warning When calling method about read/write in disk cache, be sure to either make your disk cache implementation IO-safe or using the same access queue to avoid issues. + */ +@property (nonatomic, strong, readonly, nonnull) id diskCache; + +/** + * The disk cache's root path + */ +@property (nonatomic, copy, nonnull, readonly) NSString *diskCachePath; + +/** + * The additional disk cache path to check if the query from disk cache not exist; + * The `key` param is the image cache key. The returned file path will be used to load the disk cache. If return nil, ignore it. + * Useful if you want to bundle pre-loaded images with your app + */ +@property (nonatomic, copy, nullable) SDImageCacheAdditionalCachePathBlock additionalCachePathBlock; + +#pragma mark - Singleton and initialization + +/** + * Returns global shared cache instance + */ +@property (nonatomic, class, readonly, nonnull) SDImageCache *sharedImageCache; + +/** + * Init a new cache store with a specific namespace + * + * @param ns The namespace to use for this cache store + */ +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns; + +/** + * Init a new cache store with a specific namespace and directory. + * If you don't provide the disk cache directory, we will use the User Cache directory with prefix (~/Library/Caches/com.hackemist.SDImageCache/). + * + * @param ns The namespace to use for this cache store + * @param directory Directory to cache disk images in + */ +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns + diskCacheDirectory:(nullable NSString *)directory; + +/** + * Init a new cache store with a specific namespace, directory and file manager + * The final disk cache directory should looks like ($directory/$namespace). And the default config of shared cache, should result in (~/Library/Caches/com.hackemist.SDImageCache/default/) + * + * @param ns The namespace to use for this cache store + * @param directory Directory to cache disk images in + * @param config The cache config to be used to create the cache. You can provide custom memory cache or disk cache class in the cache config + */ +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns + diskCacheDirectory:(nullable NSString *)directory + config:(nullable SDImageCacheConfig *)config NS_DESIGNATED_INITIALIZER; + +#pragma mark - Cache paths + +/** + Get the cache path for a certain key + + @param key The unique image cache key + @return The cache path. You can check `lastPathComponent` to grab the file name. + */ +- (nullable NSString *)cachePathForKey:(nullable NSString *)key; + +#pragma mark - Store Ops + +/** + * Asynchronously store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + * @param completionBlock A block executed after the operation is finished + */ +- (void)storeImage:(nullable UIImage *)image + forKey:(nullable NSString *)key + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + * Asynchronously store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES. If NO, the completion block is called synchronously + * @param completionBlock A block executed after the operation is finished + */ +- (void)storeImage:(nullable UIImage *)image + forKey:(nullable NSString *)key + toDisk:(BOOL)toDisk + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + * Asynchronously store an image into memory and disk cache at the given key. + * + * @param image The image to store + * @param imageData The image data as returned by the server, this representation will be used for disk storage + * instead of converting the given image object into a storable/compressed image format in order + * to save quality and CPU + * @param key The unique image cache key, usually it's image absolute URL + * @param toDisk Store the image to disk cache if YES. If NO, the completion block is called synchronously + * @param completionBlock A block executed after the operation is finished + */ +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + toDisk:(BOOL)toDisk + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + * Synchronously store image into memory cache at the given key. + * + * @param image The image to store + * @param key The unique image cache key, usually it's image absolute URL + */ +- (void)storeImageToMemory:(nullable UIImage*)image + forKey:(nullable NSString *)key; + +/** + * Synchronously store image data into disk cache at the given key. + * + * @param imageData The image data to store + * @param key The unique image cache key, usually it's image absolute URL + */ +- (void)storeImageDataToDisk:(nullable NSData *)imageData + forKey:(nullable NSString *)key; + + +#pragma mark - Contains and Check Ops + +/** + * Asynchronously check if image exists in disk cache already (does not load the image) + * + * @param key the key describing the url + * @param completionBlock the block to be executed when the check is done. + * @note the completion block will be always executed on the main queue + */ +- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDImageCacheCheckCompletionBlock)completionBlock; + +/** + * Synchronously check if image data exists in disk cache already (does not load the image) + * + * @param key the key describing the url + */ +- (BOOL)diskImageDataExistsWithKey:(nullable NSString *)key; + +#pragma mark - Query and Retrieve Ops + +/** + * Asynchronously queries the cache with operation and call the completion when done. + * Query the image data for the given key synchronously. + * + * @param key The unique key used to store the wanted image + * @return The image data for the given key, or nil if not found. + */ +- (nullable NSData *)diskImageDataForKey:(nullable NSString *)key; + +/** + * Operation that queries the cache asynchronously and call the completion when done. + * + * @param key The unique key used to store the wanted image + * @param doneBlock The completion block. Will not get called if the operation is cancelled + * + * @return a NSOperation instance containing the cache op + */ +- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDImageCacheQueryCompletionBlock)doneBlock; + +/** + * Asynchronously queries the cache with operation and call the completion when done. + * + * @param key The unique key used to store the wanted image + * @param options A mask to specify options to use for this cache query + * @param doneBlock The completion block. Will not get called if the operation is cancelled + * + * @return a NSOperation instance containing the cache op + */ +- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options done:(nullable SDImageCacheQueryCompletionBlock)doneBlock; + +/** + * Asynchronously queries the cache with operation and call the completion when done. + * + * @param key The unique key used to store the wanted image + * @param options A mask to specify options to use for this cache query + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param doneBlock The completion block. Will not get called if the operation is cancelled + * + * @return a NSOperation instance containing the cache op + */ +- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context done:(nullable SDImageCacheQueryCompletionBlock)doneBlock; + +/** + * Synchronously query the memory cache. + * + * @param key The unique key used to store the image + * @return The image for the given key, or nil if not found. + */ +- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key; + +/** + * Synchronously query the disk cache. + * + * @param key The unique key used to store the image + * @return The image for the given key, or nil if not found. + */ +- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key; + +/** + * Synchronously query the cache (memory and or disk) after checking the memory cache. + * + * @param key The unique key used to store the image + * @return The image for the given key, or nil if not found. + */ +- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key; + +#pragma mark - Remove Ops + +/** + * Asynchronously remove the image from memory and disk cache + * + * @param key The unique image cache key + * @param completion A block that should be executed after the image has been removed (optional) + */ +- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion; + +/** + * Asynchronously remove the image from memory and optionally disk cache + * + * @param key The unique image cache key + * @param fromDisk Also remove cache entry from disk if YES. If NO, the completion block is called synchronously + * @param completion A block that should be executed after the image has been removed (optional) + */ +- (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion; + +/** + Synchronously remove the image from memory cache. + + @param key The unique image cache key + */ +- (void)removeImageFromMemoryForKey:(nullable NSString *)key; + +/** + Synchronously remove the image from disk cache. + + @param key The unique image cache key + */ +- (void)removeImageFromDiskForKey:(nullable NSString *)key; + +#pragma mark - Cache clean Ops + +/** + * Synchronously Clear all memory cached images + */ +- (void)clearMemory; + +/** + * Asynchronously clear all disk cached images. Non-blocking method - returns immediately. + * @param completion A block that should be executed after cache expiration completes (optional) + */ +- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion; + +/** + * Asynchronously remove all expired cached image from disk. Non-blocking method - returns immediately. + * @param completionBlock A block that should be executed after cache expiration completes (optional) + */ +- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock; + +#pragma mark - Cache Info + +/** + * Get the total bytes size of images in the disk cache + */ +- (NSUInteger)totalDiskSize; + +/** + * Get the number of images in the disk cache + */ +- (NSUInteger)totalDiskCount; + +/** + * Asynchronously calculate the disk cache's size. + */ +- (void)calculateSizeWithCompletionBlock:(nullable SDImageCacheCalculateSizeBlock)completionBlock; + +@end + +/** + * SDImageCache is the built-in image cache implementation for web image manager. It adopts `SDImageCache` protocol to provide the function for web image manager to use for image loading process. + */ +@interface SDImageCache (SDImageCache) + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCache.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCache.m new file mode 100644 index 0000000..362a299 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCache.m @@ -0,0 +1,831 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCache.h" +#import "NSImage+Compatibility.h" +#import "SDImageCodersManager.h" +#import "SDImageTransformer.h" +#import "SDImageCoderHelper.h" +#import "SDAnimatedImage.h" +#import "UIImage+MemoryCacheCost.h" +#import "UIImage+Metadata.h" +#import "UIImage+ExtendedCacheData.h" + +@interface SDImageCache () + +#pragma mark - Properties +@property (nonatomic, strong, readwrite, nonnull) id memoryCache; +@property (nonatomic, strong, readwrite, nonnull) id diskCache; +@property (nonatomic, copy, readwrite, nonnull) SDImageCacheConfig *config; +@property (nonatomic, copy, readwrite, nonnull) NSString *diskCachePath; +@property (nonatomic, strong, nullable) dispatch_queue_t ioQueue; + +@end + + +@implementation SDImageCache + +#pragma mark - Singleton, init, dealloc + ++ (nonnull instancetype)sharedImageCache { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (instancetype)init { + return [self initWithNamespace:@"default"]; +} + +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns { + return [self initWithNamespace:ns diskCacheDirectory:nil]; +} + +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns + diskCacheDirectory:(nullable NSString *)directory { + return [self initWithNamespace:ns diskCacheDirectory:directory config:SDImageCacheConfig.defaultCacheConfig]; +} + +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns + diskCacheDirectory:(nullable NSString *)directory + config:(nullable SDImageCacheConfig *)config { + if ((self = [super init])) { + NSAssert(ns, @"Cache namespace should not be nil"); + + // Create IO serial queue + _ioQueue = dispatch_queue_create("com.hackemist.SDImageCache", DISPATCH_QUEUE_SERIAL); + + if (!config) { + config = SDImageCacheConfig.defaultCacheConfig; + } + _config = [config copy]; + + // Init the memory cache + NSAssert([config.memoryCacheClass conformsToProtocol:@protocol(SDMemoryCache)], @"Custom memory cache class must conform to `SDMemoryCache` protocol"); + _memoryCache = [[config.memoryCacheClass alloc] initWithConfig:_config]; + + // Init the disk cache + if (directory != nil) { + _diskCachePath = [directory stringByAppendingPathComponent:ns]; + } else { + NSString *path = [[[self userCacheDirectory] stringByAppendingPathComponent:@"com.hackemist.SDImageCache"] stringByAppendingPathComponent:ns]; + _diskCachePath = path; + } + + NSAssert([config.diskCacheClass conformsToProtocol:@protocol(SDDiskCache)], @"Custom disk cache class must conform to `SDDiskCache` protocol"); + _diskCache = [[config.diskCacheClass alloc] initWithCachePath:_diskCachePath config:_config]; + + // Check and migrate disk cache directory if need + [self migrateDiskCacheDirectory]; + +#if SD_UIKIT + // Subscribe to app events + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(applicationWillTerminate:) + name:UIApplicationWillTerminateNotification + object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(applicationDidEnterBackground:) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; +#endif +#if SD_MAC + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(applicationWillTerminate:) + name:NSApplicationWillTerminateNotification + object:nil]; +#endif + } + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - Cache paths + +- (nullable NSString *)cachePathForKey:(nullable NSString *)key { + if (!key) { + return nil; + } + return [self.diskCache cachePathForKey:key]; +} + +- (nullable NSString *)userCacheDirectory { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + return paths.firstObject; +} + +- (void)migrateDiskCacheDirectory { + if ([self.diskCache isKindOfClass:[SDDiskCache class]]) { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // ~/Library/Caches/com.hackemist.SDImageCache/default/ + NSString *newDefaultPath = [[[self userCacheDirectory] stringByAppendingPathComponent:@"com.hackemist.SDImageCache"] stringByAppendingPathComponent:@"default"]; + // ~/Library/Caches/default/com.hackemist.SDWebImageCache.default/ + NSString *oldDefaultPath = [[[self userCacheDirectory] stringByAppendingPathComponent:@"default"] stringByAppendingPathComponent:@"com.hackemist.SDWebImageCache.default"]; + dispatch_async(self.ioQueue, ^{ + [((SDDiskCache *)self.diskCache) moveCacheDirectoryFromPath:oldDefaultPath toPath:newDefaultPath]; + }); + }); + } +} + +#pragma mark - Store Ops + +- (void)storeImage:(nullable UIImage *)image + forKey:(nullable NSString *)key + completion:(nullable SDWebImageNoParamsBlock)completionBlock { + [self storeImage:image imageData:nil forKey:key toDisk:YES completion:completionBlock]; +} + +- (void)storeImage:(nullable UIImage *)image + forKey:(nullable NSString *)key + toDisk:(BOOL)toDisk + completion:(nullable SDWebImageNoParamsBlock)completionBlock { + [self storeImage:image imageData:nil forKey:key toDisk:toDisk completion:completionBlock]; +} + +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + toDisk:(BOOL)toDisk + completion:(nullable SDWebImageNoParamsBlock)completionBlock { + return [self storeImage:image imageData:imageData forKey:key toMemory:YES toDisk:toDisk completion:completionBlock]; +} + +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + toMemory:(BOOL)toMemory + toDisk:(BOOL)toDisk + completion:(nullable SDWebImageNoParamsBlock)completionBlock { + if (!image || !key) { + if (completionBlock) { + completionBlock(); + } + return; + } + // if memory cache is enabled + if (toMemory && self.config.shouldCacheImagesInMemory) { + NSUInteger cost = image.sd_memoryCost; + [self.memoryCache setObject:image forKey:key cost:cost]; + } + + if (toDisk) { + dispatch_async(self.ioQueue, ^{ + @autoreleasepool { + NSData *data = imageData; + if (!data && image) { + // If we do not have any data to detect image format, check whether it contains alpha channel to use PNG or JPEG format + SDImageFormat format; + if ([SDImageCoderHelper CGImageContainsAlpha:image.CGImage]) { + format = SDImageFormatPNG; + } else { + format = SDImageFormatJPEG; + } + data = [[SDImageCodersManager sharedManager] encodedDataWithImage:image format:format options:nil]; + } + [self _storeImageDataToDisk:data forKey:key]; + if (image) { + // Check extended data + id extendedObject = image.sd_extendedObject; + if ([extendedObject conformsToProtocol:@protocol(NSCoding)]) { + NSData *extendedData; + if (@available(iOS 11, tvOS 11, macOS 10.13, watchOS 4, *)) { + NSError *error; + extendedData = [NSKeyedArchiver archivedDataWithRootObject:extendedObject requiringSecureCoding:NO error:&error]; + if (error) { + NSLog(@"NSKeyedArchiver archive failed with error: %@", error); + } + } else { + @try { + extendedData = [NSKeyedArchiver archivedDataWithRootObject:extendedObject]; + } @catch (NSException *exception) { + NSLog(@"NSKeyedArchiver archive failed with exception: %@", exception); + } + } + if (extendedData) { + [self.diskCache setExtendedData:extendedData forKey:key]; + } + } + } + } + + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(); + }); + } + }); + } else { + if (completionBlock) { + completionBlock(); + } + } +} + +- (void)storeImageToMemory:(UIImage *)image forKey:(NSString *)key { + if (!image || !key) { + return; + } + NSUInteger cost = image.sd_memoryCost; + [self.memoryCache setObject:image forKey:key cost:cost]; +} + +- (void)storeImageDataToDisk:(nullable NSData *)imageData + forKey:(nullable NSString *)key { + if (!imageData || !key) { + return; + } + + dispatch_sync(self.ioQueue, ^{ + [self _storeImageDataToDisk:imageData forKey:key]; + }); +} + +// Make sure to call form io queue by caller +- (void)_storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key { + if (!imageData || !key) { + return; + } + + [self.diskCache setData:imageData forKey:key]; +} + +#pragma mark - Query and Retrieve Ops + +- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDImageCacheCheckCompletionBlock)completionBlock { + dispatch_async(self.ioQueue, ^{ + BOOL exists = [self _diskImageDataExistsWithKey:key]; + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(exists); + }); + } + }); +} + +- (BOOL)diskImageDataExistsWithKey:(nullable NSString *)key { + if (!key) { + return NO; + } + + __block BOOL exists = NO; + dispatch_sync(self.ioQueue, ^{ + exists = [self _diskImageDataExistsWithKey:key]; + }); + + return exists; +} + +// Make sure to call form io queue by caller +- (BOOL)_diskImageDataExistsWithKey:(nullable NSString *)key { + if (!key) { + return NO; + } + + return [self.diskCache containsDataForKey:key]; +} + +- (nullable NSData *)diskImageDataForKey:(nullable NSString *)key { + if (!key) { + return nil; + } + __block NSData *imageData = nil; + dispatch_sync(self.ioQueue, ^{ + imageData = [self diskImageDataBySearchingAllPathsForKey:key]; + }); + + return imageData; +} + +- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key { + return [self.memoryCache objectForKey:key]; +} + +- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key { + UIImage *diskImage = [self diskImageForKey:key]; + if (diskImage && self.config.shouldCacheImagesInMemory) { + NSUInteger cost = diskImage.sd_memoryCost; + [self.memoryCache setObject:diskImage forKey:key cost:cost]; + } + + return diskImage; +} + +- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key { + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + if (image) { + return image; + } + + // Second check the disk cache... + image = [self imageFromDiskCacheForKey:key]; + return image; +} + +- (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key { + if (!key) { + return nil; + } + + NSData *data = [self.diskCache dataForKey:key]; + if (data) { + return data; + } + + // Addtional cache path for custom pre-load cache + if (self.additionalCachePathBlock) { + NSString *filePath = self.additionalCachePathBlock(key); + if (filePath) { + data = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil]; + } + } + + return data; +} + +- (nullable UIImage *)diskImageForKey:(nullable NSString *)key { + NSData *data = [self diskImageDataForKey:key]; + return [self diskImageForKey:key data:data]; +} + +- (nullable UIImage *)diskImageForKey:(nullable NSString *)key data:(nullable NSData *)data { + return [self diskImageForKey:key data:data options:0 context:nil]; +} + +- (nullable UIImage *)diskImageForKey:(nullable NSString *)key data:(nullable NSData *)data options:(SDImageCacheOptions)options context:(SDWebImageContext *)context { + if (data) { + UIImage *image = SDImageCacheDecodeImageData(data, key, [[self class] imageOptionsFromCacheOptions:options], context); + if (image) { + // Check extended data + NSData *extendedData = [self.diskCache extendedDataForKey:key]; + if (extendedData) { + id extendedObject; + if (@available(iOS 11, tvOS 11, macOS 10.13, watchOS 4, *)) { + NSError *error; + NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:extendedData error:&error]; + unarchiver.requiresSecureCoding = NO; + extendedObject = [unarchiver decodeTopLevelObjectForKey:NSKeyedArchiveRootObjectKey error:&error]; + if (error) { + NSLog(@"NSKeyedUnarchiver unarchive failed with error: %@", error); + } + } else { + @try { + extendedObject = [NSKeyedUnarchiver unarchiveObjectWithData:extendedData]; + } @catch (NSException *exception) { + NSLog(@"NSKeyedUnarchiver unarchive failed with exception: %@", exception); + } + } + image.sd_extendedObject = extendedObject; + } + } + return image; + } else { + return nil; + } +} + +- (nullable NSOperation *)queryCacheOperationForKey:(NSString *)key done:(SDImageCacheQueryCompletionBlock)doneBlock { + return [self queryCacheOperationForKey:key options:0 done:doneBlock]; +} + +- (nullable NSOperation *)queryCacheOperationForKey:(NSString *)key options:(SDImageCacheOptions)options done:(SDImageCacheQueryCompletionBlock)doneBlock { + return [self queryCacheOperationForKey:key options:options context:nil done:doneBlock]; +} + +- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context done:(nullable SDImageCacheQueryCompletionBlock)doneBlock { + if (!key) { + if (doneBlock) { + doneBlock(nil, nil, SDImageCacheTypeNone); + } + return nil; + } + + id transformer = context[SDWebImageContextImageTransformer]; + if (transformer) { + // grab the transformed disk image if transformer provided + NSString *transformerKey = [transformer transformerKey]; + key = SDTransformedKeyForKey(key, transformerKey); + } + + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + + if (image) { + if (options & SDImageCacheDecodeFirstFrameOnly) { + // Ensure static image + Class animatedImageClass = image.class; + if (image.sd_isAnimated || ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)])) { +#if SD_MAC + image = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp]; +#else + image = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation]; +#endif + } + } else if (options & SDImageCacheMatchAnimatedImageClass) { + // Check image class matching + Class animatedImageClass = image.class; + Class desiredImageClass = context[SDWebImageContextAnimatedImageClass]; + if (desiredImageClass && ![animatedImageClass isSubclassOfClass:desiredImageClass]) { + image = nil; + } + } + } + + BOOL shouldQueryMemoryOnly = (image && !(options & SDImageCacheQueryMemoryData)); + if (shouldQueryMemoryOnly) { + if (doneBlock) { + doneBlock(image, nil, SDImageCacheTypeMemory); + } + return nil; + } + + // Second check the disk cache... + NSOperation *operation = [NSOperation new]; + // Check whether we need to synchronously query disk + // 1. in-memory cache hit & memoryDataSync + // 2. in-memory cache miss & diskDataSync + BOOL shouldQueryDiskSync = ((image && options & SDImageCacheQueryMemoryDataSync) || + (!image && options & SDImageCacheQueryDiskDataSync)); + void(^queryDiskBlock)(void) = ^{ + if (operation.isCancelled) { + if (doneBlock) { + doneBlock(nil, nil, SDImageCacheTypeNone); + } + return; + } + + @autoreleasepool { + NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key]; + UIImage *diskImage; + SDImageCacheType cacheType = SDImageCacheTypeNone; + if (image) { + // the image is from in-memory cache, but need image data + diskImage = image; + cacheType = SDImageCacheTypeMemory; + } else if (diskData) { + cacheType = SDImageCacheTypeDisk; + // decode image data only if in-memory cache missed + diskImage = [self diskImageForKey:key data:diskData options:options context:context]; + if (diskImage && self.config.shouldCacheImagesInMemory) { + NSUInteger cost = diskImage.sd_memoryCost; + [self.memoryCache setObject:diskImage forKey:key cost:cost]; + } + } + + if (doneBlock) { + if (shouldQueryDiskSync) { + doneBlock(diskImage, diskData, cacheType); + } else { + dispatch_async(dispatch_get_main_queue(), ^{ + doneBlock(diskImage, diskData, cacheType); + }); + } + } + } + }; + + // Query in ioQueue to keep IO-safe + if (shouldQueryDiskSync) { + dispatch_sync(self.ioQueue, queryDiskBlock); + } else { + dispatch_async(self.ioQueue, queryDiskBlock); + } + + return operation; +} + +#pragma mark - Remove Ops + +- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion { + [self removeImageForKey:key fromDisk:YES withCompletion:completion]; +} + +- (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion { + [self removeImageForKey:key fromMemory:YES fromDisk:fromDisk withCompletion:completion]; +} + +- (void)removeImageForKey:(nullable NSString *)key fromMemory:(BOOL)fromMemory fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion { + if (key == nil) { + return; + } + + if (fromMemory && self.config.shouldCacheImagesInMemory) { + [self.memoryCache removeObjectForKey:key]; + } + + if (fromDisk) { + dispatch_async(self.ioQueue, ^{ + [self.diskCache removeDataForKey:key]; + + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(); + }); + } + }); + } else if (completion) { + completion(); + } +} + +- (void)removeImageFromMemoryForKey:(NSString *)key { + if (!key) { + return; + } + + [self.memoryCache removeObjectForKey:key]; +} + +- (void)removeImageFromDiskForKey:(NSString *)key { + if (!key) { + return; + } + dispatch_sync(self.ioQueue, ^{ + [self _removeImageFromDiskForKey:key]; + }); +} + +// Make sure to call form io queue by caller +- (void)_removeImageFromDiskForKey:(NSString *)key { + if (!key) { + return; + } + + [self.diskCache removeDataForKey:key]; +} + +#pragma mark - Cache clean Ops + +- (void)clearMemory { + [self.memoryCache removeAllObjects]; +} + +- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion { + dispatch_async(self.ioQueue, ^{ + [self.diskCache removeAllData]; + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(); + }); + } + }); +} + +- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock { + dispatch_async(self.ioQueue, ^{ + [self.diskCache removeExpiredData]; + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(); + }); + } + }); +} + +#pragma mark - UIApplicationWillTerminateNotification + +#if SD_UIKIT || SD_MAC +- (void)applicationWillTerminate:(NSNotification *)notification { + [self deleteOldFilesWithCompletionBlock:nil]; +} +#endif + +#pragma mark - UIApplicationDidEnterBackgroundNotification + +#if SD_UIKIT +- (void)applicationDidEnterBackground:(NSNotification *)notification { + if (!self.config.shouldRemoveExpiredDataWhenEnterBackground) { + return; + } + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { + return; + } + UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)]; + __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ + // Clean up any unfinished task business by marking where you + // stopped or ending the task outright. + [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid; + }]; + + // Start the long-running task and return immediately. + [self deleteOldFilesWithCompletionBlock:^{ + [application endBackgroundTask:bgTask]; + bgTask = UIBackgroundTaskInvalid; + }]; +} +#endif + +#pragma mark - Cache Info + +- (NSUInteger)totalDiskSize { + __block NSUInteger size = 0; + dispatch_sync(self.ioQueue, ^{ + size = [self.diskCache totalSize]; + }); + return size; +} + +- (NSUInteger)totalDiskCount { + __block NSUInteger count = 0; + dispatch_sync(self.ioQueue, ^{ + count = [self.diskCache totalCount]; + }); + return count; +} + +- (void)calculateSizeWithCompletionBlock:(nullable SDImageCacheCalculateSizeBlock)completionBlock { + dispatch_async(self.ioQueue, ^{ + NSUInteger fileCount = [self.diskCache totalCount]; + NSUInteger totalSize = [self.diskCache totalSize]; + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(fileCount, totalSize); + }); + } + }); +} + +#pragma mark - Helper ++ (SDWebImageOptions)imageOptionsFromCacheOptions:(SDImageCacheOptions)cacheOptions { + SDWebImageOptions options = 0; + if (cacheOptions & SDImageCacheScaleDownLargeImages) options |= SDWebImageScaleDownLargeImages; + if (cacheOptions & SDImageCacheDecodeFirstFrameOnly) options |= SDWebImageDecodeFirstFrameOnly; + if (cacheOptions & SDImageCachePreloadAllFrames) options |= SDWebImagePreloadAllFrames; + if (cacheOptions & SDImageCacheAvoidDecodeImage) options |= SDWebImageAvoidDecodeImage; + if (cacheOptions & SDImageCacheMatchAnimatedImageClass) options |= SDWebImageMatchAnimatedImageClass; + + return options; +} + +@end + +@implementation SDImageCache (SDImageCache) + +#pragma mark - SDImageCache + +- (id)queryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context completion:(nullable SDImageCacheQueryCompletionBlock)completionBlock { + SDImageCacheOptions cacheOptions = 0; + if (options & SDWebImageQueryMemoryData) cacheOptions |= SDImageCacheQueryMemoryData; + if (options & SDWebImageQueryMemoryDataSync) cacheOptions |= SDImageCacheQueryMemoryDataSync; + if (options & SDWebImageQueryDiskDataSync) cacheOptions |= SDImageCacheQueryDiskDataSync; + if (options & SDWebImageScaleDownLargeImages) cacheOptions |= SDImageCacheScaleDownLargeImages; + if (options & SDWebImageAvoidDecodeImage) cacheOptions |= SDImageCacheAvoidDecodeImage; + if (options & SDWebImageDecodeFirstFrameOnly) cacheOptions |= SDImageCacheDecodeFirstFrameOnly; + if (options & SDWebImagePreloadAllFrames) cacheOptions |= SDImageCachePreloadAllFrames; + if (options & SDWebImageMatchAnimatedImageClass) cacheOptions |= SDImageCacheMatchAnimatedImageClass; + + return [self queryCacheOperationForKey:key options:cacheOptions context:context done:completionBlock]; +} + +- (void)storeImage:(UIImage *)image imageData:(NSData *)imageData forKey:(nullable NSString *)key cacheType:(SDImageCacheType)cacheType completion:(nullable SDWebImageNoParamsBlock)completionBlock { + switch (cacheType) { + case SDImageCacheTypeNone: { + [self storeImage:image imageData:imageData forKey:key toMemory:NO toDisk:NO completion:completionBlock]; + } + break; + case SDImageCacheTypeMemory: { + [self storeImage:image imageData:imageData forKey:key toMemory:YES toDisk:NO completion:completionBlock]; + } + break; + case SDImageCacheTypeDisk: { + [self storeImage:image imageData:imageData forKey:key toMemory:NO toDisk:YES completion:completionBlock]; + } + break; + case SDImageCacheTypeAll: { + [self storeImage:image imageData:imageData forKey:key toMemory:YES toDisk:YES completion:completionBlock]; + } + break; + default: { + if (completionBlock) { + completionBlock(); + } + } + break; + } +} + +- (void)removeImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(nullable SDWebImageNoParamsBlock)completionBlock { + switch (cacheType) { + case SDImageCacheTypeNone: { + [self removeImageForKey:key fromMemory:NO fromDisk:NO withCompletion:completionBlock]; + } + break; + case SDImageCacheTypeMemory: { + [self removeImageForKey:key fromMemory:YES fromDisk:NO withCompletion:completionBlock]; + } + break; + case SDImageCacheTypeDisk: { + [self removeImageForKey:key fromMemory:NO fromDisk:YES withCompletion:completionBlock]; + } + break; + case SDImageCacheTypeAll: { + [self removeImageForKey:key fromMemory:YES fromDisk:YES withCompletion:completionBlock]; + } + break; + default: { + if (completionBlock) { + completionBlock(); + } + } + break; + } +} + +- (void)containsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(nullable SDImageCacheContainsCompletionBlock)completionBlock { + switch (cacheType) { + case SDImageCacheTypeNone: { + if (completionBlock) { + completionBlock(SDImageCacheTypeNone); + } + } + break; + case SDImageCacheTypeMemory: { + BOOL isInMemoryCache = ([self imageFromMemoryCacheForKey:key] != nil); + if (completionBlock) { + completionBlock(isInMemoryCache ? SDImageCacheTypeMemory : SDImageCacheTypeNone); + } + } + break; + case SDImageCacheTypeDisk: { + [self diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { + if (completionBlock) { + completionBlock(isInDiskCache ? SDImageCacheTypeDisk : SDImageCacheTypeNone); + } + }]; + } + break; + case SDImageCacheTypeAll: { + BOOL isInMemoryCache = ([self imageFromMemoryCacheForKey:key] != nil); + if (isInMemoryCache) { + if (completionBlock) { + completionBlock(SDImageCacheTypeMemory); + } + return; + } + [self diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { + if (completionBlock) { + completionBlock(isInDiskCache ? SDImageCacheTypeDisk : SDImageCacheTypeNone); + } + }]; + } + break; + default: + if (completionBlock) { + completionBlock(SDImageCacheTypeNone); + } + break; + } +} + +- (void)clearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock { + switch (cacheType) { + case SDImageCacheTypeNone: { + if (completionBlock) { + completionBlock(); + } + } + break; + case SDImageCacheTypeMemory: { + [self clearMemory]; + if (completionBlock) { + completionBlock(); + } + } + break; + case SDImageCacheTypeDisk: { + [self clearDiskOnCompletion:completionBlock]; + } + break; + case SDImageCacheTypeAll: { + [self clearMemory]; + [self clearDiskOnCompletion:completionBlock]; + } + break; + default: { + if (completionBlock) { + completionBlock(); + } + } + break; + } +} + +@end + diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.h new file mode 100644 index 0000000..e77e128 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.h @@ -0,0 +1,137 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/// Image Cache Expire Type +typedef NS_ENUM(NSUInteger, SDImageCacheConfigExpireType) { + /** + * When the image cache is accessed it will update this value + */ + SDImageCacheConfigExpireTypeAccessDate, + /** + * When the image cache is created or modified it will update this value (Default) + */ + SDImageCacheConfigExpireTypeModificationDate, + /** + * When the image cache is created it will update this value + */ + SDImageCacheConfigExpireTypeCreationDate, + /** + * When the image cache is created, modified, renamed, file attribute updated (like permission, xattr) it will update this value + */ + SDImageCacheConfigExpireTypeChangeDate, +}; + +/** + The class contains all the config for image cache + @note This class conform to NSCopying, make sure to add the property in `copyWithZone:` as well. + */ +@interface SDImageCacheConfig : NSObject + +/** + Gets the default cache config used for shared instance or initialization when it does not provide any cache config. Such as `SDImageCache.sharedImageCache`. + @note You can modify the property on default cache config, which can be used for later created cache instance. The already created cache instance does not get affected. + */ +@property (nonatomic, class, readonly, nonnull) SDImageCacheConfig *defaultCacheConfig; + +/** + * Whether or not to disable iCloud backup + * Defaults to YES. + */ +@property (assign, nonatomic) BOOL shouldDisableiCloud; + +/** + * Whether or not to use memory cache + * @note When the memory cache is disabled, the weak memory cache will also be disabled. + * Defaults to YES. + */ +@property (assign, nonatomic) BOOL shouldCacheImagesInMemory; + +/* + * The option to control weak memory cache for images. When enable, `SDImageCache`'s memory cache will use a weak maptable to store the image at the same time when it stored to memory, and get removed at the same time. + * However when memory warning is triggered, since the weak maptable does not hold a strong reference to image instance, even when the memory cache itself is purged, some images which are held strongly by UIImageViews or other live instances can be recovered again, to avoid later re-query from disk cache or network. This may be helpful for the case, for example, when app enter background and memory is purged, cause cell flashing after re-enter foreground. + * Defautls to YES. You can change this option dynamically. + */ +@property (assign, nonatomic) BOOL shouldUseWeakMemoryCache; + +/** + * Whether or not to remove the expired disk data when application entering the background. (Not works for macOS) + * Defaults to YES. + */ +@property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenEnterBackground; + +/** + * The reading options while reading cache from disk. + * Defaults to 0. You can set this to `NSDataReadingMappedIfSafe` to improve performance. + */ +@property (assign, nonatomic) NSDataReadingOptions diskCacheReadingOptions; + +/** + * The writing options while writing cache to disk. + * Defaults to `NSDataWritingAtomic`. You can set this to `NSDataWritingWithoutOverwriting` to prevent overwriting an existing file. + */ +@property (assign, nonatomic) NSDataWritingOptions diskCacheWritingOptions; + +/** + * The maximum length of time to keep an image in the disk cache, in seconds. + * Setting this to a negative value means no expiring. + * Setting this to zero means that all cached files would be removed when do expiration check. + * Defaults to 1 week. + */ +@property (assign, nonatomic) NSTimeInterval maxDiskAge; + +/** + * The maximum size of the disk cache, in bytes. + * Defaults to 0. Which means there is no cache size limit. + */ +@property (assign, nonatomic) NSUInteger maxDiskSize; + +/** + * The maximum "total cost" of the in-memory image cache. The cost function is the bytes size held in memory. + * @note The memory cost is bytes size in memory, but not simple pixels count. For common ARGB8888 image, one pixel is 4 bytes (32 bits). + * Defaults to 0. Which means there is no memory cost limit. + */ +@property (assign, nonatomic) NSUInteger maxMemoryCost; + +/** + * The maximum number of objects in-memory image cache should hold. + * Defaults to 0. Which means there is no memory count limit. + */ +@property (assign, nonatomic) NSUInteger maxMemoryCount; + +/* + * The attribute which the clear cache will be checked against when clearing the disk cache + * Default is Modified Date + */ +@property (assign, nonatomic) SDImageCacheConfigExpireType diskCacheExpireType; + +/** + * The custom file manager for disk cache. Pass nil to let disk cache choose the proper file manager. + * Defaults to nil. + * @note This value does not support dynamic changes. Which means further modification on this value after cache initlized has no effect. + * @note Since `NSFileManager` does not support `NSCopying`. We just pass this by reference during copying. So it's not recommend to set this value on `defaultCacheConfig`. + */ +@property (strong, nonatomic, nullable) NSFileManager *fileManager; + +/** + * The custom memory cache class. Provided class instance must conform to `SDMemoryCache` protocol to allow usage. + * Defaults to built-in `SDMemoryCache` class. + * @note This value does not support dynamic changes. Which means further modification on this value after cache initlized has no effect. + */ +@property (assign, nonatomic, nonnull) Class memoryCacheClass; + +/** + * The custom disk cache class. Provided class instance must conform to `SDDiskCache` protocol to allow usage. + * Defaults to built-in `SDDiskCache` class. + * @note This value does not support dynamic changes. Which means further modification on this value after cache initlized has no effect. + */ +@property (assign ,nonatomic, nonnull) Class diskCacheClass; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.m new file mode 100644 index 0000000..40a5334 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheConfig.m @@ -0,0 +1,63 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCacheConfig.h" +#import "SDMemoryCache.h" +#import "SDDiskCache.h" + +static SDImageCacheConfig *_defaultCacheConfig; +static const NSInteger kDefaultCacheMaxDiskAge = 60 * 60 * 24 * 7; // 1 week + +@implementation SDImageCacheConfig + ++ (SDImageCacheConfig *)defaultCacheConfig { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _defaultCacheConfig = [SDImageCacheConfig new]; + }); + return _defaultCacheConfig; +} + +- (instancetype)init { + if (self = [super init]) { + _shouldDisableiCloud = YES; + _shouldCacheImagesInMemory = YES; + _shouldUseWeakMemoryCache = YES; + _shouldRemoveExpiredDataWhenEnterBackground = YES; + _diskCacheReadingOptions = 0; + _diskCacheWritingOptions = NSDataWritingAtomic; + _maxDiskAge = kDefaultCacheMaxDiskAge; + _maxDiskSize = 0; + _diskCacheExpireType = SDImageCacheConfigExpireTypeModificationDate; + _memoryCacheClass = [SDMemoryCache class]; + _diskCacheClass = [SDDiskCache class]; + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + SDImageCacheConfig *config = [[[self class] allocWithZone:zone] init]; + config.shouldDisableiCloud = self.shouldDisableiCloud; + config.shouldCacheImagesInMemory = self.shouldCacheImagesInMemory; + config.shouldUseWeakMemoryCache = self.shouldUseWeakMemoryCache; + config.shouldRemoveExpiredDataWhenEnterBackground = self.shouldRemoveExpiredDataWhenEnterBackground; + config.diskCacheReadingOptions = self.diskCacheReadingOptions; + config.diskCacheWritingOptions = self.diskCacheWritingOptions; + config.maxDiskAge = self.maxDiskAge; + config.maxDiskSize = self.maxDiskSize; + config.maxMemoryCost = self.maxMemoryCost; + config.maxMemoryCount = self.maxMemoryCount; + config.diskCacheExpireType = self.diskCacheExpireType; + config.fileManager = self.fileManager; // NSFileManager does not conform to NSCopying, just pass the reference + config.memoryCacheClass = self.memoryCacheClass; + config.diskCacheClass = self.diskCacheClass; + + return config; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.h new file mode 100644 index 0000000..be4e021 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.h @@ -0,0 +1,125 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" +#import "SDWebImageDefine.h" + +/// Image Cache Type +typedef NS_ENUM(NSInteger, SDImageCacheType) { + /** + * For query and contains op in response, means the image isn't available in the image cache + * For op in request, this type is not available and take no effect. + */ + SDImageCacheTypeNone, + /** + * For query and contains op in response, means the image was obtained from the disk cache. + * For op in request, means process only disk cache. + */ + SDImageCacheTypeDisk, + /** + * For query and contains op in response, means the image was obtained from the memory cache. + * For op in request, means process only memory cache. + */ + SDImageCacheTypeMemory, + /** + * For query and contains op in response, this type is not available and take no effect. + * For op in request, means process both memory cache and disk cache. + */ + SDImageCacheTypeAll +}; + +typedef void(^SDImageCacheCheckCompletionBlock)(BOOL isInCache); +typedef void(^SDImageCacheCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); +typedef NSString * _Nullable (^SDImageCacheAdditionalCachePathBlock)(NSString * _Nonnull key); +typedef void(^SDImageCacheQueryCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType); +typedef void(^SDImageCacheContainsCompletionBlock)(SDImageCacheType containsCacheType); + +/** + This is the built-in decoding process for image query from cache. + @note If you want to implement your custom loader with `queryImageForKey:options:context:completion:` API, but also want to keep compatible with SDWebImage's behavior, you'd better use this to produce image. + + @param imageData The image data from the cache. Should not be nil + @param cacheKey The image cache key from the input. Should not be nil + @param options The options arg from the input + @param context The context arg from the input + @return The decoded image for current image data query from cache + */ +FOUNDATION_EXPORT UIImage * _Nullable SDImageCacheDecodeImageData(NSData * _Nonnull imageData, NSString * _Nonnull cacheKey, SDWebImageOptions options, SDWebImageContext * _Nullable context); + +/** + This is the image cache protocol to provide custom image cache for `SDWebImageManager`. + Though the best practice to custom image cache, is to write your own class which conform `SDMemoryCache` or `SDDiskCache` protocol for `SDImageCache` class (See more on `SDImageCacheConfig.memoryCacheClass & SDImageCacheConfig.diskCacheClass`). + However, if your own cache implementation contains more advanced feature beyond `SDImageCache` itself, you can consider to provide this instead. For example, you can even use a cache manager like `SDImageCachesManager` to register multiple caches. + */ +@protocol SDImageCache + +@required +/** + Query the cached image from image cache for given key. The operation can be used to cancel the query. + If image is cached in memory, completion is called synchronously, else aynchronously and depends on the options arg (See `SDWebImageQueryDiskSync`) + + @param key The image cache key + @param options A mask to specify options to use for this query + @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + @param completionBlock The completion block. Will not get called if the operation is cancelled + @return The operation for this query + */ +- (nullable id)queryImageForKey:(nullable NSString *)key + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + completion:(nullable SDImageCacheQueryCompletionBlock)completionBlock; + +/** + Store the image into image cache for the given key. If cache type is memory only, completion is called synchronously, else aynchronously. + + @param image The image to store + @param imageData The image data to be used for disk storage + @param key The image cache key + @param cacheType The image store op cache type + @param completionBlock A block executed after the operation is finished + */ +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + forKey:(nullable NSString *)key + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + Remove the image from image cache for the given key. If cache type is memory only, completion is called synchronously, else aynchronously. + + @param key The image cache key + @param cacheType The image remove op cache type + @param completionBlock A block executed after the operation is finished + */ +- (void)removeImageForKey:(nullable NSString *)key + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +/** + Check if image cache contains the image for the given key (does not load the image). If image is cached in memory, completion is called synchronously, else aynchronously. + + @param key The image cache key + @param cacheType The image contains op cache type + @param completionBlock A block executed after the operation is finished. + */ +- (void)containsImageForKey:(nullable NSString *)key + cacheType:(SDImageCacheType)cacheType + completion:(nullable SDImageCacheContainsCompletionBlock)completionBlock; + +/** + Clear all the cached images for image cache. If cache type is memory only, completion is called synchronously, else aynchronously. + + @param cacheType The image clear op cache type + @param completionBlock A block executed after the operation is finished + */ +- (void)clearWithCacheType:(SDImageCacheType)cacheType + completion:(nullable SDWebImageNoParamsBlock)completionBlock; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.m new file mode 100644 index 0000000..75dfb4e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCacheDefine.m @@ -0,0 +1,77 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCacheDefine.h" +#import "SDImageCodersManager.h" +#import "SDImageCoderHelper.h" +#import "SDAnimatedImage.h" +#import "UIImage+Metadata.h" +#import "SDInternalMacros.h" + +UIImage * _Nullable SDImageCacheDecodeImageData(NSData * _Nonnull imageData, NSString * _Nonnull cacheKey, SDWebImageOptions options, SDWebImageContext * _Nullable context) { + UIImage *image; + BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly); + NSNumber *scaleValue = context[SDWebImageContextImageScaleFactor]; + CGFloat scale = scaleValue.doubleValue >= 1 ? scaleValue.doubleValue : SDImageScaleFactorForKey(cacheKey); + NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio]; + NSValue *thumbnailSizeValue; + BOOL shouldScaleDown = SD_OPTIONS_CONTAINS(options, SDWebImageScaleDownLargeImages); + if (shouldScaleDown) { + CGFloat thumbnailPixels = SDImageCoderHelper.defaultScaleDownLimitBytes / 4; + CGFloat dimension = ceil(sqrt(thumbnailPixels)); + thumbnailSizeValue = @(CGSizeMake(dimension, dimension)); + } + if (context[SDWebImageContextImageThumbnailPixelSize]) { + thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize]; + } + + SDImageCoderMutableOptions *mutableCoderOptions = [NSMutableDictionary dictionaryWithCapacity:2]; + mutableCoderOptions[SDImageCoderDecodeFirstFrameOnly] = @(decodeFirstFrame); + mutableCoderOptions[SDImageCoderDecodeScaleFactor] = @(scale); + mutableCoderOptions[SDImageCoderDecodePreserveAspectRatio] = preserveAspectRatioValue; + mutableCoderOptions[SDImageCoderDecodeThumbnailPixelSize] = thumbnailSizeValue; + mutableCoderOptions[SDImageCoderWebImageContext] = context; + SDImageCoderOptions *coderOptions = [mutableCoderOptions copy]; + + if (!decodeFirstFrame) { + Class animatedImageClass = context[SDWebImageContextAnimatedImageClass]; + // check whether we should use `SDAnimatedImage` + if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)]) { + image = [[animatedImageClass alloc] initWithData:imageData scale:scale options:coderOptions]; + if (image) { + // Preload frames if supported + if (options & SDWebImagePreloadAllFrames && [image respondsToSelector:@selector(preloadAllFrames)]) { + [((id)image) preloadAllFrames]; + } + } else { + // Check image class matching + if (options & SDWebImageMatchAnimatedImageClass) { + return nil; + } + } + } + } + if (!image) { + image = [[SDImageCodersManager sharedManager] decodedImageWithData:imageData options:coderOptions]; + } + if (image) { + BOOL shouldDecode = !SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage); + if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)]) { + // `SDAnimatedImage` do not decode + shouldDecode = NO; + } else if (image.sd_isAnimated) { + // animated image do not decode + shouldDecode = NO; + } + if (shouldDecode) { + image = [SDImageCoderHelper decodedImageWithImage:image]; + } + } + + return image; +} diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.h new file mode 100644 index 0000000..ad85db8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.h @@ -0,0 +1,81 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageCacheDefine.h" + +/// Policy for cache operation +typedef NS_ENUM(NSUInteger, SDImageCachesManagerOperationPolicy) { + SDImageCachesManagerOperationPolicySerial, // process all caches serially (from the highest priority to the lowest priority cache by order) + SDImageCachesManagerOperationPolicyConcurrent, // process all caches concurrently + SDImageCachesManagerOperationPolicyHighestOnly, // process the highest priority cache only + SDImageCachesManagerOperationPolicyLowestOnly // process the lowest priority cache only +}; + +/** + A caches manager to manage multiple caches. + */ +@interface SDImageCachesManager : NSObject + +/** + Returns the global shared caches manager instance. By default we will set [`SDImageCache.sharedImageCache`] into the caches array. + */ +@property (nonatomic, class, readonly, nonnull) SDImageCachesManager *sharedManager; + +// These are op policy for cache manager. + +/** + Operation policy for query op. + Defaults to `Serial`, means query all caches serially (one completion called then next begin) until one cache query success (`image` != nil). + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy queryOperationPolicy; + +/** + Operation policy for store op. + Defaults to `HighestOnly`, means store to the highest priority cache only. + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy storeOperationPolicy; + +/** + Operation policy for remove op. + Defaults to `Concurrent`, means remove all caches concurrently. + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy removeOperationPolicy; + +/** + Operation policy for contains op. + Defaults to `Serial`, means check all caches serially (one completion called then next begin) until one cache check success (`containsCacheType` != None). + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy containsOperationPolicy; + +/** + Operation policy for clear op. + Defaults to `Concurrent`, means clear all caches concurrently. + */ +@property (nonatomic, assign) SDImageCachesManagerOperationPolicy clearOperationPolicy; + +/** + All caches in caches manager. The caches array is a priority queue, which means the later added cache will have the highest priority + */ +@property (nonatomic, copy, nullable) NSArray> *caches; + +/** + Add a new cache to the end of caches array. Which has the highest priority. + + @param cache cache + */ +- (void)addCache:(nonnull id)cache; + +/** + Remove a cache in the caches array. + + @param cache cache + */ +- (void)removeCache:(nonnull id)cache; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.m new file mode 100644 index 0000000..6b6f7d8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCachesManager.m @@ -0,0 +1,553 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCachesManager.h" +#import "SDImageCachesManagerOperation.h" +#import "SDImageCache.h" +#import "SDInternalMacros.h" + +@interface SDImageCachesManager () + +@property (nonatomic, strong, nonnull) dispatch_semaphore_t cachesLock; + +@end + +@implementation SDImageCachesManager +{ + NSMutableArray> *_imageCaches; +} + ++ (SDImageCachesManager *)sharedManager { + static dispatch_once_t onceToken; + static SDImageCachesManager *manager; + dispatch_once(&onceToken, ^{ + manager = [[SDImageCachesManager alloc] init]; + }); + return manager; +} + +- (instancetype)init { + self = [super init]; + if (self) { + self.queryOperationPolicy = SDImageCachesManagerOperationPolicySerial; + self.storeOperationPolicy = SDImageCachesManagerOperationPolicyHighestOnly; + self.removeOperationPolicy = SDImageCachesManagerOperationPolicyConcurrent; + self.containsOperationPolicy = SDImageCachesManagerOperationPolicySerial; + self.clearOperationPolicy = SDImageCachesManagerOperationPolicyConcurrent; + // initialize with default image caches + _imageCaches = [NSMutableArray arrayWithObject:[SDImageCache sharedImageCache]]; + _cachesLock = dispatch_semaphore_create(1); + } + return self; +} + +- (NSArray> *)caches { + SD_LOCK(self.cachesLock); + NSArray> *caches = [_imageCaches copy]; + SD_UNLOCK(self.cachesLock); + return caches; +} + +- (void)setCaches:(NSArray> *)caches { + SD_LOCK(self.cachesLock); + [_imageCaches removeAllObjects]; + if (caches.count) { + [_imageCaches addObjectsFromArray:caches]; + } + SD_UNLOCK(self.cachesLock); +} + +#pragma mark - Cache IO operations + +- (void)addCache:(id)cache { + if (![cache conformsToProtocol:@protocol(SDImageCache)]) { + return; + } + SD_LOCK(self.cachesLock); + [_imageCaches addObject:cache]; + SD_UNLOCK(self.cachesLock); +} + +- (void)removeCache:(id)cache { + if (![cache conformsToProtocol:@protocol(SDImageCache)]) { + return; + } + SD_LOCK(self.cachesLock); + [_imageCaches removeObject:cache]; + SD_UNLOCK(self.cachesLock); +} + +#pragma mark - SDImageCache + +- (id)queryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context completion:(SDImageCacheQueryCompletionBlock)completionBlock { + if (!key) { + return nil; + } + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return nil; + } else if (count == 1) { + return [caches.firstObject queryImageForKey:key options:options context:context completion:completionBlock]; + } + switch (self.queryOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + return [cache queryImageForKey:key options:options context:context completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + return [cache queryImageForKey:key options:options context:context completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentQueryImageForKey:key options:options context:context completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + return operation; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self serialQueryImageForKey:key options:options context:context completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + return operation; + } + break; + default: + return nil; + break; + } +} + +- (void)storeImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock { + if (!key) { + return; + } + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return; + } else if (count == 1) { + [caches.firstObject storeImage:image imageData:imageData forKey:key cacheType:cacheType completion:completionBlock]; + return; + } + switch (self.storeOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + [cache storeImage:image imageData:imageData forKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + [cache storeImage:image imageData:imageData forKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentStoreImage:image imageData:imageData forKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + [self serialStoreImage:image imageData:imageData forKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator]; + } + break; + default: + break; + } +} + +- (void)removeImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock { + if (!key) { + return; + } + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return; + } else if (count == 1) { + [caches.firstObject removeImageForKey:key cacheType:cacheType completion:completionBlock]; + return; + } + switch (self.removeOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + [cache removeImageForKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + [cache removeImageForKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentRemoveImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + [self serialRemoveImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator]; + } + break; + default: + break; + } +} + +- (void)containsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheContainsCompletionBlock)completionBlock { + if (!key) { + return; + } + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return; + } else if (count == 1) { + [caches.firstObject containsImageForKey:key cacheType:cacheType completion:completionBlock]; + return; + } + switch (self.clearOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + [cache containsImageForKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + [cache containsImageForKey:key cacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentContainsImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self serialContainsImageForKey:key cacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + default: + break; + } +} + +- (void)clearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock { + NSArray> *caches = self.caches; + NSUInteger count = caches.count; + if (count == 0) { + return; + } else if (count == 1) { + [caches.firstObject clearWithCacheType:cacheType completion:completionBlock]; + return; + } + switch (self.clearOperationPolicy) { + case SDImageCachesManagerOperationPolicyHighestOnly: { + id cache = caches.lastObject; + [cache clearWithCacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyLowestOnly: { + id cache = caches.firstObject; + [cache clearWithCacheType:cacheType completion:completionBlock]; + } + break; + case SDImageCachesManagerOperationPolicyConcurrent: { + SDImageCachesManagerOperation *operation = [SDImageCachesManagerOperation new]; + [operation beginWithTotalCount:caches.count]; + [self concurrentClearWithCacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator operation:operation]; + } + break; + case SDImageCachesManagerOperationPolicySerial: { + [self serialClearWithCacheType:cacheType completion:completionBlock enumerator:caches.reverseObjectEnumerator]; + } + break; + default: + break; + } +} + +#pragma mark - Concurrent Operation + +- (void)concurrentQueryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context completion:(SDImageCacheQueryCompletionBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache queryImageForKey:key options:options context:context completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) { + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (image) { + // Success + [operation done]; + if (completionBlock) { + completionBlock(image, data, cacheType); + } + return; + } + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(nil, nil, SDImageCacheTypeNone); + } + } + }]; + } +} + +- (void)concurrentStoreImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache storeImage:image imageData:imageData forKey:key cacheType:cacheType completion:^{ + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(); + } + } + }]; + } +} + +- (void)concurrentRemoveImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache removeImageForKey:key cacheType:cacheType completion:^{ + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(); + } + } + }]; + } +} + +- (void)concurrentContainsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheContainsCompletionBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache containsImageForKey:key cacheType:cacheType completion:^(SDImageCacheType containsCacheType) { + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (containsCacheType != SDImageCacheTypeNone) { + // Success + [operation done]; + if (completionBlock) { + completionBlock(containsCacheType); + } + return; + } + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(SDImageCacheTypeNone); + } + } + }]; + } +} + +- (void)concurrentClearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + for (id cache in enumerator) { + [cache clearWithCacheType:cacheType completion:^{ + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (operation.pendingCount == 0) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(); + } + } + }]; + } +} + +#pragma mark - Serial Operation + +- (void)serialQueryImageForKey:(NSString *)key options:(SDWebImageOptions)options context:(SDWebImageContext *)context completion:(SDImageCacheQueryCompletionBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(nil, nil, SDImageCacheTypeNone); + } + return; + } + @weakify(self); + [cache queryImageForKey:key options:options context:context completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) { + @strongify(self); + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (image) { + // Success + [operation done]; + if (completionBlock) { + completionBlock(image, data, cacheType); + } + return; + } + // Next + [self serialQueryImageForKey:key options:options context:context completion:completionBlock enumerator:enumerator operation:operation]; + }]; +} + +- (void)serialStoreImage:(UIImage *)image imageData:(NSData *)imageData forKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator { + NSParameterAssert(enumerator); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + if (completionBlock) { + completionBlock(); + } + return; + } + @weakify(self); + [cache storeImage:image imageData:imageData forKey:key cacheType:cacheType completion:^{ + @strongify(self); + // Next + [self serialStoreImage:image imageData:imageData forKey:key cacheType:cacheType completion:completionBlock enumerator:enumerator]; + }]; +} + +- (void)serialRemoveImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator { + NSParameterAssert(enumerator); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + if (completionBlock) { + completionBlock(); + } + return; + } + @weakify(self); + [cache removeImageForKey:key cacheType:cacheType completion:^{ + @strongify(self); + // Next + [self serialRemoveImageForKey:key cacheType:cacheType completion:completionBlock enumerator:enumerator]; + }]; +} + +- (void)serialContainsImageForKey:(NSString *)key cacheType:(SDImageCacheType)cacheType completion:(SDImageCacheContainsCompletionBlock)completionBlock enumerator:(NSEnumerator> *)enumerator operation:(SDImageCachesManagerOperation *)operation { + NSParameterAssert(enumerator); + NSParameterAssert(operation); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + [operation done]; + if (completionBlock) { + completionBlock(SDImageCacheTypeNone); + } + return; + } + @weakify(self); + [cache containsImageForKey:key cacheType:cacheType completion:^(SDImageCacheType containsCacheType) { + @strongify(self); + if (operation.isCancelled) { + // Cancelled + return; + } + if (operation.isFinished) { + // Finished + return; + } + [operation completeOne]; + if (containsCacheType != SDImageCacheTypeNone) { + // Success + [operation done]; + if (completionBlock) { + completionBlock(containsCacheType); + } + return; + } + // Next + [self serialContainsImageForKey:key cacheType:cacheType completion:completionBlock enumerator:enumerator operation:operation]; + }]; +} + +- (void)serialClearWithCacheType:(SDImageCacheType)cacheType completion:(SDWebImageNoParamsBlock)completionBlock enumerator:(NSEnumerator> *)enumerator { + NSParameterAssert(enumerator); + id cache = enumerator.nextObject; + if (!cache) { + // Complete + if (completionBlock) { + completionBlock(); + } + return; + } + @weakify(self); + [cache clearWithCacheType:cacheType completion:^{ + @strongify(self); + // Next + [self serialClearWithCacheType:cacheType completion:completionBlock enumerator:enumerator]; + }]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.h new file mode 100644 index 0000000..221246a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.h @@ -0,0 +1,234 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "NSData+ImageContentType.h" + +typedef NSString * SDImageCoderOption NS_STRING_ENUM; +typedef NSDictionary SDImageCoderOptions; +typedef NSMutableDictionary SDImageCoderMutableOptions; + +#pragma mark - Coder Options +// These options are for image decoding +/** + A Boolean value indicating whether to decode the first frame only for animated image during decoding. (NSNumber). If not provide, decode animated image if need. + @note works for `SDImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeFirstFrameOnly; +/** + A CGFloat value which is greater than or equal to 1.0. This value specify the image scale factor for decoding. If not provide, use 1.0. (NSNumber) + @note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeScaleFactor; + +/** + A Boolean value indicating whether to keep the original aspect ratio when generating thumbnail images (or bitmap images from vector format). + Defaults to YES. + @note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodePreserveAspectRatio; + +/** + A CGSize value indicating whether or not to generate the thumbnail images (or bitmap images from vector format). When this value is provided, the decoder will generate a thumbnail image which pixel size is smaller than or equal to (depends the `.preserveAspectRatio`) the value size. + Defaults to CGSizeZero, which means no thumbnail generation at all. + @note When you pass `.preserveAspectRatio == NO`, the thumbnail image is stretched to match each dimension. When `.preserveAspectRatio == YES`, the thumbnail image's width is limited to pixel size's width, the thumbnail image's height is limited to pixel size's height. For common cases, you can just pass a square size to limit both. + @note works for `SDImageCoder`, `SDProgressiveImageCoder`, `SDAnimatedImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderDecodeThumbnailPixelSize; + + +// These options are for image encoding +/** + A Boolean value indicating whether to encode the first frame only for animated image during encoding. (NSNumber). If not provide, encode animated image if need. + @note works for `SDImageCoder`. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeFirstFrameOnly; +/** + A double value between 0.0-1.0 indicating the encode compression quality to produce the image data. 1.0 resulting in no compression and 0.0 resulting in the maximum compression possible. If not provide, use 1.0. (NSNumber) + @note works for `SDImageCoder` + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderEncodeCompressionQuality; + +/** + A SDWebImageContext object which hold the original context options from top-level API. (SDWebImageContext) + This option is ignored for all built-in coders and take no effect. + But this may be useful for some custom coders, because some business logic may dependent on things other than image or image data inforamtion only. + See `SDWebImageContext` for more detailed information. + */ +FOUNDATION_EXPORT SDImageCoderOption _Nonnull const SDImageCoderWebImageContext; + +#pragma mark - Coder +/** + This is the image coder protocol to provide custom image decoding/encoding. + These methods are all required to implement. + @note Pay attention that these methods are not called from main queue. + */ +@protocol SDImageCoder + +@required +#pragma mark - Decoding +/** + Returns YES if this coder can decode some data. Otherwise, the data should be passed to another coder. + + @param data The image data so we can look at it + @return YES if this coder can decode the data, NO otherwise + */ +- (BOOL)canDecodeFromData:(nullable NSData *)data; + +/** + Decode the image data to image. + @note This protocol may supports decode animated image frames. You can use `+[SDImageCoderHelper animatedImageWithFrames:]` to produce an animated image with frames. + + @param data The image data to be decoded + @param options A dictionary containing any decoding options. Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for image. Pass @{SDImageCoderDecodeFirstFrameOnly: @(YES)} to decode the first frame only. + @return The decoded image from data + */ +- (nullable UIImage *)decodedImageWithData:(nullable NSData *)data + options:(nullable SDImageCoderOptions *)options; + +#pragma mark - Encoding + +/** + Returns YES if this coder can encode some image. Otherwise, it should be passed to another coder. + For custom coder which introduce new image format, you'd better define a new `SDImageFormat` using like this. If you're creating public coder plugin for new image format, also update `https://github.com/rs/SDWebImage/wiki/Coder-Plugin-List` to avoid same value been defined twice. + * @code + static const SDImageFormat SDImageFormatHEIF = 10; + * @endcode + + @param format The image format + @return YES if this coder can encode the image, NO otherwise + */ +- (BOOL)canEncodeToFormat:(SDImageFormat)format NS_SWIFT_NAME(canEncode(to:)); + +/** + Encode the image to image data. + @note This protocol may supports encode animated image frames. You can use `+[SDImageCoderHelper framesFromAnimatedImage:]` to assemble an animated image with frames. + + @param image The image to be encoded + @param format The image format to encode, you should note `SDImageFormatUndefined` format is also possible + @param options A dictionary containing any encoding options. Pass @{SDImageCoderEncodeCompressionQuality: @(1)} to specify compression quality. + @return The encoded image data + */ +- (nullable NSData *)encodedDataWithImage:(nullable UIImage *)image + format:(SDImageFormat)format + options:(nullable SDImageCoderOptions *)options; + +@end + +#pragma mark - Progressive Coder +/** + This is the image coder protocol to provide custom progressive image decoding. + These methods are all required to implement. + @note Pay attention that these methods are not called from main queue. + */ +@protocol SDProgressiveImageCoder + +@required +/** + Returns YES if this coder can incremental decode some data. Otherwise, it should be passed to another coder. + + @param data The image data so we can look at it + @return YES if this coder can decode the data, NO otherwise + */ +- (BOOL)canIncrementalDecodeFromData:(nullable NSData *)data; + +/** + Because incremental decoding need to keep the decoded context, we will alloc a new instance with the same class for each download operation to avoid conflicts + This init method should not return nil + + @param options A dictionary containing any progressive decoding options (instance-level). Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for progressive animated image (each frames should use the same scale). + @return A new instance to do incremental decoding for the specify image format + */ +- (nonnull instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options; + +/** + Update the incremental decoding when new image data available + + @param data The image data has been downloaded so far + @param finished Whether the download has finished + */ +- (void)updateIncrementalData:(nullable NSData *)data finished:(BOOL)finished; + +/** + Incremental decode the current image data to image. + @note Due to the performance issue for progressive decoding and the integration for image view. This method may only return the first frame image even if the image data is animated image. If you want progressive animated image decoding, conform to `SDAnimatedImageCoder` protocol as well and use `animatedImageFrameAtIndex:` instead. + + @param options A dictionary containing any progressive decoding options. Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for progressive image + @return The decoded image from current data + */ +- (nullable UIImage *)incrementalDecodedImageWithOptions:(nullable SDImageCoderOptions *)options; + +@end + +#pragma mark - Animated Image Provider +/** + This is the animated image protocol to provide the basic function for animated image rendering. It's adopted by `SDAnimatedImage` and `SDAnimatedImageCoder` + */ +@protocol SDAnimatedImageProvider + +@required +/** + The original animated image data for current image. If current image is not an animated format, return nil. + We may use this method to grab back the original image data if need, such as NSCoding or compare. + + @return The animated image data + */ +@property (nonatomic, copy, readonly, nullable) NSData *animatedImageData; + +/** + Total animated frame count. + If the frame count is less than 1, then the methods below will be ignored. + + @return Total animated frame count. + */ +@property (nonatomic, assign, readonly) NSUInteger animatedImageFrameCount; +/** + Animation loop count, 0 means infinite looping. + + @return Animation loop count + */ +@property (nonatomic, assign, readonly) NSUInteger animatedImageLoopCount; +/** + Returns the frame image from a specified index. + @note The index maybe randomly if one image was set to different imageViews, keep it re-entrant. (It's not recommend to store the images into array because it's memory consuming) + + @param index Frame index (zero based). + @return Frame's image + */ +- (nullable UIImage *)animatedImageFrameAtIndex:(NSUInteger)index; +/** + Returns the frames's duration from a specified index. + @note The index maybe randomly if one image was set to different imageViews, keep it re-entrant. (It's recommend to store the durations into array because it's not memory-consuming) + + @param index Frame index (zero based). + @return Frame's duration + */ +- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index; + +@end + +#pragma mark - Animated Coder +/** + This is the animated image coder protocol for custom animated image class like `SDAnimatedImage`. Through it inherit from `SDImageCoder`. We currentlly only use the method `canDecodeFromData:` to detect the proper coder for specify animated image format. + */ +@protocol SDAnimatedImageCoder + +@required +/** + Because animated image coder should keep the original data, we will alloc a new instance with the same class for the specify animated image data + The init method should return nil if it can't decode the specify animated image data to produce any frame. + After the instance created, we may call methods in `SDAnimatedImageProvider` to produce animated image frame. + + @param data The animated image data to be decode + @param options A dictionary containing any animated decoding options (instance-level). Pass @{SDImageCoderDecodeScaleFactor: @(1.0)} to specify scale factor for animated image (each frames should use the same scale). + @return A new instance to do animated decoding for specify image data + */ +- (nullable instancetype)initWithAnimatedImageData:(nullable NSData *)data options:(nullable SDImageCoderOptions *)options; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.m new file mode 100644 index 0000000..df5224a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoder.m @@ -0,0 +1,19 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCoder.h" + +SDImageCoderOption const SDImageCoderDecodeFirstFrameOnly = @"decodeFirstFrameOnly"; +SDImageCoderOption const SDImageCoderDecodeScaleFactor = @"decodeScaleFactor"; +SDImageCoderOption const SDImageCoderDecodePreserveAspectRatio = @"decodePreserveAspectRatio"; +SDImageCoderOption const SDImageCoderDecodeThumbnailPixelSize = @"decodeThumbnailPixelSize"; + +SDImageCoderOption const SDImageCoderEncodeFirstFrameOnly = @"encodeFirstFrameOnly"; +SDImageCoderOption const SDImageCoderEncodeCompressionQuality = @"encodeCompressionQuality"; + +SDImageCoderOption const SDImageCoderWebImageContext = @"webImageContext"; diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.h new file mode 100644 index 0000000..5dbd523 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.h @@ -0,0 +1,126 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDImageFrame.h" + +/** + Provide some common helper methods for building the image decoder/encoder. + */ +@interface SDImageCoderHelper : NSObject + +/** + Return an animated image with frames array. + For UIKit, this will apply the patch and then create animated UIImage. The patch is because that `+[UIImage animatedImageWithImages:duration:]` just use the average of duration for each image. So it will not work if different frame has different duration. Therefore we repeat the specify frame for specify times to let it work. + For AppKit, NSImage does not support animates other than GIF. This will try to encode the frames to GIF format and then create an animated NSImage for rendering. Attention the animated image may loss some detail if the input frames contain full alpha channel because GIF only supports 1 bit alpha channel. (For 1 pixel, either transparent or not) + + @param frames The frames array. If no frames or frames is empty, return nil + @return A animated image for rendering on UIImageView(UIKit) or NSImageView(AppKit) + */ ++ (UIImage * _Nullable)animatedImageWithFrames:(NSArray * _Nullable)frames; + +/** + Return frames array from an animated image. + For UIKit, this will unapply the patch for the description above and then create frames array. This will also work for normal animated UIImage. + For AppKit, NSImage does not support animates other than GIF. This will try to decode the GIF imageRep and then create frames array. + + @param animatedImage A animated image. If it's not animated, return nil + @return The frames array + */ ++ (NSArray * _Nullable)framesFromAnimatedImage:(UIImage * _Nullable)animatedImage NS_SWIFT_NAME(frames(from:)); + +/** + Return the shared device-dependent RGB color space. This follows The Get Rule. + On iOS, it's created with deviceRGB (if available, use sRGB). + On macOS, it's from the screen colorspace (if failed, use deviceRGB) + Because it's shared, you should not retain or release this object. + + @return The device-dependent RGB color space + */ ++ (CGColorSpaceRef _Nonnull)colorSpaceGetDeviceRGB CF_RETURNS_NOT_RETAINED; + +/** + Check whether CGImage contains alpha channel. + + @param cgImage The CGImage + @return Return YES if CGImage contains alpha channel, otherwise return NO + */ ++ (BOOL)CGImageContainsAlpha:(_Nonnull CGImageRef)cgImage; + +/** + Create a decoded CGImage by the provided CGImage. This follows The Create Rule and you are response to call release after usage. + It will detect whether image contains alpha channel, then create a new bitmap context with the same size of image, and draw it. This can ensure that the image do not need extra decoding after been set to the imageView. + @note This actually call `CGImageCreateDecoded:orientation:` with the Up orientation. + + @param cgImage The CGImage + @return A new created decoded image + */ ++ (CGImageRef _Nullable)CGImageCreateDecoded:(_Nonnull CGImageRef)cgImage CF_RETURNS_RETAINED; + +/** + Create a decoded CGImage by the provided CGImage and orientation. This follows The Create Rule and you are response to call release after usage. + It will detect whether image contains alpha channel, then create a new bitmap context with the same size of image, and draw it. This can ensure that the image do not need extra decoding after been set to the imageView. + + @param cgImage The CGImage + @param orientation The EXIF image orientation. + @return A new created decoded image + */ ++ (CGImageRef _Nullable)CGImageCreateDecoded:(_Nonnull CGImageRef)cgImage orientation:(CGImagePropertyOrientation)orientation CF_RETURNS_RETAINED; + +/** + Create a scaled CGImage by the provided CGImage and size. This follows The Create Rule and you are response to call release after usage. + It will detect whether the image size matching the scale size, if not, stretch the image to the target size. + + @param cgImage The CGImage + @param size The scale size in pixel. + @return A new created scaled image + */ ++ (CGImageRef _Nullable)CGImageCreateScaled:(_Nonnull CGImageRef)cgImage size:(CGSize)size CF_RETURNS_RETAINED; + +/** + Return the decoded image by the provided image. This one unlike `CGImageCreateDecoded:`, will not decode the image which contains alpha channel or animated image + @param image The image to be decoded + @return The decoded image + */ ++ (UIImage * _Nullable)decodedImageWithImage:(UIImage * _Nullable)image; + +/** + Return the decoded and probably scaled down image by the provided image. If the image is large than the limit size, will try to scale down. Or just works as `decodedImageWithImage:` + + @param image The image to be decoded and scaled down + @param bytes The limit bytes size. Provide 0 to use the build-in limit. + @return The decoded and probably scaled down image + */ ++ (UIImage * _Nullable)decodedAndScaledDownImageWithImage:(UIImage * _Nullable)image limitBytes:(NSUInteger)bytes; + +/** + Control the default limit bytes to scale down larget images. + This value must be larger than or equal to 1MB. Defaults to 60MB on iOS/tvOS, 90MB on macOS, 30MB on watchOS. + */ +@property (class, readwrite) NSUInteger defaultScaleDownLimitBytes; + +#if SD_UIKIT || SD_WATCH +/** + Convert an EXIF image orientation to an iOS one. + + @param exifOrientation EXIF orientation + @return iOS orientation + */ ++ (UIImageOrientation)imageOrientationFromEXIFOrientation:(CGImagePropertyOrientation)exifOrientation NS_SWIFT_NAME(imageOrientation(from:)); + +/** + Convert an iOS orientation to an EXIF image orientation. + + @param imageOrientation iOS orientation + @return EXIF orientation + */ ++ (CGImagePropertyOrientation)exifOrientationFromImageOrientation:(UIImageOrientation)imageOrientation; +#endif + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.m new file mode 100644 index 0000000..c29685a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCoderHelper.m @@ -0,0 +1,686 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCoderHelper.h" +#import "SDImageFrame.h" +#import "NSImage+Compatibility.h" +#import "NSData+ImageContentType.h" +#import "SDAnimatedImageRep.h" +#import "UIImage+ForceDecode.h" +#import "SDAssociatedObject.h" +#import "UIImage+Metadata.h" +#import "SDInternalMacros.h" +#import + +static inline size_t SDByteAlign(size_t size, size_t alignment) { + return ((size + (alignment - 1)) / alignment) * alignment; +} + +static const size_t kBytesPerPixel = 4; +static const size_t kBitsPerComponent = 8; + +static const CGFloat kBytesPerMB = 1024.0f * 1024.0f; +static const CGFloat kPixelsPerMB = kBytesPerMB / kBytesPerPixel; +/* + * Defines the maximum size in MB of the decoded image when the flag `SDWebImageScaleDownLargeImages` is set + * Suggested value for iPad1 and iPhone 3GS: 60. + * Suggested value for iPad2 and iPhone 4: 120. + * Suggested value for iPhone 3G and iPod 2 and earlier devices: 30. + */ +#if SD_MAC +static CGFloat kDestImageLimitBytes = 90.f * kBytesPerMB; +#elif SD_UIKIT +static CGFloat kDestImageLimitBytes = 60.f * kBytesPerMB; +#elif SD_WATCH +static CGFloat kDestImageLimitBytes = 30.f * kBytesPerMB; +#endif + +static const CGFloat kDestSeemOverlap = 2.0f; // the numbers of pixels to overlap the seems where tiles meet. + +@implementation SDImageCoderHelper + ++ (UIImage *)animatedImageWithFrames:(NSArray *)frames { + NSUInteger frameCount = frames.count; + if (frameCount == 0) { + return nil; + } + + UIImage *animatedImage; + +#if SD_UIKIT || SD_WATCH + NSUInteger durations[frameCount]; + for (size_t i = 0; i < frameCount; i++) { + durations[i] = frames[i].duration * 1000; + } + NSUInteger const gcd = gcdArray(frameCount, durations); + __block NSUInteger totalDuration = 0; + NSMutableArray *animatedImages = [NSMutableArray arrayWithCapacity:frameCount]; + [frames enumerateObjectsUsingBlock:^(SDImageFrame * _Nonnull frame, NSUInteger idx, BOOL * _Nonnull stop) { + UIImage *image = frame.image; + NSUInteger duration = frame.duration * 1000; + totalDuration += duration; + NSUInteger repeatCount; + if (gcd) { + repeatCount = duration / gcd; + } else { + repeatCount = 1; + } + for (size_t i = 0; i < repeatCount; ++i) { + [animatedImages addObject:image]; + } + }]; + + animatedImage = [UIImage animatedImageWithImages:animatedImages duration:totalDuration / 1000.f]; + +#else + + NSMutableData *imageData = [NSMutableData data]; + CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:SDImageFormatGIF]; + // Create an image destination. GIF does not support EXIF image orientation + CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, frameCount, NULL); + if (!imageDestination) { + // Handle failure. + return nil; + } + + for (size_t i = 0; i < frameCount; i++) { + @autoreleasepool { + SDImageFrame *frame = frames[i]; + NSTimeInterval frameDuration = frame.duration; + CGImageRef frameImageRef = frame.image.CGImage; + NSDictionary *frameProperties = @{(__bridge NSString *)kCGImagePropertyGIFDictionary : @{(__bridge NSString *)kCGImagePropertyGIFDelayTime : @(frameDuration)}}; + CGImageDestinationAddImage(imageDestination, frameImageRef, (__bridge CFDictionaryRef)frameProperties); + } + } + // Finalize the destination. + if (CGImageDestinationFinalize(imageDestination) == NO) { + // Handle failure. + CFRelease(imageDestination); + return nil; + } + CFRelease(imageDestination); + CGFloat scale = MAX(frames.firstObject.image.scale, 1); + + SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:imageData]; + NSSize size = NSMakeSize(imageRep.pixelsWide / scale, imageRep.pixelsHigh / scale); + imageRep.size = size; + animatedImage = [[NSImage alloc] initWithSize:size]; + [animatedImage addRepresentation:imageRep]; +#endif + + return animatedImage; +} + ++ (NSArray *)framesFromAnimatedImage:(UIImage *)animatedImage { + if (!animatedImage) { + return nil; + } + + NSMutableArray *frames = [NSMutableArray array]; + NSUInteger frameCount = 0; + +#if SD_UIKIT || SD_WATCH + NSArray *animatedImages = animatedImage.images; + frameCount = animatedImages.count; + if (frameCount == 0) { + return nil; + } + + NSTimeInterval avgDuration = animatedImage.duration / frameCount; + if (avgDuration == 0) { + avgDuration = 0.1; // if it's a animated image but no duration, set it to default 100ms (this do not have that 10ms limit like GIF or WebP to allow custom coder provide the limit) + } + + __block NSUInteger index = 0; + __block NSUInteger repeatCount = 1; + __block UIImage *previousImage = animatedImages.firstObject; + [animatedImages enumerateObjectsUsingBlock:^(UIImage * _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) { + // ignore first + if (idx == 0) { + return; + } + if ([image isEqual:previousImage]) { + repeatCount++; + } else { + SDImageFrame *frame = [SDImageFrame frameWithImage:previousImage duration:avgDuration * repeatCount]; + [frames addObject:frame]; + repeatCount = 1; + index++; + } + previousImage = image; + // last one + if (idx == frameCount - 1) { + SDImageFrame *frame = [SDImageFrame frameWithImage:previousImage duration:avgDuration * repeatCount]; + [frames addObject:frame]; + } + }]; + +#else + + NSRect imageRect = NSMakeRect(0, 0, animatedImage.size.width, animatedImage.size.height); + NSImageRep *imageRep = [animatedImage bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (!bitmapImageRep) { + return nil; + } + frameCount = [[bitmapImageRep valueForProperty:NSImageFrameCount] unsignedIntegerValue]; + if (frameCount == 0) { + return nil; + } + CGFloat scale = animatedImage.scale; + + for (size_t i = 0; i < frameCount; i++) { + @autoreleasepool { + // NSBitmapImageRep need to manually change frame. "Good taste" API + [bitmapImageRep setProperty:NSImageCurrentFrame withValue:@(i)]; + NSTimeInterval frameDuration = [[bitmapImageRep valueForProperty:NSImageCurrentFrameDuration] doubleValue]; + NSImage *frameImage = [[NSImage alloc] initWithCGImage:bitmapImageRep.CGImage scale:scale orientation:kCGImagePropertyOrientationUp]; + SDImageFrame *frame = [SDImageFrame frameWithImage:frameImage duration:frameDuration]; + [frames addObject:frame]; + } + } +#endif + + return frames; +} + ++ (CGColorSpaceRef)colorSpaceGetDeviceRGB { +#if SD_MAC + CGColorSpaceRef screenColorSpace = NSScreen.mainScreen.colorSpace.CGColorSpace; + if (screenColorSpace) { + return screenColorSpace; + } +#endif + static CGColorSpaceRef colorSpace; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ +#if SD_UIKIT + if (@available(iOS 9.0, tvOS 9.0, *)) { + colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + } else { + colorSpace = CGColorSpaceCreateDeviceRGB(); + } +#else + colorSpace = CGColorSpaceCreateDeviceRGB(); +#endif + }); + return colorSpace; +} + ++ (BOOL)CGImageContainsAlpha:(CGImageRef)cgImage { + if (!cgImage) { + return NO; + } + CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(cgImage); + BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone || + alphaInfo == kCGImageAlphaNoneSkipFirst || + alphaInfo == kCGImageAlphaNoneSkipLast); + return hasAlpha; +} + ++ (CGImageRef)CGImageCreateDecoded:(CGImageRef)cgImage { + return [self CGImageCreateDecoded:cgImage orientation:kCGImagePropertyOrientationUp]; +} + ++ (CGImageRef)CGImageCreateDecoded:(CGImageRef)cgImage orientation:(CGImagePropertyOrientation)orientation { + if (!cgImage) { + return NULL; + } + size_t width = CGImageGetWidth(cgImage); + size_t height = CGImageGetHeight(cgImage); + if (width == 0 || height == 0) return NULL; + size_t newWidth; + size_t newHeight; + switch (orientation) { + case kCGImagePropertyOrientationLeft: + case kCGImagePropertyOrientationLeftMirrored: + case kCGImagePropertyOrientationRight: + case kCGImagePropertyOrientationRightMirrored: { + // These orientation should swap width & height + newWidth = height; + newHeight = width; + } + break; + default: { + newWidth = width; + newHeight = height; + } + break; + } + + BOOL hasAlpha = [self CGImageContainsAlpha:cgImage]; + // iOS prefer BGRA8888 (premultiplied) or BGRX8888 bitmapInfo for screen rendering, which is same as `UIGraphicsBeginImageContext()` or `- [CALayer drawInContext:]` + // Though you can use any supported bitmapInfo (see: https://developer.apple.com/library/content/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-BCIBHHBB ) and let Core Graphics reorder it when you call `CGContextDrawImage` + // But since our build-in coders use this bitmapInfo, this can have a little performance benefit + CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host; + bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst; + CGContextRef context = CGBitmapContextCreate(NULL, newWidth, newHeight, 8, 0, [self colorSpaceGetDeviceRGB], bitmapInfo); + if (!context) { + return NULL; + } + + // Apply transform + CGAffineTransform transform = SDCGContextTransformFromOrientation(orientation, CGSizeMake(newWidth, newHeight)); + CGContextConcatCTM(context, transform); + CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage); // The rect is bounding box of CGImage, don't swap width & height + CGImageRef newImageRef = CGBitmapContextCreateImage(context); + CGContextRelease(context); + + return newImageRef; +} + ++ (CGImageRef)CGImageCreateScaled:(CGImageRef)cgImage size:(CGSize)size { + if (!cgImage) { + return NULL; + } + size_t width = CGImageGetWidth(cgImage); + size_t height = CGImageGetHeight(cgImage); + if (width == size.width && height == size.height) { + CGImageRetain(cgImage); + return cgImage; + } + + __block vImage_Buffer input_buffer = {}, output_buffer = {}; + @onExit { + if (input_buffer.data) free(input_buffer.data); + if (output_buffer.data) free(output_buffer.data); + }; + BOOL hasAlpha = [self CGImageContainsAlpha:cgImage]; + // iOS display alpha info (BGRA8888/BGRX8888) + CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host; + bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst; + vImage_CGImageFormat format = (vImage_CGImageFormat) { + .bitsPerComponent = 8, + .bitsPerPixel = 32, + .colorSpace = NULL, + .bitmapInfo = bitmapInfo, + .version = 0, + .decode = NULL, + .renderingIntent = kCGRenderingIntentDefault, + }; + + vImage_Error a_ret = vImageBuffer_InitWithCGImage(&input_buffer, &format, NULL, cgImage, kvImageNoFlags); + if (a_ret != kvImageNoError) return NULL; + output_buffer.width = MAX(size.width, 0); + output_buffer.height = MAX(size.height, 0); + output_buffer.rowBytes = SDByteAlign(output_buffer.width * 4, 64); + output_buffer.data = malloc(output_buffer.rowBytes * output_buffer.height); + if (!output_buffer.data) return NULL; + + vImage_Error ret = vImageScale_ARGB8888(&input_buffer, &output_buffer, NULL, kvImageHighQualityResampling); + if (ret != kvImageNoError) return NULL; + + CGImageRef outputImage = vImageCreateCGImageFromBuffer(&output_buffer, &format, NULL, NULL, kvImageNoFlags, &ret); + if (ret != kvImageNoError) { + CGImageRelease(outputImage); + return NULL; + } + + return outputImage; +} + ++ (UIImage *)decodedImageWithImage:(UIImage *)image { + if (![self shouldDecodeImage:image]) { + return image; + } + + CGImageRef imageRef = [self CGImageCreateDecoded:image.CGImage]; + if (!imageRef) { + return image; + } +#if SD_MAC + UIImage *decodedImage = [[UIImage alloc] initWithCGImage:imageRef scale:image.scale orientation:kCGImagePropertyOrientationUp]; +#else + UIImage *decodedImage = [[UIImage alloc] initWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation]; +#endif + CGImageRelease(imageRef); + SDImageCopyAssociatedObject(image, decodedImage); + decodedImage.sd_isDecoded = YES; + return decodedImage; +} + ++ (UIImage *)decodedAndScaledDownImageWithImage:(UIImage *)image limitBytes:(NSUInteger)bytes { + if (![self shouldDecodeImage:image]) { + return image; + } + + if (![self shouldScaleDownImage:image limitBytes:bytes]) { + return [self decodedImageWithImage:image]; + } + + CGFloat destTotalPixels; + CGFloat tileTotalPixels; + if (bytes == 0) { + bytes = kDestImageLimitBytes; + } + destTotalPixels = bytes / kBytesPerPixel; + tileTotalPixels = destTotalPixels / 3; + CGContextRef destContext; + + // autorelease the bitmap context and all vars to help system to free memory when there are memory warning. + // on iOS7, do not forget to call [[SDImageCache sharedImageCache] clearMemory]; + @autoreleasepool { + CGImageRef sourceImageRef = image.CGImage; + + CGSize sourceResolution = CGSizeZero; + sourceResolution.width = CGImageGetWidth(sourceImageRef); + sourceResolution.height = CGImageGetHeight(sourceImageRef); + CGFloat sourceTotalPixels = sourceResolution.width * sourceResolution.height; + // Determine the scale ratio to apply to the input image + // that results in an output image of the defined size. + // see kDestImageSizeMB, and how it relates to destTotalPixels. + CGFloat imageScale = sqrt(destTotalPixels / sourceTotalPixels); + CGSize destResolution = CGSizeZero; + destResolution.width = (int)(sourceResolution.width * imageScale); + destResolution.height = (int)(sourceResolution.height * imageScale); + + // device color space + CGColorSpaceRef colorspaceRef = [self colorSpaceGetDeviceRGB]; + BOOL hasAlpha = [self CGImageContainsAlpha:sourceImageRef]; + // iOS display alpha info (BGRA8888/BGRX8888) + CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host; + bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst; + + // kCGImageAlphaNone is not supported in CGBitmapContextCreate. + // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipFirst + // to create bitmap graphics contexts without alpha info. + destContext = CGBitmapContextCreate(NULL, + destResolution.width, + destResolution.height, + kBitsPerComponent, + 0, + colorspaceRef, + bitmapInfo); + + if (destContext == NULL) { + return image; + } + CGContextSetInterpolationQuality(destContext, kCGInterpolationHigh); + + // Now define the size of the rectangle to be used for the + // incremental blits from the input image to the output image. + // we use a source tile width equal to the width of the source + // image due to the way that iOS retrieves image data from disk. + // iOS must decode an image from disk in full width 'bands', even + // if current graphics context is clipped to a subrect within that + // band. Therefore we fully utilize all of the pixel data that results + // from a decoding opertion by achnoring our tile size to the full + // width of the input image. + CGRect sourceTile = CGRectZero; + sourceTile.size.width = sourceResolution.width; + // The source tile height is dynamic. Since we specified the size + // of the source tile in MB, see how many rows of pixels high it + // can be given the input image width. + sourceTile.size.height = (int)(tileTotalPixels / sourceTile.size.width ); + sourceTile.origin.x = 0.0f; + // The output tile is the same proportions as the input tile, but + // scaled to image scale. + CGRect destTile; + destTile.size.width = destResolution.width; + destTile.size.height = sourceTile.size.height * imageScale; + destTile.origin.x = 0.0f; + // The source seem overlap is proportionate to the destination seem overlap. + // this is the amount of pixels to overlap each tile as we assemble the ouput image. + float sourceSeemOverlap = (int)((kDestSeemOverlap/destResolution.height)*sourceResolution.height); + CGImageRef sourceTileImageRef; + // calculate the number of read/write operations required to assemble the + // output image. + int iterations = (int)( sourceResolution.height / sourceTile.size.height ); + // If tile height doesn't divide the image height evenly, add another iteration + // to account for the remaining pixels. + int remainder = (int)sourceResolution.height % (int)sourceTile.size.height; + if(remainder) { + iterations++; + } + // Add seem overlaps to the tiles, but save the original tile height for y coordinate calculations. + float sourceTileHeightMinusOverlap = sourceTile.size.height; + sourceTile.size.height += sourceSeemOverlap; + destTile.size.height += kDestSeemOverlap; + for( int y = 0; y < iterations; ++y ) { + @autoreleasepool { + sourceTile.origin.y = y * sourceTileHeightMinusOverlap + sourceSeemOverlap; + destTile.origin.y = destResolution.height - (( y + 1 ) * sourceTileHeightMinusOverlap * imageScale + kDestSeemOverlap); + sourceTileImageRef = CGImageCreateWithImageInRect( sourceImageRef, sourceTile ); + if( y == iterations - 1 && remainder ) { + float dify = destTile.size.height; + destTile.size.height = CGImageGetHeight( sourceTileImageRef ) * imageScale; + dify -= destTile.size.height; + destTile.origin.y += dify; + } + CGContextDrawImage( destContext, destTile, sourceTileImageRef ); + CGImageRelease( sourceTileImageRef ); + } + } + + CGImageRef destImageRef = CGBitmapContextCreateImage(destContext); + CGContextRelease(destContext); + if (destImageRef == NULL) { + return image; + } +#if SD_MAC + UIImage *destImage = [[UIImage alloc] initWithCGImage:destImageRef scale:image.scale orientation:kCGImagePropertyOrientationUp]; +#else + UIImage *destImage = [[UIImage alloc] initWithCGImage:destImageRef scale:image.scale orientation:image.imageOrientation]; +#endif + CGImageRelease(destImageRef); + if (destImage == nil) { + return image; + } + SDImageCopyAssociatedObject(image, destImage); + destImage.sd_isDecoded = YES; + return destImage; + } +} + ++ (NSUInteger)defaultScaleDownLimitBytes { + return kDestImageLimitBytes; +} + ++ (void)setDefaultScaleDownLimitBytes:(NSUInteger)defaultScaleDownLimitBytes { + if (defaultScaleDownLimitBytes < kBytesPerMB) { + return; + } + kDestImageLimitBytes = defaultScaleDownLimitBytes; +} + +#if SD_UIKIT || SD_WATCH +// Convert an EXIF image orientation to an iOS one. ++ (UIImageOrientation)imageOrientationFromEXIFOrientation:(CGImagePropertyOrientation)exifOrientation { + UIImageOrientation imageOrientation = UIImageOrientationUp; + switch (exifOrientation) { + case kCGImagePropertyOrientationUp: + imageOrientation = UIImageOrientationUp; + break; + case kCGImagePropertyOrientationDown: + imageOrientation = UIImageOrientationDown; + break; + case kCGImagePropertyOrientationLeft: + imageOrientation = UIImageOrientationLeft; + break; + case kCGImagePropertyOrientationRight: + imageOrientation = UIImageOrientationRight; + break; + case kCGImagePropertyOrientationUpMirrored: + imageOrientation = UIImageOrientationUpMirrored; + break; + case kCGImagePropertyOrientationDownMirrored: + imageOrientation = UIImageOrientationDownMirrored; + break; + case kCGImagePropertyOrientationLeftMirrored: + imageOrientation = UIImageOrientationLeftMirrored; + break; + case kCGImagePropertyOrientationRightMirrored: + imageOrientation = UIImageOrientationRightMirrored; + break; + default: + break; + } + return imageOrientation; +} + +// Convert an iOS orientation to an EXIF image orientation. ++ (CGImagePropertyOrientation)exifOrientationFromImageOrientation:(UIImageOrientation)imageOrientation { + CGImagePropertyOrientation exifOrientation = kCGImagePropertyOrientationUp; + switch (imageOrientation) { + case UIImageOrientationUp: + exifOrientation = kCGImagePropertyOrientationUp; + break; + case UIImageOrientationDown: + exifOrientation = kCGImagePropertyOrientationDown; + break; + case UIImageOrientationLeft: + exifOrientation = kCGImagePropertyOrientationLeft; + break; + case UIImageOrientationRight: + exifOrientation = kCGImagePropertyOrientationRight; + break; + case UIImageOrientationUpMirrored: + exifOrientation = kCGImagePropertyOrientationUpMirrored; + break; + case UIImageOrientationDownMirrored: + exifOrientation = kCGImagePropertyOrientationDownMirrored; + break; + case UIImageOrientationLeftMirrored: + exifOrientation = kCGImagePropertyOrientationLeftMirrored; + break; + case UIImageOrientationRightMirrored: + exifOrientation = kCGImagePropertyOrientationRightMirrored; + break; + default: + break; + } + return exifOrientation; +} +#endif + +#pragma mark - Helper Fuction ++ (BOOL)shouldDecodeImage:(nullable UIImage *)image { + // Avoid extra decode + if (image.sd_isDecoded) { + return NO; + } + // Prevent "CGBitmapContextCreateImage: invalid context 0x0" error + if (image == nil) { + return NO; + } + // do not decode animated images + if (image.sd_isAnimated) { + return NO; + } + + return YES; +} + ++ (BOOL)shouldScaleDownImage:(nonnull UIImage *)image limitBytes:(NSUInteger)bytes { + BOOL shouldScaleDown = YES; + + CGImageRef sourceImageRef = image.CGImage; + CGSize sourceResolution = CGSizeZero; + sourceResolution.width = CGImageGetWidth(sourceImageRef); + sourceResolution.height = CGImageGetHeight(sourceImageRef); + float sourceTotalPixels = sourceResolution.width * sourceResolution.height; + if (sourceTotalPixels <= 0) { + return NO; + } + CGFloat destTotalPixels; + if (bytes == 0) { + bytes = kDestImageLimitBytes; + } + destTotalPixels = bytes / kBytesPerPixel; + if (destTotalPixels <= kPixelsPerMB) { + // Too small to scale down + return NO; + } + float imageScale = destTotalPixels / sourceTotalPixels; + if (imageScale < 1) { + shouldScaleDown = YES; + } else { + shouldScaleDown = NO; + } + + return shouldScaleDown; +} + +static inline CGAffineTransform SDCGContextTransformFromOrientation(CGImagePropertyOrientation orientation, CGSize size) { + // Inspiration from @libfeihu + // We need to calculate the proper transformation to make the image upright. + // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored. + CGAffineTransform transform = CGAffineTransformIdentity; + + switch (orientation) { + case kCGImagePropertyOrientationDown: + case kCGImagePropertyOrientationDownMirrored: + transform = CGAffineTransformTranslate(transform, size.width, size.height); + transform = CGAffineTransformRotate(transform, M_PI); + break; + + case kCGImagePropertyOrientationLeft: + case kCGImagePropertyOrientationLeftMirrored: + transform = CGAffineTransformTranslate(transform, size.width, 0); + transform = CGAffineTransformRotate(transform, M_PI_2); + break; + + case kCGImagePropertyOrientationRight: + case kCGImagePropertyOrientationRightMirrored: + transform = CGAffineTransformTranslate(transform, 0, size.height); + transform = CGAffineTransformRotate(transform, -M_PI_2); + break; + case kCGImagePropertyOrientationUp: + case kCGImagePropertyOrientationUpMirrored: + break; + } + + switch (orientation) { + case kCGImagePropertyOrientationUpMirrored: + case kCGImagePropertyOrientationDownMirrored: + transform = CGAffineTransformTranslate(transform, size.width, 0); + transform = CGAffineTransformScale(transform, -1, 1); + break; + + case kCGImagePropertyOrientationLeftMirrored: + case kCGImagePropertyOrientationRightMirrored: + transform = CGAffineTransformTranslate(transform, size.height, 0); + transform = CGAffineTransformScale(transform, -1, 1); + break; + case kCGImagePropertyOrientationUp: + case kCGImagePropertyOrientationDown: + case kCGImagePropertyOrientationLeft: + case kCGImagePropertyOrientationRight: + break; + } + + return transform; +} + +#if SD_UIKIT || SD_WATCH +static NSUInteger gcd(NSUInteger a, NSUInteger b) { + NSUInteger c; + while (a != 0) { + c = a; + a = b % a; + b = c; + } + return b; +} + +static NSUInteger gcdArray(size_t const count, NSUInteger const * const values) { + if (count == 0) { + return 0; + } + NSUInteger result = values[0]; + for (size_t i = 1; i < count; ++i) { + result = gcd(values[i], result); + } + return result; +} +#endif + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.h new file mode 100644 index 0000000..14b655d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.h @@ -0,0 +1,58 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageCoder.h" + +/** + Global object holding the array of coders, so that we avoid passing them from object to object. + Uses a priority queue behind scenes, which means the latest added coders have the highest priority. + This is done so when encoding/decoding something, we go through the list and ask each coder if they can handle the current data. + That way, users can add their custom coders while preserving our existing prebuilt ones + + Note: the `coders` getter will return the coders in their reversed order + Example: + - by default we internally set coders = `IOCoder`, `GIFCoder`, `APNGCoder` + - calling `coders` will return `@[IOCoder, GIFCoder, APNGCoder]` + - call `[addCoder:[MyCrazyCoder new]]` + - calling `coders` now returns `@[IOCoder, GIFCoder, APNGCoder, MyCrazyCoder]` + + Coders + ------ + A coder must conform to the `SDImageCoder` protocol or even to `SDProgressiveImageCoder` if it supports progressive decoding + Conformance is important because that way, they will implement `canDecodeFromData` or `canEncodeToFormat` + Those methods are called on each coder in the array (using the priority order) until one of them returns YES. + That means that coder can decode that data / encode to that format + */ +@interface SDImageCodersManager : NSObject + +/** + Returns the global shared coders manager instance. + */ +@property (nonatomic, class, readonly, nonnull) SDImageCodersManager *sharedManager; + +/** + All coders in coders manager. The coders array is a priority queue, which means the later added coder will have the highest priority + */ +@property (nonatomic, copy, nullable) NSArray> *coders; + +/** + Add a new coder to the end of coders array. Which has the highest priority. + + @param coder coder + */ +- (void)addCoder:(nonnull id)coder; + +/** + Remove a coder in the coders array. + + @param coder coder + */ +- (void)removeCoder:(nonnull id)coder; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.m new file mode 100644 index 0000000..c49b5e7 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageCodersManager.m @@ -0,0 +1,133 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCodersManager.h" +#import "SDImageIOCoder.h" +#import "SDImageGIFCoder.h" +#import "SDImageAPNGCoder.h" +#import "SDImageHEICCoder.h" +#import "SDInternalMacros.h" + +@interface SDImageCodersManager () + +@property (nonatomic, strong, nonnull) dispatch_semaphore_t codersLock; + +@end + +@implementation SDImageCodersManager +{ + NSMutableArray> *_imageCoders; +} + ++ (nonnull instancetype)sharedManager { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (instancetype)init { + if (self = [super init]) { + // initialize with default coders + _imageCoders = [NSMutableArray arrayWithArray:@[[SDImageIOCoder sharedCoder], [SDImageGIFCoder sharedCoder], [SDImageAPNGCoder sharedCoder]]]; + _codersLock = dispatch_semaphore_create(1); + } + return self; +} + +- (NSArray> *)coders +{ + SD_LOCK(self.codersLock); + NSArray> *coders = [_imageCoders copy]; + SD_UNLOCK(self.codersLock); + return coders; +} + +- (void)setCoders:(NSArray> *)coders +{ + SD_LOCK(self.codersLock); + [_imageCoders removeAllObjects]; + if (coders.count) { + [_imageCoders addObjectsFromArray:coders]; + } + SD_UNLOCK(self.codersLock); +} + +#pragma mark - Coder IO operations + +- (void)addCoder:(nonnull id)coder { + if (![coder conformsToProtocol:@protocol(SDImageCoder)]) { + return; + } + SD_LOCK(self.codersLock); + [_imageCoders addObject:coder]; + SD_UNLOCK(self.codersLock); +} + +- (void)removeCoder:(nonnull id)coder { + if (![coder conformsToProtocol:@protocol(SDImageCoder)]) { + return; + } + SD_LOCK(self.codersLock); + [_imageCoders removeObject:coder]; + SD_UNLOCK(self.codersLock); +} + +#pragma mark - SDImageCoder +- (BOOL)canDecodeFromData:(NSData *)data { + NSArray> *coders = self.coders; + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canDecodeFromData:data]) { + return YES; + } + } + return NO; +} + +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + NSArray> *coders = self.coders; + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canEncodeToFormat:format]) { + return YES; + } + } + return NO; +} + +- (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options { + if (!data) { + return nil; + } + UIImage *image; + NSArray> *coders = self.coders; + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canDecodeFromData:data]) { + image = [coder decodedImageWithData:data options:options]; + break; + } + } + + return image; +} + +- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options { + if (!image) { + return nil; + } + NSArray> *coders = self.coders; + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canEncodeToFormat:format]) { + return [coder encodedDataWithImage:image format:format options:options]; + } + } + return nil; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.h new file mode 100644 index 0000000..a93fd9c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.h @@ -0,0 +1,36 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/** + This class is used for creating animated images via `animatedImageWithFrames` in `SDImageCoderHelper`. + @note If you need to specify animated images loop count, use `sd_imageLoopCount` property in `UIImage+Metadata.h`. + */ +@interface SDImageFrame : NSObject + +/** + The image of current frame. You should not set an animated image. + */ +@property (nonatomic, strong, readonly, nonnull) UIImage *image; +/** + The duration of current frame to be displayed. The number is seconds but not milliseconds. You should not set this to zero. + */ +@property (nonatomic, readonly, assign) NSTimeInterval duration; + +/** + Create a frame instance with specify image and duration + + @param image current frame's image + @param duration current frame's duration + @return frame instance + */ ++ (instancetype _Nonnull)frameWithImage:(UIImage * _Nonnull)image duration:(NSTimeInterval)duration; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.m new file mode 100644 index 0000000..f035af5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageFrame.m @@ -0,0 +1,28 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageFrame.h" + +@interface SDImageFrame () + +@property (nonatomic, strong, readwrite, nonnull) UIImage *image; +@property (nonatomic, readwrite, assign) NSTimeInterval duration; + +@end + +@implementation SDImageFrame + ++ (instancetype)frameWithImage:(UIImage *)image duration:(NSTimeInterval)duration { + SDImageFrame *frame = [[SDImageFrame alloc] init]; + frame.image = image; + frame.duration = duration; + + return frame; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.h new file mode 100644 index 0000000..5ef67ac --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.h @@ -0,0 +1,22 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageIOAnimatedCoder.h" + +/** + Built in coder using ImageIO that supports animated GIF encoding/decoding + @note `SDImageIOCoder` supports GIF but only as static (will use the 1st frame). + @note Use `SDImageGIFCoder` for fully animated GIFs. For `UIImageView`, it will produce animated `UIImage`(`NSImage` on macOS) for rendering. For `SDAnimatedImageView`, it will use `SDAnimatedImage` for rendering. + @note The recommended approach for animated GIFs is using `SDAnimatedImage` with `SDAnimatedImageView`. It's more performant than `UIImageView` for GIF displaying(especially on memory usage) + */ +@interface SDImageGIFCoder : SDImageIOAnimatedCoder + +@property (nonatomic, class, readonly, nonnull) SDImageGIFCoder *sharedCoder; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.m new file mode 100644 index 0000000..e4aaa5d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGIFCoder.m @@ -0,0 +1,57 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageGIFCoder.h" +#if SD_MAC +#import +#else +#import +#endif + +@implementation SDImageGIFCoder + ++ (instancetype)sharedCoder { + static SDImageGIFCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDImageGIFCoder alloc] init]; + }); + return coder; +} + +#pragma mark - Subclass Override + ++ (SDImageFormat)imageFormat { + return SDImageFormatGIF; +} + ++ (NSString *)imageUTType { + return (__bridge NSString *)kUTTypeGIF; +} + ++ (NSString *)dictionaryProperty { + return (__bridge NSString *)kCGImagePropertyGIFDictionary; +} + ++ (NSString *)unclampedDelayTimeProperty { + return (__bridge NSString *)kCGImagePropertyGIFUnclampedDelayTime; +} + ++ (NSString *)delayTimeProperty { + return (__bridge NSString *)kCGImagePropertyGIFDelayTime; +} + ++ (NSString *)loopCountProperty { + return (__bridge NSString *)kCGImagePropertyGIFLoopCount; +} + ++ (NSUInteger)defaultLoopCount { + return 1; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.h new file mode 100644 index 0000000..131d685 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.h @@ -0,0 +1,28 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import + +/** + These following graphics context method are provided to easily write cross-platform(AppKit/UIKit) code. + For UIKit, these methods just call the same method in `UIGraphics.h`. See the documentation for usage. + For AppKit, these methods use `NSGraphicsContext` to create image context and match the behavior like UIKit. + @note If you don't care bitmap format (ARGB8888) and just draw image, use `SDGraphicsImageRenderer` instead. It's more performant on RAM usage.` + */ + +/// Returns the current graphics context. +FOUNDATION_EXPORT CGContextRef __nullable SDGraphicsGetCurrentContext(void) CF_RETURNS_NOT_RETAINED; +/// Creates a bitmap-based graphics context and makes it the current context. +FOUNDATION_EXPORT void SDGraphicsBeginImageContext(CGSize size); +/// Creates a bitmap-based graphics context with the specified options. +FOUNDATION_EXPORT void SDGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale); +/// Removes the current bitmap-based graphics context from the top of the stack. +FOUNDATION_EXPORT void SDGraphicsEndImageContext(void); +/// Returns an image based on the contents of the current bitmap-based graphics context. +FOUNDATION_EXPORT UIImage * __nullable SDGraphicsGetImageFromCurrentImageContext(void); diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.m new file mode 100644 index 0000000..e7c4ed4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageGraphics.m @@ -0,0 +1,105 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageGraphics.h" +#import "NSImage+Compatibility.h" +#import "objc/runtime.h" + +#if SD_MAC +static void *kNSGraphicsContextScaleFactorKey; + +static CGContextRef SDCGContextCreateBitmapContext(CGSize size, BOOL opaque, CGFloat scale) { + if (scale == 0) { + // Match `UIGraphicsBeginImageContextWithOptions`, reset to the scale factor of the device’s main screen if scale is 0. + scale = [NSScreen mainScreen].backingScaleFactor; + } + size_t width = ceil(size.width * scale); + size_t height = ceil(size.height * scale); + if (width < 1 || height < 1) return NULL; + + //pre-multiplied BGRA for non-opaque, BGRX for opaque, 8-bits per component, as Apple's doc + CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); + CGImageAlphaInfo alphaInfo = kCGBitmapByteOrder32Host | (opaque ? kCGImageAlphaNoneSkipFirst : kCGImageAlphaPremultipliedFirst); + CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, kCGBitmapByteOrderDefault | alphaInfo); + CGColorSpaceRelease(space); + if (!context) { + return NULL; + } + CGContextScaleCTM(context, scale, scale); + + return context; +} +#endif + +CGContextRef SDGraphicsGetCurrentContext(void) { +#if SD_UIKIT || SD_WATCH + return UIGraphicsGetCurrentContext(); +#else + return NSGraphicsContext.currentContext.CGContext; +#endif +} + +void SDGraphicsBeginImageContext(CGSize size) { +#if SD_UIKIT || SD_WATCH + UIGraphicsBeginImageContext(size); +#else + SDGraphicsBeginImageContextWithOptions(size, NO, 1.0); +#endif +} + +void SDGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) { +#if SD_UIKIT || SD_WATCH + UIGraphicsBeginImageContextWithOptions(size, opaque, scale); +#else + CGContextRef context = SDCGContextCreateBitmapContext(size, opaque, scale); + if (!context) { + return; + } + NSGraphicsContext *graphicsContext = [NSGraphicsContext graphicsContextWithCGContext:context flipped:NO]; + objc_setAssociatedObject(graphicsContext, &kNSGraphicsContextScaleFactorKey, @(scale), OBJC_ASSOCIATION_RETAIN); + CGContextRelease(context); + [NSGraphicsContext saveGraphicsState]; + NSGraphicsContext.currentContext = graphicsContext; +#endif +} + +void SDGraphicsEndImageContext(void) { +#if SD_UIKIT || SD_WATCH + UIGraphicsEndImageContext(); +#else + [NSGraphicsContext restoreGraphicsState]; +#endif +} + +UIImage * SDGraphicsGetImageFromCurrentImageContext(void) { +#if SD_UIKIT || SD_WATCH + return UIGraphicsGetImageFromCurrentImageContext(); +#else + NSGraphicsContext *context = NSGraphicsContext.currentContext; + CGContextRef contextRef = context.CGContext; + if (!contextRef) { + return nil; + } + CGImageRef imageRef = CGBitmapContextCreateImage(contextRef); + if (!imageRef) { + return nil; + } + CGFloat scale = 0; + NSNumber *scaleFactor = objc_getAssociatedObject(context, &kNSGraphicsContextScaleFactorKey); + if ([scaleFactor isKindOfClass:[NSNumber class]]) { + scale = scaleFactor.doubleValue; + } + if (!scale) { + // reset to the scale factor of the device’s main screen if scale is 0. + scale = [NSScreen mainScreen].backingScaleFactor; + } + NSImage *image = [[NSImage alloc] initWithCGImage:imageRef scale:scale orientation:kCGImagePropertyOrientationUp]; + CGImageRelease(imageRef); + return image; +#endif +} diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.h new file mode 100644 index 0000000..3b6036d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.h @@ -0,0 +1,24 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDImageIOAnimatedCoder.h" + +/** + This coder is used for HEIC (HEIF with HEVC container codec) image format. + Image/IO provide the static HEIC (.heic) support in iOS 11/macOS 10.13/tvOS 11/watchOS 4+. + Image/IO provide the animated HEIC (.heics) support in iOS 13/macOS 10.15/tvOS 13/watchOS 6+. + See https://nokiatech.github.io/heif/technical.html for the standard. + @note This coder is not in the default coder list for now, since HEIC animated image is really rare, and Apple's implementation still contains performance issues. You can enable if you need this. + @note If you need to support lower firmware version for HEIF, you can have a try at https://github.com/SDWebImage/SDWebImageHEIFCoder + */ +@interface SDImageHEICCoder : SDImageIOAnimatedCoder + +@property (nonatomic, class, readonly, nonnull) SDImageHEICCoder *sharedCoder; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.m new file mode 100644 index 0000000..cac53c7 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageHEICCoder.m @@ -0,0 +1,167 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDImageHEICCoder.h" +#import "SDImageHEICCoderInternal.h" + +// These constantce are available from iOS 13+ and Xcode 11. This raw value is used for toolchain and firmware compatiblitiy +static NSString * kSDCGImagePropertyHEICSDictionary = @"{HEICS}"; +static NSString * kSDCGImagePropertyHEICSLoopCount = @"LoopCount"; +static NSString * kSDCGImagePropertyHEICSDelayTime = @"DelayTime"; +static NSString * kSDCGImagePropertyHEICSUnclampedDelayTime = @"UnclampedDelayTime"; + +@implementation SDImageHEICCoder + ++ (void)initialize { +#if __IPHONE_13_0 || __TVOS_13_0 || __MAC_10_15 || __WATCHOS_6_0 + // Xcode 11 + if (@available(iOS 13, tvOS 13, macOS 10.15, watchOS 6, *)) { + // Use SDK instead of raw value + kSDCGImagePropertyHEICSDictionary = (__bridge NSString *)kCGImagePropertyHEICSDictionary; + kSDCGImagePropertyHEICSLoopCount = (__bridge NSString *)kCGImagePropertyHEICSLoopCount; + kSDCGImagePropertyHEICSDelayTime = (__bridge NSString *)kCGImagePropertyHEICSDelayTime; + kSDCGImagePropertyHEICSUnclampedDelayTime = (__bridge NSString *)kCGImagePropertyHEICSUnclampedDelayTime; + } +#endif +} + ++ (instancetype)sharedCoder { + static SDImageHEICCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDImageHEICCoder alloc] init]; + }); + return coder; +} + +#pragma mark - SDImageCoder + +- (BOOL)canDecodeFromData:(nullable NSData *)data { + switch ([NSData sd_imageFormatForImageData:data]) { + case SDImageFormatHEIC: + // Check HEIC decoding compatibility + return [self.class canDecodeFromHEICFormat]; + case SDImageFormatHEIF: + // Check HEIF decoding compatibility + return [self.class canDecodeFromHEIFFormat]; + default: + return NO; + } +} + +- (BOOL)canIncrementalDecodeFromData:(NSData *)data { + return [self canDecodeFromData:data]; +} + +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + switch (format) { + case SDImageFormatHEIC: + // Check HEIC encoding compatibility + return [self.class canEncodeToHEICFormat]; + case SDImageFormatHEIF: + // Check HEIF encoding compatibility + return [self.class canEncodeToHEIFFormat]; + default: + return NO; + } +} + +#pragma mark - HEIF Format + ++ (BOOL)canDecodeFromFormat:(SDImageFormat)format { + CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format]; + NSArray *imageUTTypes = (__bridge_transfer NSArray *)CGImageSourceCopyTypeIdentifiers(); + if ([imageUTTypes containsObject:(__bridge NSString *)(imageUTType)]) { + return YES; + } + return NO; +} + ++ (BOOL)canDecodeFromHEICFormat { + static BOOL canDecode = NO; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + canDecode = [self canDecodeFromFormat:SDImageFormatHEIC]; + }); + return canDecode; +} + ++ (BOOL)canDecodeFromHEIFFormat { + static BOOL canDecode = NO; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + canDecode = [self canDecodeFromFormat:SDImageFormatHEIF]; + }); + return canDecode; +} + ++ (BOOL)canEncodeToFormat:(SDImageFormat)format { + NSMutableData *imageData = [NSMutableData data]; + CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format]; + + // Create an image destination. + CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL); + if (!imageDestination) { + // Can't encode to HEIC + return NO; + } else { + // Can encode to HEIC + CFRelease(imageDestination); + return YES; + } +} + ++ (BOOL)canEncodeToHEICFormat { + static BOOL canEncode = NO; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + canEncode = [self canEncodeToFormat:SDImageFormatHEIC]; + }); + return canEncode; +} + ++ (BOOL)canEncodeToHEIFFormat { + static BOOL canEncode = NO; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + canEncode = [self canEncodeToFormat:SDImageFormatHEIF]; + }); + return canEncode; +} + +#pragma mark - Subclass Override + ++ (SDImageFormat)imageFormat { + return SDImageFormatHEIC; +} + ++ (NSString *)imageUTType { + return (__bridge NSString *)kSDUTTypeHEIC; +} + ++ (NSString *)dictionaryProperty { + return kSDCGImagePropertyHEICSDictionary; +} + ++ (NSString *)unclampedDelayTimeProperty { + return kSDCGImagePropertyHEICSUnclampedDelayTime; +} + ++ (NSString *)delayTimeProperty { + return kSDCGImagePropertyHEICSDelayTime; +} + ++ (NSString *)loopCountProperty { + return kSDCGImagePropertyHEICSLoopCount; +} + ++ (NSUInteger)defaultLoopCount { + return 0; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.h new file mode 100644 index 0000000..4d651e8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.h @@ -0,0 +1,59 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import +#import "SDImageCoder.h" + +/** + This is the abstract class for all animated coder, which use the Image/IO API. You can not use this directly as real coders. A exception will be raised if you use this class. + All of the properties need the subclass to implment and works as expceted. + For Image/IO, See Apple's documentation: https://developer.apple.com/documentation/imageio + */ +@interface SDImageIOAnimatedCoder : NSObject + +#pragma mark - Subclass Override +/** + The supported animated image format. Such as `SDImageFormatGIF`. + @note Subclass override. + */ +@property (class, readonly) SDImageFormat imageFormat; +/** + The supported image format UTI Type. Such as `kUTTypeGIF`. + This can be used for cases when we can not detect `SDImageFormat. Such as progressive decoding's hint format `kCGImageSourceTypeIdentifierHint`. + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *imageUTType; +/** + The image container property key used in Image/IO API. Such as `kCGImagePropertyGIFDictionary`. + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *dictionaryProperty; +/** + The image unclamped deply time property key used in Image/IO API. Such as `kCGImagePropertyGIFUnclampedDelayTime` + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *unclampedDelayTimeProperty; +/** + The image delay time property key used in Image/IO API. Such as `kCGImagePropertyGIFDelayTime`. + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *delayTimeProperty; +/** + The image loop count property key used in Image/IO API. Such as `kCGImagePropertyGIFLoopCount`. + @note Subclass override. + */ +@property (class, readonly, nonnull) NSString *loopCountProperty; +/** + The default loop count when there are no any loop count information inside image container metadata. + For example, for GIF format, the standard use 1 (play once). For APNG format, the standard use 0 (infinity loop). + @note Subclass override. + */ +@property (class, readonly) NSUInteger defaultLoopCount; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.m new file mode 100644 index 0000000..b72dc4e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOAnimatedCoder.m @@ -0,0 +1,548 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDImageIOAnimatedCoder.h" +#import "NSImage+Compatibility.h" +#import "UIImage+Metadata.h" +#import "NSData+ImageContentType.h" +#import "SDImageCoderHelper.h" +#import "SDAnimatedImageRep.h" +#import "UIImage+ForceDecode.h" + +@interface SDImageIOCoderFrame : NSObject + +@property (nonatomic, assign) NSUInteger index; // Frame index (zero based) +@property (nonatomic, assign) NSTimeInterval duration; // Frame duration in seconds + +@end + +@implementation SDImageIOCoderFrame +@end + +@implementation SDImageIOAnimatedCoder { + size_t _width, _height; + CGImageSourceRef _imageSource; + NSData *_imageData; + CGFloat _scale; + NSUInteger _loopCount; + NSUInteger _frameCount; + NSArray *_frames; + BOOL _finished; + BOOL _preserveAspectRatio; + CGSize _thumbnailSize; +} + +- (void)dealloc +{ + if (_imageSource) { + CFRelease(_imageSource); + _imageSource = NULL; + } +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif +} + +- (void)didReceiveMemoryWarning:(NSNotification *)notification +{ + if (_imageSource) { + for (size_t i = 0; i < _frameCount; i++) { + CGImageSourceRemoveCacheAtIndex(_imageSource, i); + } + } +} + +#pragma mark - Subclass Override + ++ (SDImageFormat)imageFormat { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)imageUTType { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)dictionaryProperty { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)unclampedDelayTimeProperty { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)delayTimeProperty { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSString *)loopCountProperty { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + ++ (NSUInteger)defaultLoopCount { + @throw [NSException exceptionWithName:NSInternalInconsistencyException + reason:[NSString stringWithFormat:@"For `SDImageIOAnimatedCoder` subclass, you must override %@ method", NSStringFromSelector(_cmd)] + userInfo:nil]; +} + +#pragma mark - Utils + ++ (NSUInteger)imageLoopCountWithSource:(CGImageSourceRef)source { + NSUInteger loopCount = self.defaultLoopCount; + NSDictionary *imageProperties = (__bridge_transfer NSDictionary *)CGImageSourceCopyProperties(source, nil); + NSDictionary *containerProperties = imageProperties[self.dictionaryProperty]; + if (containerProperties) { + NSNumber *containerLoopCount = containerProperties[self.loopCountProperty]; + if (containerLoopCount != nil) { + loopCount = containerLoopCount.unsignedIntegerValue; + } + } + return loopCount; +} + ++ (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { + NSTimeInterval frameDuration = 0.1; + CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); + if (!cfFrameProperties) { + return frameDuration; + } + NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; + NSDictionary *containerProperties = frameProperties[self.dictionaryProperty]; + + NSNumber *delayTimeUnclampedProp = containerProperties[self.unclampedDelayTimeProperty]; + if (delayTimeUnclampedProp != nil) { + frameDuration = [delayTimeUnclampedProp doubleValue]; + } else { + NSNumber *delayTimeProp = containerProperties[self.delayTimeProperty]; + if (delayTimeProp != nil) { + frameDuration = [delayTimeProp doubleValue]; + } + } + + // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. + // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify + // a duration of <= 10 ms. See and + // for more information. + + if (frameDuration < 0.011) { + frameDuration = 0.1; + } + + CFRelease(cfFrameProperties); + return frameDuration; +} + ++ (UIImage *)createFrameAtIndex:(NSUInteger)index source:(CGImageSourceRef)source scale:(CGFloat)scale preserveAspectRatio:(BOOL)preserveAspectRatio thumbnailSize:(CGSize)thumbnailSize { + // Parse the image properties + NSDictionary *properties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, index, NULL); + NSUInteger pixelWidth = [properties[(__bridge NSString *)kCGImagePropertyPixelWidth] unsignedIntegerValue]; + NSUInteger pixelHeight = [properties[(__bridge NSString *)kCGImagePropertyPixelHeight] unsignedIntegerValue]; + CGImagePropertyOrientation exifOrientation = (CGImagePropertyOrientation)[properties[(__bridge NSString *)kCGImagePropertyOrientation] unsignedIntegerValue]; + if (!exifOrientation) { + exifOrientation = kCGImagePropertyOrientationUp; + } + + CGImageRef imageRef; + if (thumbnailSize.width == 0 || thumbnailSize.height == 0 || (pixelWidth <= thumbnailSize.width && pixelHeight <= thumbnailSize.height)) { + imageRef = CGImageSourceCreateImageAtIndex(source, index, NULL); + } else { + NSMutableDictionary *thumbnailOptions = [NSMutableDictionary dictionary]; + thumbnailOptions[(__bridge NSString *)kCGImageSourceCreateThumbnailWithTransform] = @(preserveAspectRatio); + CGFloat maxPixelSize; + if (preserveAspectRatio) { + CGFloat pixelRatio = pixelWidth / pixelHeight; + CGFloat thumbnailRatio = thumbnailSize.width / thumbnailSize.height; + if (pixelRatio > thumbnailRatio) { + maxPixelSize = thumbnailSize.width; + } else { + maxPixelSize = thumbnailSize.height; + } + } else { + maxPixelSize = MAX(thumbnailSize.width, thumbnailSize.height); + } + thumbnailOptions[(__bridge NSString *)kCGImageSourceThumbnailMaxPixelSize] = @(maxPixelSize); + thumbnailOptions[(__bridge NSString *)kCGImageSourceCreateThumbnailFromImageIfAbsent] = @(YES); + imageRef = CGImageSourceCreateThumbnailAtIndex(source, index, (__bridge CFDictionaryRef)thumbnailOptions); + if (preserveAspectRatio) { + // kCGImageSourceCreateThumbnailWithTransform will apply EXIF transform as well, we should not apply twice + exifOrientation = kCGImagePropertyOrientationUp; + } else { + // `CGImageSourceCreateThumbnailAtIndex` take only pixel dimension, if not `preserveAspectRatio`, we should manual scale to the target size + if (imageRef) { + CGImageRef scaledImageRef = [SDImageCoderHelper CGImageCreateScaled:imageRef size:thumbnailSize]; + CGImageRelease(imageRef); + imageRef = scaledImageRef; + } + } + } + if (!imageRef) { + return nil; + } + +#if SD_UIKIT || SD_WATCH + UIImageOrientation imageOrientation = [SDImageCoderHelper imageOrientationFromEXIFOrientation:exifOrientation]; + UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:scale orientation:imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:scale orientation:exifOrientation]; +#endif + CGImageRelease(imageRef); + return image; +} + +#pragma mark - Decode +- (BOOL)canDecodeFromData:(nullable NSData *)data { + return ([NSData sd_imageFormatForImageData:data] == self.class.imageFormat); +} + +- (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options { + if (!data) { + return nil; + } + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { +#if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; +#else + thumbnailSize = thumbnailSizeValue.CGSizeValue; +#endif + } + + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + +#if SD_MAC + // If don't use thumbnail, prefers the built-in generation of frames (GIF/APNG) + // Which decode frames in time and reduce memory usage + if (thumbnailSize.width == 0 || thumbnailSize.height == 0) { + SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:data]; + NSSize size = NSMakeSize(imageRep.pixelsWide / scale, imageRep.pixelsHigh / scale); + imageRep.size = size; + NSImage *animatedImage = [[NSImage alloc] initWithSize:size]; + [animatedImage addRepresentation:imageRep]; + return animatedImage; + } +#endif + + CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); + if (!source) { + return nil; + } + size_t count = CGImageSourceGetCount(source); + UIImage *animatedImage; + + BOOL decodeFirstFrame = [options[SDImageCoderDecodeFirstFrameOnly] boolValue]; + if (decodeFirstFrame || count <= 1) { + animatedImage = [self.class createFrameAtIndex:0 source:source scale:scale preserveAspectRatio:preserveAspectRatio thumbnailSize:thumbnailSize]; + } else { + NSMutableArray *frames = [NSMutableArray array]; + + for (size_t i = 0; i < count; i++) { + UIImage *image = [self.class createFrameAtIndex:i source:source scale:scale preserveAspectRatio:preserveAspectRatio thumbnailSize:thumbnailSize]; + if (!image) { + continue; + } + + NSTimeInterval duration = [self.class frameDurationAtIndex:i source:source]; + + SDImageFrame *frame = [SDImageFrame frameWithImage:image duration:duration]; + [frames addObject:frame]; + } + + NSUInteger loopCount = [self.class imageLoopCountWithSource:source]; + + animatedImage = [SDImageCoderHelper animatedImageWithFrames:frames]; + animatedImage.sd_imageLoopCount = loopCount; + } + animatedImage.sd_imageFormat = self.class.imageFormat; + CFRelease(source); + + return animatedImage; +} + +#pragma mark - Progressive Decode + +- (BOOL)canIncrementalDecodeFromData:(NSData *)data { + return ([NSData sd_imageFormatForImageData:data] == self.class.imageFormat); +} + +- (instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options { + self = [super init]; + if (self) { + NSString *imageUTType = self.class.imageUTType; + _imageSource = CGImageSourceCreateIncremental((__bridge CFDictionaryRef)@{(__bridge NSString *)kCGImageSourceTypeIdentifierHint : imageUTType}); + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + _scale = scale; + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + #if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; + #else + thumbnailSize = thumbnailSizeValue.CGSizeValue; + #endif + } + _thumbnailSize = thumbnailSize; + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + _preserveAspectRatio = preserveAspectRatio; +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + +- (void)updateIncrementalData:(NSData *)data finished:(BOOL)finished { + if (_finished) { + return; + } + _imageData = data; + _finished = finished; + + // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ + // Thanks to the author @Nyx0uf + + // Update the data source, we must pass ALL the data, not just the new bytes + CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)data, finished); + + if (_width + _height == 0) { + CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL); + if (properties) { + CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); + if (val) CFNumberGetValue(val, kCFNumberLongType, &_height); + val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); + if (val) CFNumberGetValue(val, kCFNumberLongType, &_width); + CFRelease(properties); + } + } + + // For animated image progressive decoding because the frame count and duration may be changed. + [self scanAndCheckFramesValidWithImageSource:_imageSource]; +} + +- (UIImage *)incrementalDecodedImageWithOptions:(SDImageCoderOptions *)options { + UIImage *image; + + if (_width + _height > 0) { + // Create the image + CGFloat scale = _scale; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + image = [SDImageIOAnimatedCoder createFrameAtIndex:0 source:_imageSource scale:scale preserveAspectRatio:_preserveAspectRatio thumbnailSize:_thumbnailSize]; + if (image) { + image.sd_imageFormat = self.class.imageFormat; + } + } + + return image; +} + +#pragma mark - Encode +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + return (format == self.class.imageFormat); +} + +- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options { + if (!image) { + return nil; + } + + if (format != self.class.imageFormat) { + return nil; + } + + NSMutableData *imageData = [NSMutableData data]; + CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format]; + NSArray *frames = [SDImageCoderHelper framesFromAnimatedImage:image]; + + // Create an image destination. Animated Image does not support EXIF image orientation TODO + // The `CGImageDestinationCreateWithData` will log a warning when count is 0, use 1 instead. + CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, frames.count ?: 1, NULL); + if (!imageDestination) { + // Handle failure. + return nil; + } + NSMutableDictionary *properties = [NSMutableDictionary dictionary]; + double compressionQuality = 1; + if (options[SDImageCoderEncodeCompressionQuality]) { + compressionQuality = [options[SDImageCoderEncodeCompressionQuality] doubleValue]; + } + properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = @(compressionQuality); + + BOOL encodeFirstFrame = [options[SDImageCoderEncodeFirstFrameOnly] boolValue]; + if (encodeFirstFrame || frames.count == 0) { + // for static single images + CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)properties); + } else { + // for animated images + NSUInteger loopCount = image.sd_imageLoopCount; + NSDictionary *containerProperties = @{self.class.loopCountProperty : @(loopCount)}; + properties[self.class.dictionaryProperty] = containerProperties; + CGImageDestinationSetProperties(imageDestination, (__bridge CFDictionaryRef)properties); + + for (size_t i = 0; i < frames.count; i++) { + SDImageFrame *frame = frames[i]; + NSTimeInterval frameDuration = frame.duration; + CGImageRef frameImageRef = frame.image.CGImage; + NSDictionary *frameProperties = @{self.class.dictionaryProperty : @{self.class.delayTimeProperty : @(frameDuration)}}; + CGImageDestinationAddImage(imageDestination, frameImageRef, (__bridge CFDictionaryRef)frameProperties); + } + } + // Finalize the destination. + if (CGImageDestinationFinalize(imageDestination) == NO) { + // Handle failure. + imageData = nil; + } + + CFRelease(imageDestination); + + return [imageData copy]; +} + +#pragma mark - SDAnimatedImageCoder +- (nullable instancetype)initWithAnimatedImageData:(nullable NSData *)data options:(nullable SDImageCoderOptions *)options { + if (!data) { + return nil; + } + self = [super init]; + if (self) { + CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); + if (!imageSource) { + return nil; + } + BOOL framesValid = [self scanAndCheckFramesValidWithImageSource:imageSource]; + if (!framesValid) { + CFRelease(imageSource); + return nil; + } + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + _scale = scale; + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + #if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; + #else + thumbnailSize = thumbnailSizeValue.CGSizeValue; + #endif + } + _thumbnailSize = thumbnailSize; + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + _preserveAspectRatio = preserveAspectRatio; + _imageSource = imageSource; + _imageData = data; +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + +- (BOOL)scanAndCheckFramesValidWithImageSource:(CGImageSourceRef)imageSource { + if (!imageSource) { + return NO; + } + NSUInteger frameCount = CGImageSourceGetCount(imageSource); + NSUInteger loopCount = [self.class imageLoopCountWithSource:imageSource]; + NSMutableArray *frames = [NSMutableArray array]; + + for (size_t i = 0; i < frameCount; i++) { + SDImageIOCoderFrame *frame = [[SDImageIOCoderFrame alloc] init]; + frame.index = i; + frame.duration = [self.class frameDurationAtIndex:i source:imageSource]; + [frames addObject:frame]; + } + + _frameCount = frameCount; + _loopCount = loopCount; + _frames = [frames copy]; + + return YES; +} + +- (NSData *)animatedImageData { + return _imageData; +} + +- (NSUInteger)animatedImageLoopCount { + return _loopCount; +} + +- (NSUInteger)animatedImageFrameCount { + return _frameCount; +} + +- (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index { + if (index >= _frameCount) { + return 0; + } + return _frames[index].duration; +} + +- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index { + UIImage *image = [self.class createFrameAtIndex:index source:_imageSource scale:_scale preserveAspectRatio:_preserveAspectRatio thumbnailSize:_thumbnailSize]; + if (!image) { + return nil; + } + image.sd_imageFormat = self.class.imageFormat; + // Image/IO create CGImage does not decode, so we do this because this is called background queue, this can avoid main queue block when rendering(especially when one more imageViews use the same image instance) + CGImageRef imageRef = [SDImageCoderHelper CGImageCreateDecoded:image.CGImage]; + if (!imageRef) { + return image; + } +#if SD_MAC + image = [[UIImage alloc] initWithCGImage:imageRef scale:_scale orientation:kCGImagePropertyOrientationUp]; +#else + image = [[UIImage alloc] initWithCGImage:imageRef scale:_scale orientation:image.imageOrientation]; +#endif + CGImageRelease(imageRef); + image.sd_isDecoded = YES; + image.sd_imageFormat = self.class.imageFormat; + return image; +} + +@end + diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.h new file mode 100644 index 0000000..98682ed --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.h @@ -0,0 +1,30 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDImageCoder.h" + +/** + Built in coder that supports PNG, JPEG, TIFF, includes support for progressive decoding. + + GIF + Also supports static GIF (meaning will only handle the 1st frame). + For a full GIF support, we recommend `SDAnimatedImageView` to keep both CPU and memory balanced. + + HEIC + This coder also supports HEIC format because ImageIO supports it natively. But it depends on the system capabilities, so it won't work on all devices, see: https://devstreaming-cdn.apple.com/videos/wwdc/2017/511tj33587vdhds/511/511_working_with_heif_and_hevc.pdf + Decode(Software): !Simulator && (iOS 11 || tvOS 11 || macOS 10.13) + Decode(Hardware): !Simulator && ((iOS 11 && A9Chip) || (macOS 10.13 && 6thGenerationIntelCPU)) + Encode(Software): macOS 10.13 + Encode(Hardware): !Simulator && ((iOS 11 && A10FusionChip) || (macOS 10.13 && 6thGenerationIntelCPU)) + */ +@interface SDImageIOCoder : NSObject + +@property (nonatomic, class, readonly, nonnull) SDImageIOCoder *sharedCoder; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.m new file mode 100644 index 0000000..f617f43 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageIOCoder.m @@ -0,0 +1,271 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageIOCoder.h" +#import "SDImageCoderHelper.h" +#import "NSImage+Compatibility.h" +#import +#import "UIImage+Metadata.h" +#import "SDImageHEICCoderInternal.h" +#import "SDImageIOAnimatedCoderInternal.h" + +@implementation SDImageIOCoder { + size_t _width, _height; + CGImagePropertyOrientation _orientation; + CGImageSourceRef _imageSource; + CGFloat _scale; + BOOL _finished; + BOOL _preserveAspectRatio; + CGSize _thumbnailSize; +} + +- (void)dealloc { + if (_imageSource) { + CFRelease(_imageSource); + _imageSource = NULL; + } +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif +} + +- (void)didReceiveMemoryWarning:(NSNotification *)notification +{ + if (_imageSource) { + CGImageSourceRemoveCacheAtIndex(_imageSource, 0); + } +} + ++ (instancetype)sharedCoder { + static SDImageIOCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDImageIOCoder alloc] init]; + }); + return coder; +} + +#pragma mark - Decode +- (BOOL)canDecodeFromData:(nullable NSData *)data { + switch ([NSData sd_imageFormatForImageData:data]) { + case SDImageFormatWebP: + // Do not support WebP decoding + return NO; + case SDImageFormatHEIC: + // Check HEIC decoding compatibility + return [SDImageHEICCoder canDecodeFromHEICFormat]; + case SDImageFormatHEIF: + // Check HEIF decoding compatibility + return [SDImageHEICCoder canDecodeFromHEIFFormat]; + default: + return YES; + } +} + +- (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options { + if (!data) { + return nil; + } + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1) ; + } + + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { +#if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; +#else + thumbnailSize = thumbnailSizeValue.CGSizeValue; +#endif + } + + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + + CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); + if (!source) { + return nil; + } + + UIImage *image = [SDImageIOAnimatedCoder createFrameAtIndex:0 source:source scale:scale preserveAspectRatio:preserveAspectRatio thumbnailSize:thumbnailSize]; + CFRelease(source); + if (!image) { + return nil; + } + + image.sd_imageFormat = [NSData sd_imageFormatForImageData:data]; + return image; +} + +#pragma mark - Progressive Decode + +- (BOOL)canIncrementalDecodeFromData:(NSData *)data { + return [self canDecodeFromData:data]; +} + +- (instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options { + self = [super init]; + if (self) { + _imageSource = CGImageSourceCreateIncremental(NULL); + CGFloat scale = 1; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + _scale = scale; + CGSize thumbnailSize = CGSizeZero; + NSValue *thumbnailSizeValue = options[SDImageCoderDecodeThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + #if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; + #else + thumbnailSize = thumbnailSizeValue.CGSizeValue; + #endif + } + _thumbnailSize = thumbnailSize; + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = options[SDImageCoderDecodePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + _preserveAspectRatio = preserveAspectRatio; +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + +- (void)updateIncrementalData:(NSData *)data finished:(BOOL)finished { + if (_finished) { + return; + } + _finished = finished; + + // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ + // Thanks to the author @Nyx0uf + + // Update the data source, we must pass ALL the data, not just the new bytes + CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)data, finished); + + if (_width + _height == 0) { + CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL); + if (properties) { + NSInteger orientationValue = 1; + CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); + if (val) CFNumberGetValue(val, kCFNumberLongType, &_height); + val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); + if (val) CFNumberGetValue(val, kCFNumberLongType, &_width); + val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); + if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); + CFRelease(properties); + + // When we draw to Core Graphics, we lose orientation information, + // which means the image below born of initWithCGIImage will be + // oriented incorrectly sometimes. (Unlike the image born of initWithData + // in didCompleteWithError.) So save it here and pass it on later. + _orientation = (CGImagePropertyOrientation)orientationValue; + } + } +} + +- (UIImage *)incrementalDecodedImageWithOptions:(SDImageCoderOptions *)options { + UIImage *image; + + if (_width + _height > 0) { + // Create the image + CGFloat scale = _scale; + NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor]; + if (scaleFactor != nil) { + scale = MAX([scaleFactor doubleValue], 1); + } + image = [SDImageIOAnimatedCoder createFrameAtIndex:0 source:_imageSource scale:scale preserveAspectRatio:_preserveAspectRatio thumbnailSize:_thumbnailSize]; + if (image) { + CFStringRef uttype = CGImageSourceGetType(_imageSource); + image.sd_imageFormat = [NSData sd_imageFormatFromUTType:uttype]; + } + } + + return image; +} + +#pragma mark - Encode +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + switch (format) { + case SDImageFormatWebP: + // Do not support WebP encoding + return NO; + case SDImageFormatHEIC: + // Check HEIC encoding compatibility + return [SDImageHEICCoder canEncodeToHEICFormat]; + case SDImageFormatHEIF: + // Check HEIF encoding compatibility + return [SDImageHEICCoder canEncodeToHEIFFormat]; + default: + return YES; + } +} + +- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options { + if (!image) { + return nil; + } + + if (format == SDImageFormatUndefined) { + BOOL hasAlpha = [SDImageCoderHelper CGImageContainsAlpha:image.CGImage]; + if (hasAlpha) { + format = SDImageFormatPNG; + } else { + format = SDImageFormatJPEG; + } + } + + NSMutableData *imageData = [NSMutableData data]; + CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format]; + + // Create an image destination. + CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL); + if (!imageDestination) { + // Handle failure. + return nil; + } + + NSMutableDictionary *properties = [NSMutableDictionary dictionary]; +#if SD_UIKIT || SD_WATCH + CGImagePropertyOrientation exifOrientation = [SDImageCoderHelper exifOrientationFromImageOrientation:image.imageOrientation]; +#else + CGImagePropertyOrientation exifOrientation = kCGImagePropertyOrientationUp; +#endif + properties[(__bridge NSString *)kCGImagePropertyOrientation] = @(exifOrientation); + double compressionQuality = 1; + if (options[SDImageCoderEncodeCompressionQuality]) { + compressionQuality = [options[SDImageCoderEncodeCompressionQuality] doubleValue]; + } + properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = @(compressionQuality); + + // Add your image to the destination. + CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)properties); + + // Finalize the destination. + if (CGImageDestinationFinalize(imageDestination) == NO) { + // Handle failure. + imageData = nil; + } + + CFRelease(imageDestination); + + return [imageData copy]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.h new file mode 100644 index 0000000..941268c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.h @@ -0,0 +1,101 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDWebImageOperation.h" + +typedef void(^SDImageLoaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL); +typedef void(^SDImageLoaderCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished); + +#pragma mark - Context Options + +/** + A `UIImage` instance from `SDWebImageManager` when you specify `SDWebImageRefreshCached` and image cache hit. + This can be a hint for image loader to load the image from network and refresh the image from remote location if needed. If the image from remote location does not change, you should call the completion with `SDWebImageErrorCacheNotModified` error. (UIImage) + @note If you don't implement `SDWebImageRefreshCached` support, you do not need to care abot this context option. + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextLoaderCachedImage; + +#pragma mark - Helper method + +/** + This is the built-in decoding process for image download from network or local file. + @note If you want to implement your custom loader with `requestImageWithURL:options:context:progress:completed:` API, but also want to keep compatible with SDWebImage's behavior, you'd better use this to produce image. + + @param imageData The image data from the network. Should not be nil + @param imageURL The image URL from the input. Should not be nil + @param options The options arg from the input + @param context The context arg from the input + @return The decoded image for current image data load from the network + */ +FOUNDATION_EXPORT UIImage * _Nullable SDImageLoaderDecodeImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, SDWebImageOptions options, SDWebImageContext * _Nullable context); + +/** + This is the built-in decoding process for image progressive download from network. It's used when `SDWebImageProgressiveLoad` option is set. (It's not required when your loader does not support progressive image loading) + @note If you want to implement your custom loader with `requestImageWithURL:options:context:progress:completed:` API, but also want to keep compatible with SDWebImage's behavior, you'd better use this to produce image. + + @param imageData The image data from the network so far. Should not be nil + @param imageURL The image URL from the input. Should not be nil + @param finished Pass NO to specify the download process has not finished. Pass YES when all image data has finished. + @param operation The loader operation associated with current progressive download. Why to provide this is because progressive decoding need to store the partial decoded context for each operation to avoid conflict. You should provide the operation from `loadImageWithURL:` method return value. + @param options The options arg from the input + @param context The context arg from the input + @return The decoded progressive image for current image data load from the network + */ +FOUNDATION_EXPORT UIImage * _Nullable SDImageLoaderDecodeProgressiveImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, BOOL finished, id _Nonnull operation, SDWebImageOptions options, SDWebImageContext * _Nullable context); + +#pragma mark - SDImageLoader + +/** + This is the protocol to specify custom image load process. You can create your own class to conform this protocol and use as a image loader to load image from network or any avaiable remote resources defined by yourself. + If you want to implement custom loader for image download from network or local file, you just need to concentrate on image data download only. After the download finish, call `SDImageLoaderDecodeImageData` or `SDImageLoaderDecodeProgressiveImageData` to use the built-in decoding process and produce image (Remember to call in the global queue). And finally callback the completion block. + If you directlly get the image instance using some third-party SDKs, such as image directlly from Photos framework. You can process the image data and image instance by yourself without that built-in decoding process. And finally callback the completion block. + @note It's your responsibility to load the image in the desired global queue(to avoid block main queue). We do not dispatch these method call in a global queue but just from the call queue (For `SDWebImageManager`, it typically call from the main queue). +*/ +@protocol SDImageLoader + +/** + Whether current image loader supports to load the provide image URL. + This will be checked everytime a new image request come for loader. If this return NO, we will mark this image load as failed. If return YES, we will start to call `requestImageWithURL:options:context:progress:completed:`. + + @param url The image URL to be loaded. + @return YES to continue download, NO to stop download. + */ +- (BOOL)canRequestImageForURL:(nullable NSURL *)url; + +/** + Load the image and image data with the given URL and return the image data. You're responsible for producing the image instance. + + @param url The URL represent the image. Note this may not be a HTTP URL + @param options A mask to specify options to use for this request + @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + @param completedBlock A block called when operation has been completed. + @return An operation which allow the user to cancel the current request. + */ +- (nullable id)requestImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDImageLoaderCompletedBlock)completedBlock; + + +/** + Whether the error from image loader should be marked indded un-recoverable or not. + If this return YES, failed URL which does not using `SDWebImageRetryFailed` will be blocked into black list. Else not. + + @param url The URL represent the image. Note this may not be a HTTP URL + @param error The URL's loading error, from previous `requestImageWithURL:options:context:progress:completed:` completedBlock's error. + @return Whether to block this url or not. Return YES to mark this URL as failed. + */ +- (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url + error:(nonnull NSError *)error; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.m new file mode 100644 index 0000000..4c831c5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoader.m @@ -0,0 +1,185 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageLoader.h" +#import "SDWebImageCacheKeyFilter.h" +#import "SDImageCodersManager.h" +#import "SDImageCoderHelper.h" +#import "SDAnimatedImage.h" +#import "UIImage+Metadata.h" +#import "SDInternalMacros.h" +#import "objc/runtime.h" + +static void * SDImageLoaderProgressiveCoderKey = &SDImageLoaderProgressiveCoderKey; + +UIImage * _Nullable SDImageLoaderDecodeImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, SDWebImageOptions options, SDWebImageContext * _Nullable context) { + NSCParameterAssert(imageData); + NSCParameterAssert(imageURL); + + UIImage *image; + id cacheKeyFilter = context[SDWebImageContextCacheKeyFilter]; + NSString *cacheKey; + if (cacheKeyFilter) { + cacheKey = [cacheKeyFilter cacheKeyForURL:imageURL]; + } else { + cacheKey = imageURL.absoluteString; + } + BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly); + NSNumber *scaleValue = context[SDWebImageContextImageScaleFactor]; + CGFloat scale = scaleValue.doubleValue >= 1 ? scaleValue.doubleValue : SDImageScaleFactorForKey(cacheKey); + NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio]; + NSValue *thumbnailSizeValue; + BOOL shouldScaleDown = SD_OPTIONS_CONTAINS(options, SDWebImageScaleDownLargeImages); + if (shouldScaleDown) { + CGFloat thumbnailPixels = SDImageCoderHelper.defaultScaleDownLimitBytes / 4; + CGFloat dimension = ceil(sqrt(thumbnailPixels)); + thumbnailSizeValue = @(CGSizeMake(dimension, dimension)); + } + if (context[SDWebImageContextImageThumbnailPixelSize]) { + thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize]; + } + + SDImageCoderMutableOptions *mutableCoderOptions = [NSMutableDictionary dictionaryWithCapacity:2]; + mutableCoderOptions[SDImageCoderDecodeFirstFrameOnly] = @(decodeFirstFrame); + mutableCoderOptions[SDImageCoderDecodeScaleFactor] = @(scale); + mutableCoderOptions[SDImageCoderDecodePreserveAspectRatio] = preserveAspectRatioValue; + mutableCoderOptions[SDImageCoderDecodeThumbnailPixelSize] = thumbnailSizeValue; + mutableCoderOptions[SDImageCoderWebImageContext] = context; + SDImageCoderOptions *coderOptions = [mutableCoderOptions copy]; + + if (!decodeFirstFrame) { + // check whether we should use `SDAnimatedImage` + Class animatedImageClass = context[SDWebImageContextAnimatedImageClass]; + if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)]) { + image = [[animatedImageClass alloc] initWithData:imageData scale:scale options:coderOptions]; + if (image) { + // Preload frames if supported + if (options & SDWebImagePreloadAllFrames && [image respondsToSelector:@selector(preloadAllFrames)]) { + [((id)image) preloadAllFrames]; + } + } else { + // Check image class matching + if (options & SDWebImageMatchAnimatedImageClass) { + return nil; + } + } + } + } + if (!image) { + image = [[SDImageCodersManager sharedManager] decodedImageWithData:imageData options:coderOptions]; + } + if (image) { + BOOL shouldDecode = !SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage); + if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)]) { + // `SDAnimatedImage` do not decode + shouldDecode = NO; + } else if (image.sd_isAnimated) { + // animated image do not decode + shouldDecode = NO; + } + + if (shouldDecode) { + image = [SDImageCoderHelper decodedImageWithImage:image]; + } + } + + return image; +} + +UIImage * _Nullable SDImageLoaderDecodeProgressiveImageData(NSData * _Nonnull imageData, NSURL * _Nonnull imageURL, BOOL finished, id _Nonnull operation, SDWebImageOptions options, SDWebImageContext * _Nullable context) { + NSCParameterAssert(imageData); + NSCParameterAssert(imageURL); + NSCParameterAssert(operation); + + UIImage *image; + id cacheKeyFilter = context[SDWebImageContextCacheKeyFilter]; + NSString *cacheKey; + if (cacheKeyFilter) { + cacheKey = [cacheKeyFilter cacheKeyForURL:imageURL]; + } else { + cacheKey = imageURL.absoluteString; + } + BOOL decodeFirstFrame = SD_OPTIONS_CONTAINS(options, SDWebImageDecodeFirstFrameOnly); + NSNumber *scaleValue = context[SDWebImageContextImageScaleFactor]; + CGFloat scale = scaleValue.doubleValue >= 1 ? scaleValue.doubleValue : SDImageScaleFactorForKey(cacheKey); + NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio]; + NSValue *thumbnailSizeValue; + BOOL shouldScaleDown = SD_OPTIONS_CONTAINS(options, SDWebImageScaleDownLargeImages); + if (shouldScaleDown) { + CGFloat thumbnailPixels = SDImageCoderHelper.defaultScaleDownLimitBytes / 4; + CGFloat dimension = ceil(sqrt(thumbnailPixels)); + thumbnailSizeValue = @(CGSizeMake(dimension, dimension)); + } + if (context[SDWebImageContextImageThumbnailPixelSize]) { + thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize]; + } + + SDImageCoderMutableOptions *mutableCoderOptions = [NSMutableDictionary dictionaryWithCapacity:2]; + mutableCoderOptions[SDImageCoderDecodeFirstFrameOnly] = @(decodeFirstFrame); + mutableCoderOptions[SDImageCoderDecodeScaleFactor] = @(scale); + mutableCoderOptions[SDImageCoderDecodePreserveAspectRatio] = preserveAspectRatioValue; + mutableCoderOptions[SDImageCoderDecodeThumbnailPixelSize] = thumbnailSizeValue; + mutableCoderOptions[SDImageCoderWebImageContext] = context; + SDImageCoderOptions *coderOptions = [mutableCoderOptions copy]; + + id progressiveCoder = objc_getAssociatedObject(operation, SDImageLoaderProgressiveCoderKey); + if (!progressiveCoder) { + // We need to create a new instance for progressive decoding to avoid conflicts + for (idcoder in [SDImageCodersManager sharedManager].coders.reverseObjectEnumerator) { + if ([coder conformsToProtocol:@protocol(SDProgressiveImageCoder)] && + [((id)coder) canIncrementalDecodeFromData:imageData]) { + progressiveCoder = [[[coder class] alloc] initIncrementalWithOptions:coderOptions]; + break; + } + } + objc_setAssociatedObject(operation, SDImageLoaderProgressiveCoderKey, progressiveCoder, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + // If we can't find any progressive coder, disable progressive download + if (!progressiveCoder) { + return nil; + } + + [progressiveCoder updateIncrementalData:imageData finished:finished]; + if (!decodeFirstFrame) { + // check whether we should use `SDAnimatedImage` + Class animatedImageClass = context[SDWebImageContextAnimatedImageClass]; + if ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)] && [progressiveCoder conformsToProtocol:@protocol(SDAnimatedImageCoder)]) { + image = [[animatedImageClass alloc] initWithAnimatedCoder:(id)progressiveCoder scale:scale]; + if (image) { + // Progressive decoding does not preload frames + } else { + // Check image class matching + if (options & SDWebImageMatchAnimatedImageClass) { + return nil; + } + } + } + } + if (!image) { + image = [progressiveCoder incrementalDecodedImageWithOptions:coderOptions]; + } + if (image) { + BOOL shouldDecode = !SD_OPTIONS_CONTAINS(options, SDWebImageAvoidDecodeImage); + if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)]) { + // `SDAnimatedImage` do not decode + shouldDecode = NO; + } else if (image.sd_isAnimated) { + // animated image do not decode + shouldDecode = NO; + } + if (shouldDecode) { + image = [SDImageCoderHelper decodedImageWithImage:image]; + } + // mark the image as progressive (completionBlock one are not mark as progressive) + image.sd_isIncremental = YES; + } + + return image; +} + +SDWebImageContextOption const SDWebImageContextLoaderCachedImage = @"loaderCachedImage"; diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.h new file mode 100644 index 0000000..d80887e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.h @@ -0,0 +1,40 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageLoader.h" + +/** + A loaders manager to manage multiple loaders + */ +@interface SDImageLoadersManager : NSObject + +/** + Returns the global shared loaders manager instance. By default we will set [`SDWebImageDownloader.sharedDownloader`] into the loaders array. + */ +@property (nonatomic, class, readonly, nonnull) SDImageLoadersManager *sharedManager; + +/** + All image loaders in manager. The loaders array is a priority queue, which means the later added loader will have the highest priority + */ +@property (nonatomic, copy, nullable) NSArray>* loaders; + +/** + Add a new image loader to the end of loaders array. Which has the highest priority. + + @param loader loader + */ +- (void)addLoader:(nonnull id)loader; + +/** + Remove a image loader in the loaders array. + + @param loader loader + */ +- (void)removeLoader:(nonnull id)loader; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.m new file mode 100644 index 0000000..0c48e21 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageLoadersManager.m @@ -0,0 +1,114 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageLoadersManager.h" +#import "SDWebImageDownloader.h" +#import "SDInternalMacros.h" + +@interface SDImageLoadersManager () + +@property (nonatomic, strong, nonnull) dispatch_semaphore_t loadersLock; + +@end + +@implementation SDImageLoadersManager +{ + NSMutableArray>* _imageLoaders; +} + ++ (SDImageLoadersManager *)sharedManager { + static dispatch_once_t onceToken; + static SDImageLoadersManager *manager; + dispatch_once(&onceToken, ^{ + manager = [[SDImageLoadersManager alloc] init]; + }); + return manager; +} + +- (instancetype)init { + self = [super init]; + if (self) { + // initialize with default image loaders + _imageLoaders = [NSMutableArray arrayWithObject:[SDWebImageDownloader sharedDownloader]]; + _loadersLock = dispatch_semaphore_create(1); + } + return self; +} + +- (NSArray> *)loaders { + SD_LOCK(self.loadersLock); + NSArray>* loaders = [_imageLoaders copy]; + SD_UNLOCK(self.loadersLock); + return loaders; +} + +- (void)setLoaders:(NSArray> *)loaders { + SD_LOCK(self.loadersLock); + [_imageLoaders removeAllObjects]; + if (loaders.count) { + [_imageLoaders addObjectsFromArray:loaders]; + } + SD_UNLOCK(self.loadersLock); +} + +#pragma mark - Loader Property + +- (void)addLoader:(id)loader { + if (![loader conformsToProtocol:@protocol(SDImageLoader)]) { + return; + } + SD_LOCK(self.loadersLock); + [_imageLoaders addObject:loader]; + SD_UNLOCK(self.loadersLock); +} + +- (void)removeLoader:(id)loader { + if (![loader conformsToProtocol:@protocol(SDImageLoader)]) { + return; + } + SD_LOCK(self.loadersLock); + [_imageLoaders removeObject:loader]; + SD_UNLOCK(self.loadersLock); +} + +#pragma mark - SDImageLoader + +- (BOOL)canRequestImageForURL:(nullable NSURL *)url { + NSArray> *loaders = self.loaders; + for (id loader in loaders.reverseObjectEnumerator) { + if ([loader canRequestImageForURL:url]) { + return YES; + } + } + return NO; +} + +- (id)requestImageWithURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDImageLoaderCompletedBlock)completedBlock { + if (!url) { + return nil; + } + NSArray> *loaders = self.loaders; + for (id loader in loaders.reverseObjectEnumerator) { + if ([loader canRequestImageForURL:url]) { + return [loader requestImageWithURL:url options:options context:context progress:progressBlock completed:completedBlock]; + } + } + return nil; +} + +- (BOOL)shouldBlockFailedURLWithURL:(NSURL *)url error:(NSError *)error { + NSArray> *loaders = self.loaders; + for (id loader in loaders.reverseObjectEnumerator) { + if ([loader canRequestImageForURL:url]) { + return [loader shouldBlockFailedURLWithURL:url error:error]; + } + } + return NO; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.h new file mode 100644 index 0000000..f165cce --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.h @@ -0,0 +1,231 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "UIImage+Transform.h" + +/** + Return the transformed cache key which applied with specify transformerKey. + + @param key The original cache key + @param transformerKey The transformer key from the transformer + @return The transformed cache key + */ +FOUNDATION_EXPORT NSString * _Nullable SDTransformedKeyForKey(NSString * _Nullable key, NSString * _Nonnull transformerKey); + +/** + A transformer protocol to transform the image load from cache or from download. + You can provide transformer to cache and manager (Through the `transformer` property or context option `SDWebImageContextImageTransformer`). + + @note The transform process is called from a global queue in order to not to block the main queue. + */ +@protocol SDImageTransformer + +@required +/** + For each transformer, it must contains its cache key to used to store the image cache or query from the cache. This key will be appened after the original cache key generated by URL or from user. + + @return The cache key to appended after the original cache key. Should not be nil. + */ +@property (nonatomic, copy, readonly, nonnull) NSString *transformerKey; + +/** + Transform the image to another image. + + @param image The image to be transformed + @param key The cache key associated to the image + @return The transformed image, or nil if transform failed + */ +- (nullable UIImage *)transformedImageWithImage:(nonnull UIImage *)image forKey:(nonnull NSString *)key; + +@end + +#pragma mark - Pipeline + +/** + Pipeline transformer. Which you can bind multiple transformers together to let the image to be transformed one by one in order and generate the final image. + @note Because transformers are lightweight, if you want to append or arrange transfomers, create another pipeline transformer instead. This class is considered as immutable. + */ +@interface SDImagePipelineTransformer : NSObject + +/** + All transformers in pipeline + */ +@property (nonatomic, copy, readonly, nonnull) NSArray> *transformers; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)transformerWithTransformers:(nonnull NSArray> *)transformers; + +@end + +// There are some built-in transformers based on the `UIImage+Transformer` category to provide the common image geometry, image blending and image effect process. Those transform are useful for static image only but you can create your own to support animated image as well. +// Because transformers are lightweight, these class are considered as immutable. +#pragma mark - Image Geometry + +/** + Image round corner transformer + */ +@interface SDImageRoundCornerTransformer: NSObject + +/** + The radius of each corner oval. Values larger than half the + rectangle's width or height are clamped appropriately to + half the width or height. + */ +@property (nonatomic, assign, readonly) CGFloat cornerRadius; + +/** + A bitmask value that identifies the corners that you want + rounded. You can use this parameter to round only a subset + of the corners of the rectangle. + */ +@property (nonatomic, assign, readonly) SDRectCorner corners; + +/** + The inset border line width. Values larger than half the rectangle's + width or height are clamped appropriately to half the width + or height. + */ +@property (nonatomic, assign, readonly) CGFloat borderWidth; + +/** + The border stroke color. nil means clear color. + */ +@property (nonatomic, strong, readonly, nullable) UIColor *borderColor; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)transformerWithRadius:(CGFloat)cornerRadius corners:(SDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(nullable UIColor *)borderColor; + +@end + +/** + Image resizing transformer + */ +@interface SDImageResizingTransformer : NSObject + +/** + The new size to be resized, values should be positive. + */ +@property (nonatomic, assign, readonly) CGSize size; + +/** + The scale mode for image content. + */ +@property (nonatomic, assign, readonly) SDImageScaleMode scaleMode; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)transformerWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode; + +@end + +/** + Image cropping transformer + */ +@interface SDImageCroppingTransformer : NSObject + +/** + Image's inner rect. + */ +@property (nonatomic, assign, readonly) CGRect rect; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)transformerWithRect:(CGRect)rect; + +@end + +/** + Image flipping transformer + */ +@interface SDImageFlippingTransformer : NSObject + +/** + YES to flip the image horizontally. ⇋ + */ +@property (nonatomic, assign, readonly) BOOL horizontal; + +/** + YES to flip the image vertically. ⥯ + */ +@property (nonatomic, assign, readonly) BOOL vertical; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)transformerWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical; + +@end + +/** + Image rotation transformer + */ +@interface SDImageRotationTransformer : NSObject + +/** + Rotated radians in counterclockwise.⟲ + */ +@property (nonatomic, assign, readonly) CGFloat angle; + +/** + YES: new image's size is extend to fit all content. + NO: image's size will not change, content may be clipped. + */ +@property (nonatomic, assign, readonly) BOOL fitSize; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)transformerWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize; + +@end + +#pragma mark - Image Blending + +/** + Image tint color transformer + */ +@interface SDImageTintTransformer : NSObject + +/** + The tint color. + */ +@property (nonatomic, strong, readonly, nonnull) UIColor *tintColor; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)transformerWithColor:(nonnull UIColor *)tintColor; + +@end + +#pragma mark - Image Effect + +/** + Image blur effect transformer + */ +@interface SDImageBlurTransformer : NSObject + +/** + The radius of the blur in points, 0 means no blur effect. + */ +@property (nonatomic, assign, readonly) CGFloat blurRadius; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)transformerWithRadius:(CGFloat)blurRadius; + +@end + +#if SD_UIKIT || SD_MAC +/** + Core Image filter transformer + */ +@interface SDImageFilterTransformer: NSObject + +/** + The CIFilter to be applied to the image. + */ +@property (nonatomic, strong, readonly, nonnull) CIFilter *filter; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)transformerWithFilter:(nonnull CIFilter *)filter; + +@end +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.m new file mode 100644 index 0000000..26ee45c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDImageTransformer.m @@ -0,0 +1,326 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageTransformer.h" +#import "UIColor+HexString.h" +#if SD_UIKIT || SD_MAC +#import +#endif + +// Separator for different transformerKey, for example, `image.png` |> flip(YES,NO) |> rotate(pi/4,YES) => 'image-SDImageFlippingTransformer(1,0)-SDImageRotationTransformer(0.78539816339,1).png' +static NSString * const SDImageTransformerKeySeparator = @"-"; + +NSString * _Nullable SDTransformedKeyForKey(NSString * _Nullable key, NSString * _Nonnull transformerKey) { + if (!key || !transformerKey) { + return nil; + } + // Find the file extension + NSURL *keyURL = [NSURL URLWithString:key]; + NSString *ext = keyURL ? keyURL.pathExtension : key.pathExtension; + if (ext.length > 0) { + // For non-file URL + if (keyURL && !keyURL.isFileURL) { + // keep anything except path (like URL query) + NSURLComponents *component = [NSURLComponents componentsWithURL:keyURL resolvingAgainstBaseURL:NO]; + component.path = [[[component.path.stringByDeletingPathExtension stringByAppendingString:SDImageTransformerKeySeparator] stringByAppendingString:transformerKey] stringByAppendingPathExtension:ext]; + return component.URL.absoluteString; + } else { + // file URL + return [[[key.stringByDeletingPathExtension stringByAppendingString:SDImageTransformerKeySeparator] stringByAppendingString:transformerKey] stringByAppendingPathExtension:ext]; + } + } else { + return [[key stringByAppendingString:SDImageTransformerKeySeparator] stringByAppendingString:transformerKey]; + } +} + +@interface SDImagePipelineTransformer () + +@property (nonatomic, copy, readwrite, nonnull) NSArray> *transformers; +@property (nonatomic, copy, readwrite) NSString *transformerKey; + +@end + +@implementation SDImagePipelineTransformer + ++ (instancetype)transformerWithTransformers:(NSArray> *)transformers { + SDImagePipelineTransformer *transformer = [SDImagePipelineTransformer new]; + transformer.transformers = transformers; + transformer.transformerKey = [[self class] cacheKeyForTransformers:transformers]; + + return transformer; +} + ++ (NSString *)cacheKeyForTransformers:(NSArray> *)transformers { + if (transformers.count == 0) { + return @""; + } + NSMutableArray *cacheKeys = [NSMutableArray arrayWithCapacity:transformers.count]; + [transformers enumerateObjectsUsingBlock:^(id _Nonnull transformer, NSUInteger idx, BOOL * _Nonnull stop) { + NSString *cacheKey = transformer.transformerKey; + [cacheKeys addObject:cacheKey]; + }]; + + return [cacheKeys componentsJoinedByString:SDImageTransformerKeySeparator]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + UIImage *transformedImage = image; + for (id transformer in self.transformers) { + transformedImage = [transformer transformedImageWithImage:transformedImage forKey:key]; + } + return transformedImage; +} + +@end + +@interface SDImageRoundCornerTransformer () + +@property (nonatomic, assign) CGFloat cornerRadius; +@property (nonatomic, assign) SDRectCorner corners; +@property (nonatomic, assign) CGFloat borderWidth; +@property (nonatomic, strong, nullable) UIColor *borderColor; + +@end + +@implementation SDImageRoundCornerTransformer + ++ (instancetype)transformerWithRadius:(CGFloat)cornerRadius corners:(SDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor { + SDImageRoundCornerTransformer *transformer = [SDImageRoundCornerTransformer new]; + transformer.cornerRadius = cornerRadius; + transformer.corners = corners; + transformer.borderWidth = borderWidth; + transformer.borderColor = borderColor; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageRoundCornerTransformer(%f,%lu,%f,%@)", self.cornerRadius, (unsigned long)self.corners, self.borderWidth, self.borderColor.sd_hexString]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_roundedCornerImageWithRadius:self.cornerRadius corners:self.corners borderWidth:self.borderWidth borderColor:self.borderColor]; +} + +@end + +@interface SDImageResizingTransformer () + +@property (nonatomic, assign) CGSize size; +@property (nonatomic, assign) SDImageScaleMode scaleMode; + +@end + +@implementation SDImageResizingTransformer + ++ (instancetype)transformerWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode { + SDImageResizingTransformer *transformer = [SDImageResizingTransformer new]; + transformer.size = size; + transformer.scaleMode = scaleMode; + + return transformer; +} + +- (NSString *)transformerKey { + CGSize size = self.size; + return [NSString stringWithFormat:@"SDImageResizingTransformer({%f,%f},%lu)", size.width, size.height, (unsigned long)self.scaleMode]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_resizedImageWithSize:self.size scaleMode:self.scaleMode]; +} + +@end + +@interface SDImageCroppingTransformer () + +@property (nonatomic, assign) CGRect rect; + +@end + +@implementation SDImageCroppingTransformer + ++ (instancetype)transformerWithRect:(CGRect)rect { + SDImageCroppingTransformer *transformer = [SDImageCroppingTransformer new]; + transformer.rect = rect; + + return transformer; +} + +- (NSString *)transformerKey { + CGRect rect = self.rect; + return [NSString stringWithFormat:@"SDImageCroppingTransformer({%f,%f,%f,%f})", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_croppedImageWithRect:self.rect]; +} + +@end + +@interface SDImageFlippingTransformer () + +@property (nonatomic, assign) BOOL horizontal; +@property (nonatomic, assign) BOOL vertical; + +@end + +@implementation SDImageFlippingTransformer + ++ (instancetype)transformerWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical { + SDImageFlippingTransformer *transformer = [SDImageFlippingTransformer new]; + transformer.horizontal = horizontal; + transformer.vertical = vertical; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageFlippingTransformer(%d,%d)", self.horizontal, self.vertical]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_flippedImageWithHorizontal:self.horizontal vertical:self.vertical]; +} + +@end + +@interface SDImageRotationTransformer () + +@property (nonatomic, assign) CGFloat angle; +@property (nonatomic, assign) BOOL fitSize; + +@end + +@implementation SDImageRotationTransformer + ++ (instancetype)transformerWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize { + SDImageRotationTransformer *transformer = [SDImageRotationTransformer new]; + transformer.angle = angle; + transformer.fitSize = fitSize; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageRotationTransformer(%f,%d)", self.angle, self.fitSize]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_rotatedImageWithAngle:self.angle fitSize:self.fitSize]; +} + +@end + +#pragma mark - Image Blending + +@interface SDImageTintTransformer () + +@property (nonatomic, strong, nonnull) UIColor *tintColor; + +@end + +@implementation SDImageTintTransformer + ++ (instancetype)transformerWithColor:(UIColor *)tintColor { + SDImageTintTransformer *transformer = [SDImageTintTransformer new]; + transformer.tintColor = tintColor; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageTintTransformer(%@)", self.tintColor.sd_hexString]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_tintedImageWithColor:self.tintColor]; +} + +@end + +#pragma mark - Image Effect + +@interface SDImageBlurTransformer () + +@property (nonatomic, assign) CGFloat blurRadius; + +@end + +@implementation SDImageBlurTransformer + ++ (instancetype)transformerWithRadius:(CGFloat)blurRadius { + SDImageBlurTransformer *transformer = [SDImageBlurTransformer new]; + transformer.blurRadius = blurRadius; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageBlurTransformer(%f)", self.blurRadius]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_blurredImageWithRadius:self.blurRadius]; +} + +@end + +#if SD_UIKIT || SD_MAC +@interface SDImageFilterTransformer () + +@property (nonatomic, strong, nonnull) CIFilter *filter; + +@end + +@implementation SDImageFilterTransformer + ++ (instancetype)transformerWithFilter:(CIFilter *)filter { + SDImageFilterTransformer *transformer = [SDImageFilterTransformer new]; + transformer.filter = filter; + + return transformer; +} + +- (NSString *)transformerKey { + return [NSString stringWithFormat:@"SDImageFilterTransformer(%@)", self.filter.name]; +} + +- (UIImage *)transformedImageWithImage:(UIImage *)image forKey:(NSString *)key { + if (!image) { + return nil; + } + return [image sd_filteredImageWithFilter:self.filter]; +} + +@end +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.h new file mode 100644 index 0000000..43c39e8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.h @@ -0,0 +1,78 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +@class SDImageCacheConfig; +/** + A protocol to allow custom memory cache used in SDImageCache. + */ +@protocol SDMemoryCache + +@required + +/** + Create a new memory cache instance with the specify cache config. You can check `maxMemoryCost` and `maxMemoryCount` used for memory cache. + + @param config The cache config to be used to create the cache. + @return The new memory cache instance. + */ +- (nonnull instancetype)initWithConfig:(nonnull SDImageCacheConfig *)config; + +/** + Returns the value associated with a given key. + + @param key An object identifying the value. If nil, just return nil. + @return The value associated with key, or nil if no value is associated with key. + */ +- (nullable id)objectForKey:(nonnull id)key; + +/** + Sets the value of the specified key in the cache (0 cost). + + @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`. + @param key The key with which to associate the value. If nil, this method has no effect. + @discussion Unlike an NSMutableDictionary object, a cache does not copy the key + objects that are put into it. + */ +- (void)setObject:(nullable id)object forKey:(nonnull id)key; + +/** + Sets the value of the specified key in the cache, and associates the key-value + pair with the specified cost. + + @param object The object to store in the cache. If nil, it calls `removeObjectForKey`. + @param key The key with which to associate the value. If nil, this method has no effect. + @param cost The cost with which to associate the key-value pair. + @discussion Unlike an NSMutableDictionary object, a cache does not copy the key + objects that are put into it. + */ +- (void)setObject:(nullable id)object forKey:(nonnull id)key cost:(NSUInteger)cost; + +/** + Removes the value of the specified key in the cache. + + @param key The key identifying the value to be removed. If nil, this method has no effect. + */ +- (void)removeObjectForKey:(nonnull id)key; + +/** + Empties the cache immediately. + */ +- (void)removeAllObjects; + +@end + +/** + A memory cache which auto purge the cache on memory warning and support weak cache. + */ +@interface SDMemoryCache : NSCache + +@property (nonatomic, strong, nonnull, readonly) SDImageCacheConfig *config; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.m new file mode 100644 index 0000000..b354b49 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDMemoryCache.m @@ -0,0 +1,155 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDMemoryCache.h" +#import "SDImageCacheConfig.h" +#import "UIImage+MemoryCacheCost.h" +#import "SDInternalMacros.h" + +static void * SDMemoryCacheContext = &SDMemoryCacheContext; + +@interface SDMemoryCache () + +@property (nonatomic, strong, nullable) SDImageCacheConfig *config; +#if SD_UIKIT +@property (nonatomic, strong, nonnull) NSMapTable *weakCache; // strong-weak cache +@property (nonatomic, strong, nonnull) dispatch_semaphore_t weakCacheLock; // a lock to keep the access to `weakCache` thread-safe +#endif +@end + +@implementation SDMemoryCache + +- (void)dealloc { + [_config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCost)) context:SDMemoryCacheContext]; + [_config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCount)) context:SDMemoryCacheContext]; +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + self.delegate = nil; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _config = [[SDImageCacheConfig alloc] init]; + [self commonInit]; + } + return self; +} + +- (instancetype)initWithConfig:(SDImageCacheConfig *)config { + self = [super init]; + if (self) { + _config = config; + [self commonInit]; + } + return self; +} + +- (void)commonInit { + SDImageCacheConfig *config = self.config; + self.totalCostLimit = config.maxMemoryCost; + self.countLimit = config.maxMemoryCount; + + [config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCost)) options:0 context:SDMemoryCacheContext]; + [config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCount)) options:0 context:SDMemoryCacheContext]; + +#if SD_UIKIT + self.weakCache = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0]; + self.weakCacheLock = dispatch_semaphore_create(1); + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(didReceiveMemoryWarning:) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; +#endif +} + +// Current this seems no use on macOS (macOS use virtual memory and do not clear cache when memory warning). So we only override on iOS/tvOS platform. +#if SD_UIKIT +- (void)didReceiveMemoryWarning:(NSNotification *)notification { + // Only remove cache, but keep weak cache + [super removeAllObjects]; +} + +// `setObject:forKey:` just call this with 0 cost. Override this is enough +- (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)g { + [super setObject:obj forKey:key cost:g]; + if (!self.config.shouldUseWeakMemoryCache) { + return; + } + if (key && obj) { + // Store weak cache + SD_LOCK(self.weakCacheLock); + [self.weakCache setObject:obj forKey:key]; + SD_UNLOCK(self.weakCacheLock); + } +} + +- (id)objectForKey:(id)key { + id obj = [super objectForKey:key]; + if (!self.config.shouldUseWeakMemoryCache) { + return obj; + } + if (key && !obj) { + // Check weak cache + SD_LOCK(self.weakCacheLock); + obj = [self.weakCache objectForKey:key]; + SD_UNLOCK(self.weakCacheLock); + if (obj) { + // Sync cache + NSUInteger cost = 0; + if ([obj isKindOfClass:[UIImage class]]) { + cost = [(UIImage *)obj sd_memoryCost]; + } + [super setObject:obj forKey:key cost:cost]; + } + } + return obj; +} + +- (void)removeObjectForKey:(id)key { + [super removeObjectForKey:key]; + if (!self.config.shouldUseWeakMemoryCache) { + return; + } + if (key) { + // Remove weak cache + SD_LOCK(self.weakCacheLock); + [self.weakCache removeObjectForKey:key]; + SD_UNLOCK(self.weakCacheLock); + } +} + +- (void)removeAllObjects { + [super removeAllObjects]; + if (!self.config.shouldUseWeakMemoryCache) { + return; + } + // Manually remove should also remove weak cache + SD_LOCK(self.weakCacheLock); + [self.weakCache removeAllObjects]; + SD_UNLOCK(self.weakCacheLock); +} +#endif + +#pragma mark - KVO + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if (context == SDMemoryCacheContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(maxMemoryCost))]) { + self.totalCostLimit = self.config.maxMemoryCost; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(maxMemoryCount))]) { + self.countLimit = self.config.maxMemoryCount; + } + } else { + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + } +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.h new file mode 100644 index 0000000..4f54dd8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.h @@ -0,0 +1,32 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NSString * _Nullable(^SDWebImageCacheKeyFilterBlock)(NSURL * _Nonnull url); + +/** + This is the protocol for cache key filter. + We can use a block to specify the cache key filter. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. + */ +@protocol SDWebImageCacheKeyFilter + +- (nullable NSString *)cacheKeyForURL:(nonnull NSURL *)url; + +@end + +/** + A cache key filter class with block. + */ +@interface SDWebImageCacheKeyFilter : NSObject + +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageCacheKeyFilterBlock)block; ++ (nonnull instancetype)cacheKeyFilterWithBlock:(nonnull SDWebImageCacheKeyFilterBlock)block; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.m new file mode 100644 index 0000000..b4ebb8b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheKeyFilter.m @@ -0,0 +1,39 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCacheKeyFilter.h" + +@interface SDWebImageCacheKeyFilter () + +@property (nonatomic, copy, nonnull) SDWebImageCacheKeyFilterBlock block; + +@end + +@implementation SDWebImageCacheKeyFilter + +- (instancetype)initWithBlock:(SDWebImageCacheKeyFilterBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)cacheKeyFilterWithBlock:(SDWebImageCacheKeyFilterBlock)block { + SDWebImageCacheKeyFilter *cacheKeyFilter = [[SDWebImageCacheKeyFilter alloc] initWithBlock:block]; + return cacheKeyFilter; +} + +- (NSString *)cacheKeyForURL:(NSURL *)url { + if (!self.block) { + return nil; + } + return self.block(url); +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.h new file mode 100644 index 0000000..3c271b1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.h @@ -0,0 +1,36 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NSData * _Nullable(^SDWebImageCacheSerializerBlock)(UIImage * _Nonnull image, NSData * _Nullable data, NSURL * _Nullable imageURL); + +/** + This is the protocol for cache serializer. + We can use a block to specify the cache serializer. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. + */ +@protocol SDWebImageCacheSerializer + +/// Provide the image data associated to the image and store to disk cache +/// @param image The loaded image +/// @param data The original loaded image data +/// @param imageURL The image URL +- (nullable NSData *)cacheDataWithImage:(nonnull UIImage *)image originalData:(nullable NSData *)data imageURL:(nullable NSURL *)imageURL; + +@end + +/** + A cache serializer class with block. + */ +@interface SDWebImageCacheSerializer : NSObject + +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageCacheSerializerBlock)block; ++ (nonnull instancetype)cacheSerializerWithBlock:(nonnull SDWebImageCacheSerializerBlock)block; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.m new file mode 100644 index 0000000..51528e6 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCacheSerializer.m @@ -0,0 +1,39 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCacheSerializer.h" + +@interface SDWebImageCacheSerializer () + +@property (nonatomic, copy, nonnull) SDWebImageCacheSerializerBlock block; + +@end + +@implementation SDWebImageCacheSerializer + +- (instancetype)initWithBlock:(SDWebImageCacheSerializerBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)cacheSerializerWithBlock:(SDWebImageCacheSerializerBlock)block { + SDWebImageCacheSerializer *cacheSerializer = [[SDWebImageCacheSerializer alloc] initWithBlock:block]; + return cacheSerializer; +} + +- (NSData *)cacheDataWithImage:(UIImage *)image originalData:(NSData *)data imageURL:(nullable NSURL *)imageURL { + if (!self.block) { + return nil; + } + return self.block(image, data, imageURL); +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.h new file mode 100644 index 0000000..f47a248 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.h @@ -0,0 +1,95 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Jamie Pinkham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +#ifdef __OBJC_GC__ + #error SDWebImage does not support Objective-C Garbage Collection +#endif + +// Seems like TARGET_OS_MAC is always defined (on all platforms). +// To determine if we are running on macOS, use TARGET_OS_OSX in Xcode 8 +#if TARGET_OS_OSX + #define SD_MAC 1 +#else + #define SD_MAC 0 +#endif + +// iOS and tvOS are very similar, UIKit exists on both platforms +// Note: watchOS also has UIKit, but it's very limited +#if TARGET_OS_IOS || TARGET_OS_TV + #define SD_UIKIT 1 +#else + #define SD_UIKIT 0 +#endif + +#if TARGET_OS_IOS + #define SD_IOS 1 +#else + #define SD_IOS 0 +#endif + +#if TARGET_OS_TV + #define SD_TV 1 +#else + #define SD_TV 0 +#endif + +#if TARGET_OS_WATCH + #define SD_WATCH 1 +#else + #define SD_WATCH 0 +#endif + + +#if SD_MAC + #import + #ifndef UIImage + #define UIImage NSImage + #endif + #ifndef UIImageView + #define UIImageView NSImageView + #endif + #ifndef UIView + #define UIView NSView + #endif + #ifndef UIColor + #define UIColor NSColor + #endif +#else + #if SD_UIKIT + #import + #endif + #if SD_WATCH + #import + #ifndef UIView + #define UIView WKInterfaceObject + #endif + #ifndef UIImageView + #define UIImageView WKInterfaceImage + #endif + #endif +#endif + +#ifndef NS_ENUM +#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type +#endif + +#ifndef NS_OPTIONS +#define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type +#endif + +#ifndef dispatch_main_async_safe +#define dispatch_main_async_safe(block)\ + if (dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) == dispatch_queue_get_label(dispatch_get_main_queue())) {\ + block();\ + } else {\ + dispatch_async(dispatch_get_main_queue(), block);\ + } +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.m new file mode 100644 index 0000000..1297401 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageCompat.m @@ -0,0 +1,17 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if !__has_feature(objc_arc) + #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag +#endif + +#if !OS_OBJECT_USE_OBJC + #error SDWebImage need ARC for dispatch object +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.h new file mode 100644 index 0000000..bd4d4e6 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.h @@ -0,0 +1,278 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +typedef void(^SDWebImageNoParamsBlock)(void); +typedef NSString * SDWebImageContextOption NS_EXTENSIBLE_STRING_ENUM; +typedef NSDictionary SDWebImageContext; +typedef NSMutableDictionary SDWebImageMutableContext; + +#pragma mark - Image scale + +/** + Return the image scale factor for the specify key, supports file name and url key. + This is the built-in way to check the scale factor when we have no context about it. Because scale factor is not stored in image data (It's typically from filename). + However, you can also provide custom scale factor as well, see `SDWebImageContextImageScaleFactor`. + + @param key The image cache key + @return The scale factor for image + */ +FOUNDATION_EXPORT CGFloat SDImageScaleFactorForKey(NSString * _Nullable key); + +/** + Scale the image with the scale factor for the specify key. If no need to scale, return the original image. + This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`. + @note This is actually a convenience function, which firstlly call `SDImageScaleFactorForKey` and then call `SDScaledImageForScaleFactor`, kept for backward compatibility. + + @param key The image cache key + @param image The image + @return The scaled image + */ +FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image); + +/** + Scale the image with the scale factor. If no need to scale, return the original image. + This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`. + + @param scale The image scale factor + @param image The image + @return The scaled image + */ +FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForScaleFactor(CGFloat scale, UIImage * _Nullable image); + +#pragma mark - WebCache Options + +/// WebCache options +typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { + /** + * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. + * This flag disable this blacklisting. + */ + SDWebImageRetryFailed = 1 << 0, + + /** + * By default, image downloads are started during UI interactions, this flags disable this feature, + * leading to delayed download on UIScrollView deceleration for instance. + */ + SDWebImageLowPriority = 1 << 1, + + /** + * This flag enables progressive download, the image is displayed progressively during download as a browser would do. + * By default, the image is only displayed once completely downloaded. + */ + SDWebImageProgressiveLoad = 1 << 2, + + /** + * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. + * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. + * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. + * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. + * + * Use this flag only if you can't make your URLs static with embedded cache busting parameter. + */ + SDWebImageRefreshCached = 1 << 3, + + /** + * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for + * extra time in background to let the request finish. If the background task expires the operation will be cancelled. + */ + SDWebImageContinueInBackground = 1 << 4, + + /** + * Handles cookies stored in NSHTTPCookieStore by setting + * NSMutableURLRequest.HTTPShouldHandleCookies = YES; + */ + SDWebImageHandleCookies = 1 << 5, + + /** + * Enable to allow untrusted SSL certificates. + * Useful for testing purposes. Use with caution in production. + */ + SDWebImageAllowInvalidSSLCertificates = 1 << 6, + + /** + * By default, images are loaded in the order in which they were queued. This flag moves them to + * the front of the queue. + */ + SDWebImageHighPriority = 1 << 7, + + /** + * By default, placeholder images are loaded while the image is loading. This flag will delay the loading + * of the placeholder image until after the image has finished loading. + */ + SDWebImageDelayPlaceholder = 1 << 8, + + /** + * We usually don't apply transform on animated images as most transformers could not manage animated images. + * Use this flag to transform them anyway. + */ + SDWebImageTransformAnimatedImage = 1 << 9, + + /** + * By default, image is added to the imageView after download. But in some cases, we want to + * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) + * Use this flag if you want to manually set the image in the completion when success + */ + SDWebImageAvoidAutoSetImage = 1 << 10, + + /** + * By default, images are decoded respecting their original size. + * This flag will scale down the images to a size compatible with the constrained memory of devices. + * To control the limit memory bytes, check `SDImageCoderHelper.defaultScaleDownLimitBytes` (Defaults to 60MB on iOS) + * This will actually translate to use context option `.imageThumbnailPixelSize` from v5.5.0 (Defaults to (3966, 3966) on iOS). Previously does not. + * This flags effect the progressive and animated images as well from v5.5.0. Previously does not. + * @note If you need detail controls, it's better to use context option `imageThumbnailPixelSize` and `imagePreserveAspectRatio` instead. + */ + SDWebImageScaleDownLargeImages = 1 << 11, + + /** + * By default, we do not query image data when the image is already cached in memory. This mask can force to query image data at the same time. However, this query is asynchronously unless you specify `SDWebImageQueryMemoryDataSync` + */ + SDWebImageQueryMemoryData = 1 << 12, + + /** + * By default, when you only specify `SDWebImageQueryMemoryData`, we query the memory image data asynchronously. Combined this mask as well to query the memory image data synchronously. + * @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing. + */ + SDWebImageQueryMemoryDataSync = 1 << 13, + + /** + * By default, when the memory cache miss, we query the disk cache asynchronously. This mask can force to query disk cache (when memory cache miss) synchronously. + * @note These 3 query options can be combined together. For the full list about these masks combination, see wiki page. + * @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing. + */ + SDWebImageQueryDiskDataSync = 1 << 14, + + /** + * By default, when the cache missed, the image is load from the loader. This flag can prevent this to load from cache only. + */ + SDWebImageFromCacheOnly = 1 << 15, + + /** + * By default, we query the cache before the image is load from the loader. This flag can prevent this to load from loader only. + */ + SDWebImageFromLoaderOnly = 1 << 16, + + /** + * By default, when you use `SDWebImageTransition` to do some view transition after the image load finished, this transition is only applied for image download from the network. This mask can force to apply view transition for memory and disk cache as well. + */ + SDWebImageForceTransition = 1 << 17, + + /** + * By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation. + * However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image. + */ + SDWebImageAvoidDecodeImage = 1 << 18, + + /** + * By default, we decode the animated image. This flag can force decode the first frame only and produece the static image. + */ + SDWebImageDecodeFirstFrameOnly = 1 << 19, + + /** + * By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. However, you can specify to preload all frames into memory to reduce CPU usage when the animated image is shared by lots of imageViews. + * This will actually trigger `preloadAllAnimatedImageFrames` in the background queue(Disk Cache & Download only). + */ + SDWebImagePreloadAllFrames = 1 << 20, + + /** + * By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available to produce one exactlly matching your custom class as a fallback solution. + * Using this option, can ensure we always callback image with your provided class. If failed to produce one, a error with code `SDWebImageErrorBadImageData` will been used. + * Note this options is not compatible with `SDWebImageDecodeFirstFrameOnly`, which always produce a UIImage/NSImage. + */ + SDWebImageMatchAnimatedImageClass = 1 << 21, + + /** + * By default, when we load the image from network, the image will be written to the cache (memory and disk, controlled by your `storeCacheType` context option) + * This maybe an asynchronously operation and the final `SDInternalCompletionBlock` callback does not gurantee the disk cache written is finished and may cause logic error. (For example, you modify the disk data just in completion block, however, the disk cache is not ready) + * If you need to process with the disk cache in the completion block, you should use this option to ensure the disk cache already been written when callback. + * Note if you use this when using the custom cache serializer, or using the transformer, we will also wait until the output image data written is finished. + */ + SDWebImageWaitStoreCache = 1 << 22, +}; + + +#pragma mark - Context Options + +/** + A String to be used as the operation key for view category to store the image load operation. This is used for view instance which supports different image loading process. If nil, will use the class name as operation key. (NSString *) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextSetImageOperationKey; + +/** + A SDWebImageManager instance to control the image download and cache process using in UIImageView+WebCache category and likes. If not provided, use the shared manager (SDWebImageManager *) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCustomManager; + +/** + A id instance which conforms `SDImageTransformer` protocol. It's used for image transform after the image load finished and store the transformed image to cache. If you provide one, it will ignore the `transformer` in manager and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageTransformer; + +/** + A CGFloat raw value which specify the image scale factor. The number should be greater than or equal to 1.0. If not provide or the number is invalid, we will use the cache key to specify the scale factor. (NSNumber) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageScaleFactor; + +/** + A Boolean value indicating whether to keep the original aspect ratio when generating thumbnail images (or bitmap images from vector format). + Defaults to YES. (NSNumber) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImagePreserveAspectRatio; + +/** + A CGSize raw value indicating whether or not to generate the thumbnail images (or bitmap images from vector format). When this value is provided, the decoder will generate a thumbnail image which pixel size is smaller than or equal to (depends the `.imagePreserveAspectRatio`) the value size. + @note When you pass `.preserveAspectRatio == NO`, the thumbnail image is stretched to match each dimension. When `.preserveAspectRatio == YES`, the thumbnail image's width is limited to pixel size's width, the thumbnail image's height is limited to pixel size's height. For common cases, you can just pass a square size to limit both. + Defaults to CGSizeZero, which means no thumbnail generation at all. (NSValue) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageThumbnailPixelSize; + +/** + A SDImageCacheType raw value which specify the store cache type when the image has just been downloaded and will be stored to the cache. Specify `SDImageCacheTypeNone` to disable cache storage; `SDImageCacheTypeDisk` to store in disk cache only; `SDImageCacheTypeMemory` to store in memory only. And `SDImageCacheTypeAll` to store in both memory cache and disk cache. + If you use image transformer feature, this actually apply for the transformed image, but not the original image itself. Use `SDWebImageContextOriginalStoreCacheType` if you want to control the original image's store cache type at the same time. + If not provide or the value is invalid, we will use `SDImageCacheTypeAll`. (NSNumber) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextStoreCacheType; + +/** + The same behavior like `SDWebImageContextStoreCacheType`, but control the store cache type for the original image when you use image transformer feature. This allows the detail control of cache storage for these two images. For example, if you want to store the transformed image into both memory/disk cache, store the original image into disk cache only, use `[.storeCacheType : .all, .originalStoreCacheType : .disk]` + If not provide or the value is invalid, we will use `SDImageCacheTypeNone`, which does not store the original image into cache. (NSNumber) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextOriginalStoreCacheType; + +/** + A Class object which the instance is a `UIImage/NSImage` subclass and adopt `SDAnimatedImage` protocol. We will call `initWithData:scale:options:` to create the instance (or `initWithAnimatedCoder:scale:` when using progressive download) . If the instance create failed, fallback to normal `UIImage/NSImage`. + This can be used to improve animated images rendering performance (especially memory usage on big animated images) with `SDAnimatedImageView` (Class). + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextAnimatedImageClass; + +/** + A id instance to modify the image download request. It's used for downloader to modify the original request from URL and options. If you provide one, it will ignore the `requestModifier` in downloader and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadRequestModifier; + +/** + A id instance to modify the image download response. It's used for downloader to modify the original response from URL and options. If you provide one, it will ignore the `responseModifier` in downloader and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadResponseModifier; + +/** + A id instance to decrypt the image download data. This can be used for image data decryption, such as Base64 encoded image. If you provide one, it will ignore the `decryptor` in downloader and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadDecryptor; + +/** + A id instance to convert an URL into a cache key. It's used when manager need cache key to use image cache. If you provide one, it will ignore the `cacheKeyFilter` in manager and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheKeyFilter; + +/** + A id instance to convert the decoded image, the source downloaded data, to the actual data. It's used for manager to store image to the disk cache. If you provide one, it will ignore the `cacheSerializer` in manager and use provided one instead. (id) + */ +FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheSerializer; diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.m new file mode 100644 index 0000000..921e878 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDefine.m @@ -0,0 +1,134 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDefine.h" +#import "UIImage+Metadata.h" +#import "NSImage+Compatibility.h" +#import "SDAssociatedObject.h" + +#pragma mark - Image scale + +static inline NSArray * _Nonnull SDImageScaleFactors() { + return @[@2, @3]; +} + +inline CGFloat SDImageScaleFactorForKey(NSString * _Nullable key) { + CGFloat scale = 1; + if (!key) { + return scale; + } + // Check if target OS support scale +#if SD_WATCH + if ([[WKInterfaceDevice currentDevice] respondsToSelector:@selector(screenScale)]) +#elif SD_UIKIT + if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) +#elif SD_MAC + if ([[NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)]) +#endif + { + // a@2x.png -> 8 + if (key.length >= 8) { + // Fast check + BOOL isURL = [key hasPrefix:@"http://"] || [key hasPrefix:@"https://"]; + for (NSNumber *scaleFactor in SDImageScaleFactors()) { + // @2x. for file name and normal url + NSString *fileScale = [NSString stringWithFormat:@"@%@x.", scaleFactor]; + if ([key containsString:fileScale]) { + scale = scaleFactor.doubleValue; + return scale; + } + if (isURL) { + // %402x. for url encode + NSString *urlScale = [NSString stringWithFormat:@"%%40%@x.", scaleFactor]; + if ([key containsString:urlScale]) { + scale = scaleFactor.doubleValue; + return scale; + } + } + } + } + } + return scale; +} + +inline UIImage * _Nullable SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image) { + if (!image) { + return nil; + } + CGFloat scale = SDImageScaleFactorForKey(key); + return SDScaledImageForScaleFactor(scale, image); +} + +inline UIImage * _Nullable SDScaledImageForScaleFactor(CGFloat scale, UIImage * _Nullable image) { + if (!image) { + return nil; + } + if (scale <= 1) { + return image; + } + if (scale == image.scale) { + return image; + } + UIImage *scaledImage; + if (image.sd_isAnimated) { + UIImage *animatedImage; +#if SD_UIKIT || SD_WATCH + // `UIAnimatedImage` images share the same size and scale. + NSMutableArray *scaledImages = [NSMutableArray array]; + + for (UIImage *tempImage in image.images) { + UIImage *tempScaledImage = [[UIImage alloc] initWithCGImage:tempImage.CGImage scale:scale orientation:tempImage.imageOrientation]; + [scaledImages addObject:tempScaledImage]; + } + + animatedImage = [UIImage animatedImageWithImages:scaledImages duration:image.duration]; + animatedImage.sd_imageLoopCount = image.sd_imageLoopCount; +#else + // Animated GIF for `NSImage` need to grab `NSBitmapImageRep`; + NSRect imageRect = NSMakeRect(0, 0, image.size.width, image.size.height); + NSImageRep *imageRep = [image bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (bitmapImageRep) { + NSSize size = NSMakeSize(image.size.width / scale, image.size.height / scale); + animatedImage = [[NSImage alloc] initWithSize:size]; + bitmapImageRep.size = size; + [animatedImage addRepresentation:bitmapImageRep]; + } +#endif + scaledImage = animatedImage; + } else { +#if SD_UIKIT || SD_WATCH + scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; +#else + scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:kCGImagePropertyOrientationUp]; +#endif + } + SDImageCopyAssociatedObject(image, scaledImage); + + return scaledImage; +} + +#pragma mark - Context option + +SDWebImageContextOption const SDWebImageContextSetImageOperationKey = @"setImageOperationKey"; +SDWebImageContextOption const SDWebImageContextCustomManager = @"customManager"; +SDWebImageContextOption const SDWebImageContextImageTransformer = @"imageTransformer"; +SDWebImageContextOption const SDWebImageContextImageScaleFactor = @"imageScaleFactor"; +SDWebImageContextOption const SDWebImageContextImagePreserveAspectRatio = @"imagePreserveAspectRatio"; +SDWebImageContextOption const SDWebImageContextImageThumbnailPixelSize = @"imageThumbnailPixelSize"; +SDWebImageContextOption const SDWebImageContextStoreCacheType = @"storeCacheType"; +SDWebImageContextOption const SDWebImageContextOriginalStoreCacheType = @"originalStoreCacheType"; +SDWebImageContextOption const SDWebImageContextAnimatedImageClass = @"animatedImageClass"; +SDWebImageContextOption const SDWebImageContextDownloadRequestModifier = @"downloadRequestModifier"; +SDWebImageContextOption const SDWebImageContextDownloadResponseModifier = @"downloadResponseModifier"; +SDWebImageContextOption const SDWebImageContextDownloadDecryptor = @"downloadDecryptor"; +SDWebImageContextOption const SDWebImageContextCacheKeyFilter = @"cacheKeyFilter"; +SDWebImageContextOption const SDWebImageContextCacheSerializer = @"cacheSerializer"; diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.h new file mode 100644 index 0000000..571b72a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.h @@ -0,0 +1,309 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDWebImageOperation.h" +#import "SDWebImageDownloaderConfig.h" +#import "SDWebImageDownloaderRequestModifier.h" +#import "SDWebImageDownloaderResponseModifier.h" +#import "SDWebImageDownloaderDecryptor.h" +#import "SDImageLoader.h" + +/// Downloader options +typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { + /** + * Put the download in the low queue priority and task priority. + */ + SDWebImageDownloaderLowPriority = 1 << 0, + + /** + * This flag enables progressive download, the image is displayed progressively during download as a browser would do. + */ + SDWebImageDownloaderProgressiveLoad = 1 << 1, + + /** + * By default, request prevent the use of NSURLCache. With this flag, NSURLCache + * is used with default policies. + */ + SDWebImageDownloaderUseNSURLCache = 1 << 2, + + /** + * Call completion block with nil image/imageData if the image was read from NSURLCache + * And the error code is `SDWebImageErrorCacheNotModified` + * This flag should be combined with `SDWebImageDownloaderUseNSURLCache`. + */ + SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, + + /** + * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for + * extra time in background to let the request finish. If the background task expires the operation will be cancelled. + */ + SDWebImageDownloaderContinueInBackground = 1 << 4, + + /** + * Handles cookies stored in NSHTTPCookieStore by setting + * NSMutableURLRequest.HTTPShouldHandleCookies = YES; + */ + SDWebImageDownloaderHandleCookies = 1 << 5, + + /** + * Enable to allow untrusted SSL certificates. + * Useful for testing purposes. Use with caution in production. + */ + SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, + + /** + * Put the download in the high queue priority and task priority. + */ + SDWebImageDownloaderHighPriority = 1 << 7, + + /** + * By default, images are decoded respecting their original size. On iOS, this flag will scale down the + * images to a size compatible with the constrained memory of devices. + * This flag take no effect if `SDWebImageDownloaderAvoidDecodeImage` is set. And it will be ignored if `SDWebImageDownloaderProgressiveLoad` is set. + */ + SDWebImageDownloaderScaleDownLargeImages = 1 << 8, + + /** + * By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation. + * However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image. + */ + SDWebImageDownloaderAvoidDecodeImage = 1 << 9, + + /** + * By default, we decode the animated image. This flag can force decode the first frame only and produece the static image. + */ + SDWebImageDownloaderDecodeFirstFrameOnly = 1 << 10, + + /** + * By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. This flag actually trigger `preloadAllAnimatedImageFrames = YES` after image load from network + */ + SDWebImageDownloaderPreloadAllFrames = 1 << 11, + + /** + * By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available, to behave as a fallback solution. + * Using this option, can ensure we always produce image with your provided class. If failed, a error with code `SDWebImageErrorBadImageData` will been used. + * Note this options is not compatible with `SDWebImageDownloaderDecodeFirstFrameOnly`, which always produce a UIImage/NSImage. + */ + SDWebImageDownloaderMatchAnimatedImageClass = 1 << 12, +}; + +FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadStartNotification; +FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadReceiveResponseNotification; +FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadStopNotification; +FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadFinishNotification; + +typedef SDImageLoaderProgressBlock SDWebImageDownloaderProgressBlock; +typedef SDImageLoaderCompletedBlock SDWebImageDownloaderCompletedBlock; + +/** + * A token associated with each download. Can be used to cancel a download + */ +@interface SDWebImageDownloadToken : NSObject + +/** + Cancel the current download. + */ +- (void)cancel; + +/** + The download's URL. + */ +@property (nonatomic, strong, nullable, readonly) NSURL *url; + +/** + The download's request. + */ +@property (nonatomic, strong, nullable, readonly) NSURLRequest *request; + +/** + The download's response. + */ +@property (nonatomic, strong, nullable, readonly) NSURLResponse *response; + +@end + + +/** + * Asynchronous downloader dedicated and optimized for image loading. + */ +@interface SDWebImageDownloader : NSObject + +/** + * Downloader Config object - storing all kind of settings. + * Most config properties support dynamic changes during download, except something like `sessionConfiguration`, see `SDWebImageDownloaderConfig` for more detail. + */ +@property (nonatomic, copy, readonly, nonnull) SDWebImageDownloaderConfig *config; + +/** + * Set the request modifier to modify the original download request before image load. + * This request modifier method will be called for each downloading image request. Return the original request means no modification. Return nil will cancel the download request. + * Defaults to nil, means does not modify the original download request. + * @note If you want to modify single request, consider using `SDWebImageContextDownloadRequestModifier` context option. + */ +@property (nonatomic, strong, nullable) id requestModifier; + +/** + * Set the response modifier to modify the original download response during image load. + * This request modifier method will be called for each downloading image response. Return the original response means no modification. Return nil will mark current download as cancelled. + * Defaults to nil, means does not modify the original download response. + * @note If you want to modify single response, consider using `SDWebImageContextDownloadResponseModifier` context option. + */ +@property (nonatomic, strong, nullable) id responseModifier; + +/** + * Set the decryptor to decrypt the original download data before image decoding. This can be used for encrypted image data, like Base64. + * This decryptor method will be called for each downloading image data. Return the original data means no modification. Return nil will mark this download failed. + * Defaults to nil, means does not modify the original download data. + * @note When using decryptor, progressive decoding will be disabled, to avoid data corrupt issue. + * @note If you want to decrypt single download data, consider using `SDWebImageContextDownloadDecryptor` context option. + */ +@property (nonatomic, strong, nullable) id decryptor; + +/** + * The configuration in use by the internal NSURLSession. If you want to provide a custom sessionConfiguration, use `SDWebImageDownloaderConfig.sessionConfiguration` and create a new downloader instance. + @note This is immutable according to NSURLSession's documentation. Mutating this object directly has no effect. + */ +@property (nonatomic, readonly, nonnull) NSURLSessionConfiguration *sessionConfiguration; + +/** + * Gets/Sets the download queue suspension state. + */ +@property (nonatomic, assign, getter=isSuspended) BOOL suspended; + +/** + * Shows the current amount of downloads that still need to be downloaded + */ +@property (nonatomic, assign, readonly) NSUInteger currentDownloadCount; + +/** + * Returns the global shared downloader instance. Which use the `SDWebImageDownloaderConfig.defaultDownloaderConfig` config. + */ +@property (nonatomic, class, readonly, nonnull) SDWebImageDownloader *sharedDownloader; + +/** + Creates an instance of a downloader with specified downloader config. + You can specify session configuration, timeout or operation class through downloader config. + + @param config The downloader config. If you specify nil, the `defaultDownloaderConfig` will be used. + @return new instance of downloader class + */ +- (nonnull instancetype)initWithConfig:(nullable SDWebImageDownloaderConfig *)config NS_DESIGNATED_INITIALIZER; + +/** + * Set a value for a HTTP header to be appended to each download HTTP request. + * + * @param value The value for the header field. Use `nil` value to remove the header field. + * @param field The name of the header field to set. + */ +- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field; + +/** + * Returns the value of the specified HTTP header field. + * + * @return The value associated with the header field field, or `nil` if there is no corresponding header field. + */ +- (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field; + +/** + * Creates a SDWebImageDownloader async downloader instance with a given URL + * + * The delegate will be informed when the image is finish downloaded or an error has happen. + * + * @see SDWebImageDownloaderDelegate + * + * @param url The URL to the image to download + * @param completedBlock A block called once the download is completed. + * If the download succeeded, the image parameter is set, in case of error, + * error parameter is set with the error. The last parameter is always YES + * if SDWebImageDownloaderProgressiveDownload isn't use. With the + * SDWebImageDownloaderProgressiveDownload option, this block is called + * repeatedly with the partial image object and the finished argument set to NO + * before to be called a last time with the full image and finished argument + * set to YES. In case of error, the finished argument is always YES. + * + * @return A token (SDWebImageDownloadToken) that can be used to cancel this operation + */ +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Creates a SDWebImageDownloader async downloader instance with a given URL + * + * The delegate will be informed when the image is finish downloaded or an error has happen. + * + * @see SDWebImageDownloaderDelegate + * + * @param url The URL to the image to download + * @param options The options to be used for this download + * @param progressBlock A block called repeatedly while the image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called once the download is completed. + * If the download succeeded, the image parameter is set, in case of error, + * error parameter is set with the error. The last parameter is always YES + * if SDWebImageDownloaderProgressiveLoad isn't use. With the + * SDWebImageDownloaderProgressiveLoad option, this block is called + * repeatedly with the partial image object and the finished argument set to NO + * before to be called a last time with the full image and finished argument + * set to YES. In case of error, the finished argument is always YES. + * + * @return A token (SDWebImageDownloadToken) that can be used to cancel this operation + */ +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + options:(SDWebImageDownloaderOptions)options + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Creates a SDWebImageDownloader async downloader instance with a given URL + * + * The delegate will be informed when the image is finish downloaded or an error has happen. + * + * @see SDWebImageDownloaderDelegate + * + * @param url The URL to the image to download + * @param options The options to be used for this download + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called repeatedly while the image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called once the download is completed. + * + * @return A token (SDWebImageDownloadToken) that can be used to cancel this operation + */ +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Cancels all download operations in the queue + */ +- (void)cancelAllDownloads; + +/** + * Invalidates the managed session, optionally canceling pending operations. + * @note If you use custom downloader instead of the shared downloader, you need call this method when you do not use it to avoid memory leak + * @param cancelPendingOperations Whether or not to cancel pending operations. + * @note Calling this method on the shared downloader has no effect. + */ +- (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations; + +@end + + +/** + SDWebImageDownloader is the built-in image loader conform to `SDImageLoader`. Which provide the HTTP/HTTPS/FTP download, or local file URL using NSURLSession. + However, this downloader class itself also support customization for advanced users. You can specify `operationClass` in download config to custom download operation, See `SDWebImageDownloaderOperation`. + If you want to provide some image loader which beyond network or local file, consider to create your own custom class conform to `SDImageLoader`. + */ +@interface SDWebImageDownloader (SDImageLoader) + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.m new file mode 100644 index 0000000..94bfa04 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloader.m @@ -0,0 +1,596 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloader.h" +#import "SDWebImageDownloaderConfig.h" +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageError.h" +#import "SDInternalMacros.h" + +NSNotificationName const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; +NSNotificationName const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification"; +NSNotificationName const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; +NSNotificationName const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification"; + +static void * SDWebImageDownloaderContext = &SDWebImageDownloaderContext; + +@interface SDWebImageDownloadToken () + +@property (nonatomic, strong, nullable, readwrite) NSURL *url; +@property (nonatomic, strong, nullable, readwrite) NSURLRequest *request; +@property (nonatomic, strong, nullable, readwrite) NSURLResponse *response; +@property (nonatomic, weak, nullable, readwrite) id downloadOperationCancelToken; +@property (nonatomic, weak, nullable) NSOperation *downloadOperation; +@property (nonatomic, assign, getter=isCancelled) BOOL cancelled; + +- (nonnull instancetype)init NS_UNAVAILABLE; ++ (nonnull instancetype)new NS_UNAVAILABLE; +- (nonnull instancetype)initWithDownloadOperation:(nullable NSOperation *)downloadOperation; + +@end + +@interface SDWebImageDownloader () + +@property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue; +@property (strong, nonatomic, nonnull) NSMutableDictionary *> *URLOperations; +@property (strong, nonatomic, nullable) NSMutableDictionary *HTTPHeaders; +@property (strong, nonatomic, nonnull) dispatch_semaphore_t HTTPHeadersLock; // A lock to keep the access to `HTTPHeaders` thread-safe +@property (strong, nonatomic, nonnull) dispatch_semaphore_t operationsLock; // A lock to keep the access to `URLOperations` thread-safe + +// The session in which data tasks will run +@property (strong, nonatomic) NSURLSession *session; + +@end + +@implementation SDWebImageDownloader + ++ (void)initialize { + // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) + // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import + if (NSClassFromString(@"SDNetworkActivityIndicator")) { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; +#pragma clang diagnostic pop + + // Remove observer in case it was previously added. + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"startActivity") + name:SDWebImageDownloadStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:activityIndicator + selector:NSSelectorFromString(@"stopActivity") + name:SDWebImageDownloadStopNotification object:nil]; + } +} + ++ (nonnull instancetype)sharedDownloader { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (nonnull instancetype)init { + return [self initWithConfig:SDWebImageDownloaderConfig.defaultDownloaderConfig]; +} + +- (instancetype)initWithConfig:(SDWebImageDownloaderConfig *)config { + self = [super init]; + if (self) { + if (!config) { + config = SDWebImageDownloaderConfig.defaultDownloaderConfig; + } + _config = [config copy]; + [_config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxConcurrentDownloads)) options:0 context:SDWebImageDownloaderContext]; + _downloadQueue = [NSOperationQueue new]; + _downloadQueue.maxConcurrentOperationCount = _config.maxConcurrentDownloads; + _downloadQueue.name = @"com.hackemist.SDWebImageDownloader"; + _URLOperations = [NSMutableDictionary new]; + NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary]; + NSString *userAgent = nil; +#if SD_UIKIT + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; +#elif SD_WATCH + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]]; +#elif SD_MAC + userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; +#endif + if (userAgent) { + if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { + NSMutableString *mutableUserAgent = [userAgent mutableCopy]; + if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) { + userAgent = mutableUserAgent; + } + } + headerDictionary[@"User-Agent"] = userAgent; + } + headerDictionary[@"Accept"] = @"image/*,*/*;q=0.8"; + _HTTPHeaders = headerDictionary; + _HTTPHeadersLock = dispatch_semaphore_create(1); + _operationsLock = dispatch_semaphore_create(1); + NSURLSessionConfiguration *sessionConfiguration = _config.sessionConfiguration; + if (!sessionConfiguration) { + sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; + } + /** + * Create the session for this task + * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate + * method calls and completion handler calls. + */ + _session = [NSURLSession sessionWithConfiguration:sessionConfiguration + delegate:self + delegateQueue:nil]; + } + return self; +} + +- (void)dealloc { + [self.session invalidateAndCancel]; + self.session = nil; + + [self.downloadQueue cancelAllOperations]; + [self.config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxConcurrentDownloads)) context:SDWebImageDownloaderContext]; +} + +- (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations { + if (self == [SDWebImageDownloader sharedDownloader]) { + return; + } + if (cancelPendingOperations) { + [self.session invalidateAndCancel]; + } else { + [self.session finishTasksAndInvalidate]; + } +} + +- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field { + if (!field) { + return; + } + SD_LOCK(self.HTTPHeadersLock); + [self.HTTPHeaders setValue:value forKey:field]; + SD_UNLOCK(self.HTTPHeadersLock); +} + +- (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field { + if (!field) { + return nil; + } + SD_LOCK(self.HTTPHeadersLock); + NSString *value = [self.HTTPHeaders objectForKey:field]; + SD_UNLOCK(self.HTTPHeadersLock); + return value; +} + +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(NSURL *)url + completed:(SDWebImageDownloaderCompletedBlock)completedBlock { + return [self downloadImageWithURL:url options:0 progress:nil completed:completedBlock]; +} + +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(NSURL *)url + options:(SDWebImageDownloaderOptions)options + progress:(SDWebImageDownloaderProgressBlock)progressBlock + completed:(SDWebImageDownloaderCompletedBlock)completedBlock { + return [self downloadImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock { + // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. + if (url == nil) { + if (completedBlock) { + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidURL userInfo:@{NSLocalizedDescriptionKey : @"Image url is nil"}]; + completedBlock(nil, nil, error, YES); + } + return nil; + } + + SD_LOCK(self.operationsLock); + id downloadOperationCancelToken; + NSOperation *operation = [self.URLOperations objectForKey:url]; + // There is a case that the operation may be marked as finished or cancelled, but not been removed from `self.URLOperations`. + if (!operation || operation.isFinished || operation.isCancelled) { + operation = [self createDownloaderOperationWithUrl:url options:options context:context]; + if (!operation) { + SD_UNLOCK(self.operationsLock); + if (completedBlock) { + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Downloader operation is nil"}]; + completedBlock(nil, nil, error, YES); + } + return nil; + } + @weakify(self); + operation.completionBlock = ^{ + @strongify(self); + if (!self) { + return; + } + SD_LOCK(self.operationsLock); + [self.URLOperations removeObjectForKey:url]; + SD_UNLOCK(self.operationsLock); + }; + self.URLOperations[url] = operation; + // Add the handlers before submitting to operation queue, avoid the race condition that operation finished before setting handlers. + downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock]; + // Add operation to operation queue only after all configuration done according to Apple's doc. + // `addOperation:` does not synchronously execute the `operation.completionBlock` so this will not cause deadlock. + [self.downloadQueue addOperation:operation]; + } else { + // When we reuse the download operation to attach more callbacks, there may be thread safe issue because the getter of callbacks may in another queue (decoding queue or delegate queue) + // So we lock the operation here, and in `SDWebImageDownloaderOperation`, we use `@synchonzied (self)`, to ensure the thread safe between these two classes. + @synchronized (operation) { + downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock]; + } + if (!operation.isExecuting) { + if (options & SDWebImageDownloaderHighPriority) { + operation.queuePriority = NSOperationQueuePriorityHigh; + } else if (options & SDWebImageDownloaderLowPriority) { + operation.queuePriority = NSOperationQueuePriorityLow; + } else { + operation.queuePriority = NSOperationQueuePriorityNormal; + } + } + } + SD_UNLOCK(self.operationsLock); + + SDWebImageDownloadToken *token = [[SDWebImageDownloadToken alloc] initWithDownloadOperation:operation]; + token.url = url; + token.request = operation.request; + token.downloadOperationCancelToken = downloadOperationCancelToken; + + return token; +} + +- (nullable NSOperation *)createDownloaderOperationWithUrl:(nonnull NSURL *)url + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context { + NSTimeInterval timeoutInterval = self.config.downloadTimeout; + if (timeoutInterval == 0.0) { + timeoutInterval = 15.0; + } + + // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise + NSURLRequestCachePolicy cachePolicy = options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData; + NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:cachePolicy timeoutInterval:timeoutInterval]; + mutableRequest.HTTPShouldHandleCookies = SD_OPTIONS_CONTAINS(options, SDWebImageDownloaderHandleCookies); + mutableRequest.HTTPShouldUsePipelining = YES; + SD_LOCK(self.HTTPHeadersLock); + mutableRequest.allHTTPHeaderFields = self.HTTPHeaders; + SD_UNLOCK(self.HTTPHeadersLock); + + // Context Option + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + + // Request Modifier + id requestModifier; + if ([context valueForKey:SDWebImageContextDownloadRequestModifier]) { + requestModifier = [context valueForKey:SDWebImageContextDownloadRequestModifier]; + } else { + requestModifier = self.requestModifier; + } + + NSURLRequest *request; + if (requestModifier) { + NSURLRequest *modifiedRequest = [requestModifier modifiedRequestWithRequest:[mutableRequest copy]]; + // If modified request is nil, early return + if (!modifiedRequest) { + return nil; + } else { + request = [modifiedRequest copy]; + } + } else { + request = [mutableRequest copy]; + } + // Response Modifier + id responseModifier; + if ([context valueForKey:SDWebImageContextDownloadResponseModifier]) { + responseModifier = [context valueForKey:SDWebImageContextDownloadResponseModifier]; + } else { + responseModifier = self.responseModifier; + } + if (responseModifier) { + mutableContext[SDWebImageContextDownloadResponseModifier] = responseModifier; + } + // Decryptor + id decryptor; + if ([context valueForKey:SDWebImageContextDownloadDecryptor]) { + decryptor = [context valueForKey:SDWebImageContextDownloadDecryptor]; + } else { + decryptor = self.decryptor; + } + if (decryptor) { + mutableContext[SDWebImageContextDownloadDecryptor] = decryptor; + } + + context = [mutableContext copy]; + + // Operation Class + Class operationClass = self.config.operationClass; + if (operationClass && [operationClass isSubclassOfClass:[NSOperation class]] && [operationClass conformsToProtocol:@protocol(SDWebImageDownloaderOperation)]) { + // Custom operation class + } else { + operationClass = [SDWebImageDownloaderOperation class]; + } + NSOperation *operation = [[operationClass alloc] initWithRequest:request inSession:self.session options:options context:context]; + + if ([operation respondsToSelector:@selector(setCredential:)]) { + if (self.config.urlCredential) { + operation.credential = self.config.urlCredential; + } else if (self.config.username && self.config.password) { + operation.credential = [NSURLCredential credentialWithUser:self.config.username password:self.config.password persistence:NSURLCredentialPersistenceForSession]; + } + } + + if ([operation respondsToSelector:@selector(setMinimumProgressInterval:)]) { + operation.minimumProgressInterval = MIN(MAX(self.config.minimumProgressInterval, 0), 1); + } + + if (options & SDWebImageDownloaderHighPriority) { + operation.queuePriority = NSOperationQueuePriorityHigh; + } else if (options & SDWebImageDownloaderLowPriority) { + operation.queuePriority = NSOperationQueuePriorityLow; + } + + if (self.config.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { + // Emulate LIFO execution order by systematically, each previous adding operation can dependency the new operation + // This can gurantee the new operation to be execulated firstly, even if when some operations finished, meanwhile you appending new operations + // Just make last added operation dependents new operation can not solve this problem. See test case #test15DownloaderLIFOExecutionOrder + for (NSOperation *pendingOperation in self.downloadQueue.operations) { + [pendingOperation addDependency:operation]; + } + } + + return operation; +} + +- (void)cancelAllDownloads { + [self.downloadQueue cancelAllOperations]; +} + +#pragma mark - Properties + +- (BOOL)isSuspended { + return self.downloadQueue.isSuspended; +} + +- (void)setSuspended:(BOOL)suspended { + self.downloadQueue.suspended = suspended; +} + +- (NSUInteger)currentDownloadCount { + return self.downloadQueue.operationCount; +} + +- (NSURLSessionConfiguration *)sessionConfiguration { + return self.session.configuration; +} + +#pragma mark - KVO + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if (context == SDWebImageDownloaderContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(maxConcurrentDownloads))]) { + self.downloadQueue.maxConcurrentOperationCount = self.config.maxConcurrentDownloads; + } + } else { + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + } +} + +#pragma mark Helper methods + +- (NSOperation *)operationWithTask:(NSURLSessionTask *)task { + NSOperation *returnOperation = nil; + for (NSOperation *operation in self.downloadQueue.operations) { + if ([operation respondsToSelector:@selector(dataTask)]) { + // So we lock the operation here, and in `SDWebImageDownloaderOperation`, we use `@synchonzied (self)`, to ensure the thread safe between these two classes. + NSURLSessionTask *operationTask; + @synchronized (operation) { + operationTask = operation.dataTask; + } + if (operationTask.taskIdentifier == task.taskIdentifier) { + returnOperation = operation; + break; + } + } + } + return returnOperation; +} + +#pragma mark NSURLSessionDataDelegate + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:dataTask]; + if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:didReceiveResponse:completionHandler:)]) { + [dataOperation URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler]; + } else { + if (completionHandler) { + completionHandler(NSURLSessionResponseAllow); + } + } +} + +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:dataTask]; + if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:didReceiveData:)]) { + [dataOperation URLSession:session dataTask:dataTask didReceiveData:data]; + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:dataTask]; + if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:willCacheResponse:completionHandler:)]) { + [dataOperation URLSession:session dataTask:dataTask willCacheResponse:proposedResponse completionHandler:completionHandler]; + } else { + if (completionHandler) { + completionHandler(proposedResponse); + } + } +} + +#pragma mark NSURLSessionTaskDelegate + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:task]; + if ([dataOperation respondsToSelector:@selector(URLSession:task:didCompleteWithError:)]) { + [dataOperation URLSession:session task:task didCompleteWithError:error]; + } +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:task]; + if ([dataOperation respondsToSelector:@selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)]) { + [dataOperation URLSession:session task:task willPerformHTTPRedirection:response newRequest:request completionHandler:completionHandler]; + } else { + if (completionHandler) { + completionHandler(request); + } + } +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { + + // Identify the operation that runs this task and pass it the delegate method + NSOperation *dataOperation = [self operationWithTask:task]; + if ([dataOperation respondsToSelector:@selector(URLSession:task:didReceiveChallenge:completionHandler:)]) { + [dataOperation URLSession:session task:task didReceiveChallenge:challenge completionHandler:completionHandler]; + } else { + if (completionHandler) { + completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + } + } +} + +@end + +@implementation SDWebImageDownloadToken + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self name:SDWebImageDownloadReceiveResponseNotification object:nil]; +} + +- (instancetype)initWithDownloadOperation:(NSOperation *)downloadOperation { + self = [super init]; + if (self) { + _downloadOperation = downloadOperation; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadReceiveResponse:) name:SDWebImageDownloadReceiveResponseNotification object:downloadOperation]; + } + return self; +} + +- (void)downloadReceiveResponse:(NSNotification *)notification { + NSOperation *downloadOperation = notification.object; + if (downloadOperation && downloadOperation == self.downloadOperation) { + self.response = downloadOperation.response; + } +} + +- (void)cancel { + @synchronized (self) { + if (self.isCancelled) { + return; + } + self.cancelled = YES; + [self.downloadOperation cancel:self.downloadOperationCancelToken]; + self.downloadOperationCancelToken = nil; + } +} + +@end + +@implementation SDWebImageDownloader (SDImageLoader) + +- (BOOL)canRequestImageForURL:(NSURL *)url { + if (!url) { + return NO; + } + // Always pass YES to let URLSession or custom download operation to determine + return YES; +} + +- (id)requestImageWithURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDImageLoaderCompletedBlock)completedBlock { + UIImage *cachedImage = context[SDWebImageContextLoaderCachedImage]; + + SDWebImageDownloaderOptions downloaderOptions = 0; + if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; + if (options & SDWebImageProgressiveLoad) downloaderOptions |= SDWebImageDownloaderProgressiveLoad; + if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; + if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; + if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; + if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; + if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; + if (options & SDWebImageScaleDownLargeImages) downloaderOptions |= SDWebImageDownloaderScaleDownLargeImages; + if (options & SDWebImageAvoidDecodeImage) downloaderOptions |= SDWebImageDownloaderAvoidDecodeImage; + if (options & SDWebImageDecodeFirstFrameOnly) downloaderOptions |= SDWebImageDownloaderDecodeFirstFrameOnly; + if (options & SDWebImagePreloadAllFrames) downloaderOptions |= SDWebImageDownloaderPreloadAllFrames; + if (options & SDWebImageMatchAnimatedImageClass) downloaderOptions |= SDWebImageDownloaderMatchAnimatedImageClass; + + if (cachedImage && options & SDWebImageRefreshCached) { + // force progressive off if image already cached but forced refreshing + downloaderOptions &= ~SDWebImageDownloaderProgressiveLoad; + // ignore image read from NSURLCache if image if cached but force refreshing + downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; + } + + return [self downloadImageWithURL:url options:downloaderOptions context:context progress:progressBlock completed:completedBlock]; +} + +- (BOOL)shouldBlockFailedURLWithURL:(NSURL *)url error:(NSError *)error { + BOOL shouldBlockFailedURL; + // Filter the error domain and check error codes + if ([error.domain isEqualToString:SDWebImageErrorDomain]) { + shouldBlockFailedURL = ( error.code == SDWebImageErrorInvalidURL + || error.code == SDWebImageErrorBadImageData); + } else if ([error.domain isEqualToString:NSURLErrorDomain]) { + shouldBlockFailedURL = ( error.code != NSURLErrorNotConnectedToInternet + && error.code != NSURLErrorCancelled + && error.code != NSURLErrorTimedOut + && error.code != NSURLErrorInternationalRoamingOff + && error.code != NSURLErrorDataNotAllowed + && error.code != NSURLErrorCannotFindHost + && error.code != NSURLErrorCannotConnectToHost + && error.code != NSURLErrorNetworkConnectionLost); + } else { + shouldBlockFailedURL = NO; + } + return shouldBlockFailedURL; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.h new file mode 100644 index 0000000..c17090b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.h @@ -0,0 +1,98 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +/// Operation execution order +typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { + /** + * Default value. All download operations will execute in queue style (first-in-first-out). + */ + SDWebImageDownloaderFIFOExecutionOrder, + + /** + * All download operations will execute in stack style (last-in-first-out). + */ + SDWebImageDownloaderLIFOExecutionOrder +}; + +/** + The class contains all the config for image downloader + @note This class conform to NSCopying, make sure to add the property in `copyWithZone:` as well. + */ +@interface SDWebImageDownloaderConfig : NSObject + +/** + Gets the default downloader config used for shared instance or initialization when it does not provide any downloader config. Such as `SDWebImageDownloader.sharedDownloader`. + @note You can modify the property on default downloader config, which can be used for later created downloader instance. The already created downloader instance does not get affected. + */ +@property (nonatomic, class, readonly, nonnull) SDWebImageDownloaderConfig *defaultDownloaderConfig; + +/** + * The maximum number of concurrent downloads. + * Defaults to 6. + */ +@property (nonatomic, assign) NSInteger maxConcurrentDownloads; + +/** + * The timeout value (in seconds) for each download operation. + * Defaults to 15.0. + */ +@property (nonatomic, assign) NSTimeInterval downloadTimeout; + +/** + * The minimum interval about progress percent during network downloading. Which means the next progress callback and current progress callback's progress percent difference should be larger or equal to this value. However, the final finish download progress callback does not get effected. + * The value should be 0.0-1.0. + * @note If you're using progressive decoding feature, this will also effect the image refresh rate. + * @note This value may enhance the performance if you don't want progress callback too frequently. + * Defaults to 0, which means each time we receive the new data from URLSession, we callback the progressBlock immediately. + */ +@property (nonatomic, assign) double minimumProgressInterval; + +/** + * The custom session configuration in use by NSURLSession. If you don't provide one, we will use `defaultSessionConfiguration` instead. + * Defatuls to nil. + * @note This property does not support dynamic changes, means it's immutable after the downloader instance initialized. + */ +@property (nonatomic, strong, nullable) NSURLSessionConfiguration *sessionConfiguration; + +/** + * Gets/Sets a subclass of `SDWebImageDownloaderOperation` as the default + * `NSOperation` to be used each time SDWebImage constructs a request + * operation to download an image. + * Defaults to nil. + * @note Passing `NSOperation` to set as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. + */ +@property (nonatomic, assign, nullable) Class operationClass; + +/** + * Changes download operations execution order. + * Defaults to `SDWebImageDownloaderFIFOExecutionOrder`. + */ +@property (nonatomic, assign) SDWebImageDownloaderExecutionOrder executionOrder; + +/** + * Set the default URL credential to be set for request operations. + * Defaults to nil. + */ +@property (nonatomic, copy, nullable) NSURLCredential *urlCredential; + +/** + * Set username using for HTTP Basic authentication. + * Defaults to nil. + */ +@property (nonatomic, copy, nullable) NSString *username; + +/** + * Set password using for HTTP Basic authentication. + * Defautls to nil. + */ +@property (nonatomic, copy, nullable) NSString *password; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.m new file mode 100644 index 0000000..1fc9330 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderConfig.m @@ -0,0 +1,49 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloaderConfig.h" + +static SDWebImageDownloaderConfig * _defaultDownloaderConfig; + +@implementation SDWebImageDownloaderConfig + ++ (SDWebImageDownloaderConfig *)defaultDownloaderConfig { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _defaultDownloaderConfig = [SDWebImageDownloaderConfig new]; + }); + return _defaultDownloaderConfig; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _maxConcurrentDownloads = 6; + _downloadTimeout = 15.0; + _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + SDWebImageDownloaderConfig *config = [[[self class] allocWithZone:zone] init]; + config.maxConcurrentDownloads = self.maxConcurrentDownloads; + config.downloadTimeout = self.downloadTimeout; + config.minimumProgressInterval = self.minimumProgressInterval; + config.sessionConfiguration = [self.sessionConfiguration copyWithZone:zone]; + config.operationClass = self.operationClass; + config.executionOrder = self.executionOrder; + config.urlCredential = self.urlCredential; + config.username = self.username; + config.password = self.password; + + return config; +} + + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.h new file mode 100644 index 0000000..184d4f8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.h @@ -0,0 +1,44 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" + +typedef NSData * _Nullable (^SDWebImageDownloaderDecryptorBlock)(NSData * _Nonnull data, NSURLResponse * _Nullable response); + +/** +This is the protocol for downloader decryptor. Which decrypt the original encrypted data before decoding. Note progressive decoding is not compatible for decryptor. +We can use a block to specify the downloader decryptor. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. +*/ +@protocol SDWebImageDownloaderDecryptor + +/// Decrypt the original download data and return a new data. You can use this to decrypt the data using your perfereed algorithm. +/// @param data The original download data +/// @param response The URL response for data. If you modifiy the original URL response via response modifier, the modified version will be here. This arg is nullable. +/// @note If nil is returned, the image download will be marked as failed with error `SDWebImageErrorBadImageData` +- (nullable NSData *)decryptedDataWithData:(nonnull NSData *)data response:(nullable NSURLResponse *)response; + +@end + +/** +A downloader response modifier class with block. +*/ +@interface SDWebImageDownloaderDecryptor : NSObject + +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageDownloaderDecryptorBlock)block; ++ (nonnull instancetype)decryptorWithBlock:(nonnull SDWebImageDownloaderDecryptorBlock)block; + +@end + +/// Convenience way to create decryptor for common data encryption. +@interface SDWebImageDownloaderDecryptor (Conveniences) + +/// Base64 Encoded image data decryptor +@property (class, readonly, nonnull) SDWebImageDownloaderDecryptor *base64Decryptor; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.m new file mode 100644 index 0000000..a3b75b2 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderDecryptor.m @@ -0,0 +1,55 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDWebImageDownloaderDecryptor.h" + +@interface SDWebImageDownloaderDecryptor () + +@property (nonatomic, copy, nonnull) SDWebImageDownloaderDecryptorBlock block; + +@end + +@implementation SDWebImageDownloaderDecryptor + +- (instancetype)initWithBlock:(SDWebImageDownloaderDecryptorBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)decryptorWithBlock:(SDWebImageDownloaderDecryptorBlock)block { + SDWebImageDownloaderDecryptor *decryptor = [[SDWebImageDownloaderDecryptor alloc] initWithBlock:block]; + return decryptor; +} + +- (nullable NSData *)decryptedDataWithData:(nonnull NSData *)data response:(nullable NSURLResponse *)response { + if (!self.block) { + return nil; + } + return self.block(data, response); +} + +@end + +@implementation SDWebImageDownloaderDecryptor (Conveniences) + ++ (SDWebImageDownloaderDecryptor *)base64Decryptor { + static SDWebImageDownloaderDecryptor *decryptor; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + decryptor = [SDWebImageDownloaderDecryptor decryptorWithBlock:^NSData * _Nullable(NSData * _Nonnull data, NSURLResponse * _Nullable response) { + NSData *modifiedData = [[NSData alloc] initWithBase64EncodedData:data options:NSDataBase64DecodingIgnoreUnknownCharacters]; + return modifiedData; + }]; + }); + return decryptor; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.h new file mode 100644 index 0000000..e987ba4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.h @@ -0,0 +1,146 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageDownloader.h" +#import "SDWebImageOperation.h" + +/** + Describes a downloader operation. If one wants to use a custom downloader op, it needs to inherit from `NSOperation` and conform to this protocol + For the description about these methods, see `SDWebImageDownloaderOperation` + @note If your custom operation class does not use `NSURLSession` at all, do not implement the optional methods and session delegate methods. + */ +@protocol SDWebImageDownloaderOperation +@required +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options; + +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context; + +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +- (BOOL)cancel:(nullable id)token; + +@property (strong, nonatomic, readonly, nullable) NSURLRequest *request; +@property (strong, nonatomic, readonly, nullable) NSURLResponse *response; + +@optional +@property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask; +@property (strong, nonatomic, nullable) NSURLCredential *credential; +@property (assign, nonatomic) double minimumProgressInterval; + +@end + + +/** + The download operation class for SDWebImageDownloader. + */ +@interface SDWebImageDownloaderOperation : NSOperation + +/** + * The request used by the operation's task. + */ +@property (strong, nonatomic, readonly, nullable) NSURLRequest *request; + +/** + * The response returned by the operation's task. + */ +@property (strong, nonatomic, readonly, nullable) NSURLResponse *response; + +/** + * The operation's task + */ +@property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask; + +/** + * The credential used for authentication challenges in `-URLSession:task:didReceiveChallenge:completionHandler:`. + * + * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. + */ +@property (strong, nonatomic, nullable) NSURLCredential *credential; + +/** + * The minimum interval about progress percent during network downloading. Which means the next progress callback and current progress callback's progress percent difference should be larger or equal to this value. However, the final finish download progress callback does not get effected. + * The value should be 0.0-1.0. + * @note If you're using progressive decoding feature, this will also effect the image refresh rate. + * @note This value may enhance the performance if you don't want progress callback too frequently. + * Defaults to 0, which means each time we receive the new data from URLSession, we callback the progressBlock immediately. + */ +@property (assign, nonatomic) double minimumProgressInterval; + +/** + * The options for the receiver. + */ +@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; + +/** + * The context for the receiver. + */ +@property (copy, nonatomic, readonly, nullable) SDWebImageContext *context; + +/** + * Initializes a `SDWebImageDownloaderOperation` object + * + * @see SDWebImageDownloaderOperation + * + * @param request the URL request + * @param session the URL session in which this operation will run + * @param options downloader options + * + * @return the initialized instance + */ +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options; + +/** + * Initializes a `SDWebImageDownloaderOperation` object + * + * @see SDWebImageDownloaderOperation + * + * @param request the URL request + * @param session the URL session in which this operation will run + * @param options downloader options + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * + * @return the initialized instance + */ +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context NS_DESIGNATED_INITIALIZER; + +/** + * Adds handlers for progress and completion. Returns a tokent that can be passed to -cancel: to cancel this set of + * callbacks. + * + * @param progressBlock the block executed when a new chunk of data arrives. + * @note the progress block is executed on a background queue + * @param completedBlock the block executed when the download is done. + * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue + * + * @return the token to use to cancel this set of handlers + */ +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Cancels a set of callbacks. Once all callbacks are canceled, the operation is cancelled. + * + * @param token the token representing a set of callbacks to cancel + * + * @return YES if the operation was stopped because this was the last token to be canceled. NO otherwise. + */ +- (BOOL)cancel:(nullable id)token; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.m new file mode 100644 index 0000000..6527edd --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderOperation.m @@ -0,0 +1,547 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageError.h" +#import "SDInternalMacros.h" +#import "SDWebImageDownloaderResponseModifier.h" +#import "SDWebImageDownloaderDecryptor.h" + +// iOS 8 Foundation.framework extern these symbol but the define is in CFNetwork.framework. We just fix this without import CFNetwork.framework +#if ((__IPHONE_OS_VERSION_MIN_REQUIRED && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_9_0) || (__MAC_OS_X_VERSION_MIN_REQUIRED && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_11)) +const float NSURLSessionTaskPriorityHigh = 0.75; +const float NSURLSessionTaskPriorityDefault = 0.5; +const float NSURLSessionTaskPriorityLow = 0.25; +#endif + +static NSString *const kProgressCallbackKey = @"progress"; +static NSString *const kCompletedCallbackKey = @"completed"; + +typedef NSMutableDictionary SDCallbacksDictionary; + +@interface SDWebImageDownloaderOperation () + +@property (strong, nonatomic, nonnull) NSMutableArray *callbackBlocks; + +@property (assign, nonatomic, readwrite) SDWebImageDownloaderOptions options; +@property (copy, nonatomic, readwrite, nullable) SDWebImageContext *context; + +@property (assign, nonatomic, getter = isExecuting) BOOL executing; +@property (assign, nonatomic, getter = isFinished) BOOL finished; +@property (strong, nonatomic, nullable) NSMutableData *imageData; +@property (copy, nonatomic, nullable) NSData *cachedData; // for `SDWebImageDownloaderIgnoreCachedResponse` +@property (assign, nonatomic) NSUInteger expectedSize; // may be 0 +@property (assign, nonatomic) NSUInteger receivedSize; +@property (strong, nonatomic, nullable, readwrite) NSURLResponse *response; +@property (strong, nonatomic, nullable) NSError *responseError; +@property (assign, nonatomic) double previousProgress; // previous progress percent + +@property (strong, nonatomic, nullable) id responseModifier; // modifiy original URLResponse +@property (strong, nonatomic, nullable) id decryptor; // decrypt image data + +// This is weak because it is injected by whoever manages this session. If this gets nil-ed out, we won't be able to run +// the task associated with this operation +@property (weak, nonatomic, nullable) NSURLSession *unownedSession; +// This is set if we're using not using an injected NSURLSession. We're responsible of invalidating this one +@property (strong, nonatomic, nullable) NSURLSession *ownedSession; + +@property (strong, nonatomic, readwrite, nullable) NSURLSessionTask *dataTask; + +@property (strong, nonatomic, nonnull) dispatch_queue_t coderQueue; // the queue to do image decoding +#if SD_UIKIT +@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; +#endif + +@end + +@implementation SDWebImageDownloaderOperation + +@synthesize executing = _executing; +@synthesize finished = _finished; + +- (nonnull instancetype)init { + return [self initWithRequest:nil inSession:nil options:0]; +} + +- (instancetype)initWithRequest:(NSURLRequest *)request inSession:(NSURLSession *)session options:(SDWebImageDownloaderOptions)options { + return [self initWithRequest:request inSession:session options:options context:nil]; +} + +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options + context:(nullable SDWebImageContext *)context { + if ((self = [super init])) { + _request = [request copy]; + _options = options; + _context = [context copy]; + _callbackBlocks = [NSMutableArray new]; + _responseModifier = context[SDWebImageContextDownloadResponseModifier]; + _decryptor = context[SDWebImageContextDownloadDecryptor]; + _executing = NO; + _finished = NO; + _expectedSize = 0; + _unownedSession = session; + _coderQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderOperationCoderQueue", DISPATCH_QUEUE_SERIAL); +#if SD_UIKIT + _backgroundTaskId = UIBackgroundTaskInvalid; +#endif + } + return self; +} + +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock { + SDCallbacksDictionary *callbacks = [NSMutableDictionary new]; + if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; + if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; + @synchronized (self) { + [self.callbackBlocks addObject:callbacks]; + } + return callbacks; +} + +- (nullable NSArray *)callbacksForKey:(NSString *)key { + NSMutableArray *callbacks; + @synchronized (self) { + callbacks = [[self.callbackBlocks valueForKey:key] mutableCopy]; + } + // We need to remove [NSNull null] because there might not always be a progress block for each callback + [callbacks removeObjectIdenticalTo:[NSNull null]]; + return [callbacks copy]; // strip mutability here +} + +- (BOOL)cancel:(nullable id)token { + if (!token) return NO; + + BOOL shouldCancel = NO; + @synchronized (self) { + NSMutableArray *tempCallbackBlocks = [self.callbackBlocks mutableCopy]; + [tempCallbackBlocks removeObjectIdenticalTo:token]; + if (tempCallbackBlocks.count == 0) { + shouldCancel = YES; + } + } + if (shouldCancel) { + // Cancel operation running and callback last token's completion block + [self cancel]; + } else { + // Only callback this token's completion block + @synchronized (self) { + [self.callbackBlocks removeObjectIdenticalTo:token]; + } + SDWebImageDownloaderCompletedBlock completedBlock = [token valueForKey:kCompletedCallbackKey]; + dispatch_main_async_safe(^{ + if (completedBlock) { + completedBlock(nil, nil, [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:nil], YES); + } + }); + } + return shouldCancel; +} + +- (void)start { + @synchronized (self) { + if (self.isCancelled) { + self.finished = YES; + // Operation cancelled by user before sending the request + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:nil]]; + [self reset]; + return; + } + +#if SD_UIKIT + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + BOOL hasApplication = UIApplicationClass && [UIApplicationClass respondsToSelector:@selector(sharedApplication)]; + if (hasApplication && [self shouldContinueWhenAppEntersBackground]) { + __weak typeof(self) wself = self; + UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)]; + self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{ + [wself cancel]; + }]; + } +#endif + NSURLSession *session = self.unownedSession; + if (!session) { + NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; + sessionConfig.timeoutIntervalForRequest = 15; + + /** + * Create the session for this task + * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate + * method calls and completion handler calls. + */ + session = [NSURLSession sessionWithConfiguration:sessionConfig + delegate:self + delegateQueue:nil]; + self.ownedSession = session; + } + + if (self.options & SDWebImageDownloaderIgnoreCachedResponse) { + // Grab the cached data for later check + NSURLCache *URLCache = session.configuration.URLCache; + if (!URLCache) { + URLCache = [NSURLCache sharedURLCache]; + } + NSCachedURLResponse *cachedResponse; + // NSURLCache's `cachedResponseForRequest:` is not thread-safe, see https://developer.apple.com/documentation/foundation/nsurlcache#2317483 + @synchronized (URLCache) { + cachedResponse = [URLCache cachedResponseForRequest:self.request]; + } + if (cachedResponse) { + self.cachedData = cachedResponse.data; + } + } + + self.dataTask = [session dataTaskWithRequest:self.request]; + self.executing = YES; + } + + if (self.dataTask) { + if (self.options & SDWebImageDownloaderHighPriority) { + self.dataTask.priority = NSURLSessionTaskPriorityHigh; + } else if (self.options & SDWebImageDownloaderLowPriority) { + self.dataTask.priority = NSURLSessionTaskPriorityLow; + } + [self.dataTask resume]; + for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { + progressBlock(0, NSURLResponseUnknownLength, self.request.URL); + } + __block typeof(self) strongSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:strongSelf]; + }); + } else { + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Task can't be initialized"}]]; + [self done]; + } +} + +- (void)cancel { + @synchronized (self) { + [self cancelInternal]; + } +} + +- (void)cancelInternal { + if (self.isFinished) return; + [super cancel]; + + if (self.dataTask) { + [self.dataTask cancel]; + __block typeof(self) strongSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:strongSelf]; + }); + + // As we cancelled the task, its callback won't be called and thus won't + // maintain the isFinished and isExecuting flags. + if (self.isExecuting) self.executing = NO; + if (!self.isFinished) self.finished = YES; + } + // Operation cancelled by user before sending the request + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:nil]]; + + [self reset]; +} + +- (void)done { + self.finished = YES; + self.executing = NO; + [self reset]; +} + +- (void)reset { + @synchronized (self) { + [self.callbackBlocks removeAllObjects]; + self.dataTask = nil; + + if (self.ownedSession) { + [self.ownedSession invalidateAndCancel]; + self.ownedSession = nil; + } + +#if SD_UIKIT + if (self.backgroundTaskId != UIBackgroundTaskInvalid) { + // If backgroundTaskId != UIBackgroundTaskInvalid, sharedApplication is always exist + UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)]; + [app endBackgroundTask:self.backgroundTaskId]; + self.backgroundTaskId = UIBackgroundTaskInvalid; + } +#endif + } +} + +- (void)setFinished:(BOOL)finished { + [self willChangeValueForKey:@"isFinished"]; + _finished = finished; + [self didChangeValueForKey:@"isFinished"]; +} + +- (void)setExecuting:(BOOL)executing { + [self willChangeValueForKey:@"isExecuting"]; + _executing = executing; + [self didChangeValueForKey:@"isExecuting"]; +} + +- (BOOL)isConcurrent { + return YES; +} + +#pragma mark NSURLSessionDataDelegate + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { + NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; + + // Check response modifier, if return nil, will marked as cancelled. + BOOL valid = YES; + if (self.responseModifier && response) { + response = [self.responseModifier modifiedResponseWithResponse:response]; + if (!response) { + valid = NO; + self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadResponse userInfo:nil]; + } + } + + NSInteger expected = (NSInteger)response.expectedContentLength; + expected = expected > 0 ? expected : 0; + self.expectedSize = expected; + self.response = response; + + NSInteger statusCode = [response respondsToSelector:@selector(statusCode)] ? ((NSHTTPURLResponse *)response).statusCode : 200; + // Status code should between [200,400) + BOOL statusCodeValid = statusCode >= 200 && statusCode < 400; + if (!statusCodeValid) { + valid = NO; + self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadStatusCode userInfo:@{SDWebImageErrorDownloadStatusCodeKey : @(statusCode)}]; + } + //'304 Not Modified' is an exceptional one + //URLSession current behavior will return 200 status code when the server respond 304 and URLCache hit. But this is not a standard behavior and we just add a check + if (statusCode == 304 && !self.cachedData) { + valid = NO; + self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCacheNotModified userInfo:nil]; + } + + if (valid) { + for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { + progressBlock(0, expected, self.request.URL); + } + } else { + // Status code invalid and marked as cancelled. Do not call `[self.dataTask cancel]` which may mass up URLSession life cycle + disposition = NSURLSessionResponseCancel; + } + __block typeof(self) strongSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:strongSelf]; + }); + + if (completionHandler) { + completionHandler(disposition); + } +} + +- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { + if (!self.imageData) { + self.imageData = [[NSMutableData alloc] initWithCapacity:self.expectedSize]; + } + [self.imageData appendData:data]; + + self.receivedSize = self.imageData.length; + if (self.expectedSize == 0) { + // Unknown expectedSize, immediately call progressBlock and return + for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { + progressBlock(self.receivedSize, self.expectedSize, self.request.URL); + } + return; + } + + // Get the finish status + BOOL finished = (self.receivedSize >= self.expectedSize); + // Get the current progress + double currentProgress = (double)self.receivedSize / (double)self.expectedSize; + double previousProgress = self.previousProgress; + double progressInterval = currentProgress - previousProgress; + // Check if we need callback progress + if (!finished && (progressInterval < self.minimumProgressInterval)) { + return; + } + self.previousProgress = currentProgress; + + // Using data decryptor will disable the progressive decoding, since there are no support for progressive decrypt + BOOL supportProgressive = (self.options & SDWebImageDownloaderProgressiveLoad) && !self.decryptor; + if (supportProgressive) { + // Get the image data + NSData *imageData = [self.imageData copy]; + + // progressive decode the image in coder queue + dispatch_async(self.coderQueue, ^{ + @autoreleasepool { + UIImage *image = SDImageLoaderDecodeProgressiveImageData(imageData, self.request.URL, finished, self, [[self class] imageOptionsFromDownloaderOptions:self.options], self.context); + if (image) { + // We do not keep the progressive decoding image even when `finished`=YES. Because they are for view rendering but not take full function from downloader options. And some coders implementation may not keep consistent between progressive decoding and normal decoding. + + [self callCompletionBlocksWithImage:image imageData:nil error:nil finished:NO]; + } + } + }); + } + + for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { + progressBlock(self.receivedSize, self.expectedSize, self.request.URL); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { + + NSCachedURLResponse *cachedResponse = proposedResponse; + + if (!(self.options & SDWebImageDownloaderUseNSURLCache)) { + // Prevents caching of responses + cachedResponse = nil; + } + if (completionHandler) { + completionHandler(cachedResponse); + } +} + +#pragma mark NSURLSessionTaskDelegate + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { + // If we already cancel the operation or anything mark the operation finished, don't callback twice + if (self.isFinished) return; + + @synchronized(self) { + self.dataTask = nil; + __block typeof(self) strongSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:strongSelf]; + if (!error) { + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadFinishNotification object:strongSelf]; + } + }); + } + + // make sure to call `[self done]` to mark operation as finished + if (error) { + // custom error instead of URLSession error + if (self.responseError) { + error = self.responseError; + } + [self callCompletionBlocksWithError:error]; + [self done]; + } else { + if ([self callbacksForKey:kCompletedCallbackKey].count > 0) { + NSData *imageData = [self.imageData copy]; + self.imageData = nil; + // data decryptor + if (imageData && self.decryptor) { + imageData = [self.decryptor decryptedDataWithData:imageData response:self.response]; + } + if (imageData) { + /** if you specified to only use cached data via `SDWebImageDownloaderIgnoreCachedResponse`, + * then we should check if the cached data is equal to image data + */ + if (self.options & SDWebImageDownloaderIgnoreCachedResponse && [self.cachedData isEqualToData:imageData]) { + self.responseError = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCacheNotModified userInfo:nil]; + // call completion block with not modified error + [self callCompletionBlocksWithError:self.responseError]; + [self done]; + } else { + // decode the image in coder queue + dispatch_async(self.coderQueue, ^{ + @autoreleasepool { + UIImage *image = SDImageLoaderDecodeImageData(imageData, self.request.URL, [[self class] imageOptionsFromDownloaderOptions:self.options], self.context); + CGSize imageSize = image.size; + if (imageSize.width == 0 || imageSize.height == 0) { + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorBadImageData userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}]]; + } else { + [self callCompletionBlocksWithImage:image imageData:imageData error:nil finished:YES]; + } + [self done]; + } + }); + } + } else { + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorBadImageData userInfo:@{NSLocalizedDescriptionKey : @"Image data is nil"}]]; + [self done]; + } + } else { + [self done]; + } + } +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { + + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + __block NSURLCredential *credential = nil; + + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates)) { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } else { + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + disposition = NSURLSessionAuthChallengeUseCredential; + } + } else { + if (challenge.previousFailureCount == 0) { + if (self.credential) { + credential = self.credential; + disposition = NSURLSessionAuthChallengeUseCredential; + } else { + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } + } else { + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +#pragma mark Helper methods ++ (SDWebImageOptions)imageOptionsFromDownloaderOptions:(SDWebImageDownloaderOptions)downloadOptions { + SDWebImageOptions options = 0; + if (downloadOptions & SDWebImageDownloaderScaleDownLargeImages) options |= SDWebImageScaleDownLargeImages; + if (downloadOptions & SDWebImageDownloaderDecodeFirstFrameOnly) options |= SDWebImageDecodeFirstFrameOnly; + if (downloadOptions & SDWebImageDownloaderPreloadAllFrames) options |= SDWebImagePreloadAllFrames; + if (downloadOptions & SDWebImageDownloaderAvoidDecodeImage) options |= SDWebImageAvoidDecodeImage; + if (downloadOptions & SDWebImageDownloaderMatchAnimatedImageClass) options |= SDWebImageMatchAnimatedImageClass; + + return options; +} + +- (BOOL)shouldContinueWhenAppEntersBackground { + return SD_OPTIONS_CONTAINS(self.options, SDWebImageDownloaderContinueInBackground); +} + +- (void)callCompletionBlocksWithError:(nullable NSError *)error { + [self callCompletionBlocksWithImage:nil imageData:nil error:error finished:YES]; +} + +- (void)callCompletionBlocksWithImage:(nullable UIImage *)image + imageData:(nullable NSData *)imageData + error:(nullable NSError *)error + finished:(BOOL)finished { + NSArray *completionBlocks = [self callbacksForKey:kCompletedCallbackKey]; + dispatch_main_async_safe(^{ + for (SDWebImageDownloaderCompletedBlock completedBlock in completionBlocks) { + completedBlock(image, imageData, error, finished); + } + }); +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.h new file mode 100644 index 0000000..eabdf61 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.h @@ -0,0 +1,35 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NSURLRequest * _Nullable (^SDWebImageDownloaderRequestModifierBlock)(NSURLRequest * _Nonnull request); + +/** + This is the protocol for downloader request modifier. + We can use a block to specify the downloader request modifier. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. + */ +@protocol SDWebImageDownloaderRequestModifier + +/// Modify the original URL request and return a new one instead. You can modify the HTTP header, cachePolicy, etc for this URL. +/// @param request The original URL request for image loading +/// @note If return nil, the URL request will be cancelled. +- (nullable NSURLRequest *)modifiedRequestWithRequest:(nonnull NSURLRequest *)request; + +@end + +/** + A downloader request modifier class with block. + */ +@interface SDWebImageDownloaderRequestModifier : NSObject + +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageDownloaderRequestModifierBlock)block; ++ (nonnull instancetype)requestModifierWithBlock:(nonnull SDWebImageDownloaderRequestModifierBlock)block; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.m new file mode 100644 index 0000000..22d044a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderRequestModifier.m @@ -0,0 +1,39 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageDownloaderRequestModifier.h" + +@interface SDWebImageDownloaderRequestModifier () + +@property (nonatomic, copy, nonnull) SDWebImageDownloaderRequestModifierBlock block; + +@end + +@implementation SDWebImageDownloaderRequestModifier + +- (instancetype)initWithBlock:(SDWebImageDownloaderRequestModifierBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)requestModifierWithBlock:(SDWebImageDownloaderRequestModifierBlock)block { + SDWebImageDownloaderRequestModifier *requestModifier = [[SDWebImageDownloaderRequestModifier alloc] initWithBlock:block]; + return requestModifier; +} + +- (NSURLRequest *)modifiedRequestWithRequest:(NSURLRequest *)request { + if (!self.block) { + return nil; + } + return self.block(request); +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.h new file mode 100644 index 0000000..a8bcc0b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.h @@ -0,0 +1,35 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +typedef NSURLResponse * _Nullable (^SDWebImageDownloaderResponseModifierBlock)(NSURLResponse * _Nonnull response); + +/** + This is the protocol for downloader response modifier. + We can use a block to specify the downloader response modifier. But Using protocol can make this extensible, and allow Swift user to use it easily instead of using `@convention(block)` to store a block into context options. + */ +@protocol SDWebImageDownloaderResponseModifier + +/// Modify the original URL response and return a new response. You can use this to check MIME-Type, mock server response, etc. +/// @param response The original URL response, note for HTTP request it's actually a `NSHTTPURLResponse` instance +/// @note If nil is returned, the image download will marked as cancelled with error `SDWebImageErrorInvalidDownloadResponse` +- (nullable NSURLResponse *)modifiedResponseWithResponse:(nonnull NSURLResponse *)response; + +@end + +/** + A downloader response modifier class with block. + */ +@interface SDWebImageDownloaderResponseModifier : NSObject + +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageDownloaderResponseModifierBlock)block; ++ (nonnull instancetype)responseModifierWithBlock:(nonnull SDWebImageDownloaderResponseModifierBlock)block; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.m new file mode 100644 index 0000000..0894b95 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageDownloaderResponseModifier.m @@ -0,0 +1,40 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + + +#import "SDWebImageDownloaderResponseModifier.h" + +@interface SDWebImageDownloaderResponseModifier () + +@property (nonatomic, copy, nonnull) SDWebImageDownloaderResponseModifierBlock block; + +@end + +@implementation SDWebImageDownloaderResponseModifier + +- (instancetype)initWithBlock:(SDWebImageDownloaderResponseModifierBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)responseModifierWithBlock:(SDWebImageDownloaderResponseModifierBlock)block { + SDWebImageDownloaderResponseModifier *responseModifier = [[SDWebImageDownloaderResponseModifier alloc] initWithBlock:block]; + return responseModifier; +} + +- (nullable NSURLResponse *)modifiedResponseWithResponse:(nonnull NSURLResponse *)response { + if (!self.block) { + return nil; + } + return self.block(response); +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.h new file mode 100644 index 0000000..3c08cc9 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.h @@ -0,0 +1,26 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Jamie Pinkham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +FOUNDATION_EXPORT NSErrorDomain const _Nonnull SDWebImageErrorDomain; + +/// The HTTP status code for invalid download response (NSNumber *) +FOUNDATION_EXPORT NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadStatusCodeKey; + +/// SDWebImage error domain and codes +typedef NS_ERROR_ENUM(SDWebImageErrorDomain, SDWebImageError) { + SDWebImageErrorInvalidURL = 1000, // The URL is invalid, such as nil URL or corrupted URL + SDWebImageErrorBadImageData = 1001, // The image data can not be decoded to image, or the image data is empty + SDWebImageErrorCacheNotModified = 1002, // The remote location specify that the cached image is not modified, such as the HTTP response 304 code. It's useful for `SDWebImageRefreshCached` + SDWebImageErrorInvalidDownloadOperation = 2000, // The image download operation is invalid, such as nil operation or unexpected error occur when operation initialized + SDWebImageErrorInvalidDownloadStatusCode = 2001, // The image download response a invalid status code. You can check the status code in error's userInfo under `SDWebImageErrorDownloadStatusCodeKey` + SDWebImageErrorCancelled = 2002, // The image loading operation is cancelled before finished, during either async disk cache query, or waiting before actual network request. For actual network request error, check `NSURLErrorDomain` error domain and code. + SDWebImageErrorInvalidDownloadResponse = 2003, // When using response modifier, the modified download response is nil and marked as cancelled. +}; diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.m new file mode 100644 index 0000000..6d17476 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageError.m @@ -0,0 +1,13 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Jamie Pinkham + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageError.h" + +NSErrorDomain const _Nonnull SDWebImageErrorDomain = @"SDWebImageErrorDomain"; +NSErrorUserInfoKey const _Nonnull SDWebImageErrorDownloadStatusCodeKey = @"SDWebImageErrorDownloadStatusCodeKey"; diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.h new file mode 100644 index 0000000..e1165c1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.h @@ -0,0 +1,115 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT || SD_MAC + +/** + A protocol to custom the indicator during the image loading. + All of these methods are called from main queue. + */ +@protocol SDWebImageIndicator + +@required +/** + The view associate to the indicator. + + @return The indicator view + */ +@property (nonatomic, strong, readonly, nonnull) UIView *indicatorView; + +/** + Start the animating for indicator. + */ +- (void)startAnimatingIndicator; + +/** + Stop the animating for indicator. + */ +- (void)stopAnimatingIndicator; + +@optional +/** + Update the loading progress (0-1.0) for indicator. Optional + + @param progress The progress, value between 0 and 1.0 + */ +- (void)updateIndicatorProgress:(double)progress; + +@end + +#pragma mark - Activity Indicator + +/** + Activity indicator class. + for UIKit(macOS), it use a `UIActivityIndicatorView`. + for AppKit(macOS), it use a `NSProgressIndicator` with the spinning style. + */ +@interface SDWebImageActivityIndicator : NSObject + +#if SD_UIKIT +@property (nonatomic, strong, readonly, nonnull) UIActivityIndicatorView *indicatorView; +#else +@property (nonatomic, strong, readonly, nonnull) NSProgressIndicator *indicatorView; +#endif + +@end + +/** + Convenience way to use activity indicator. + */ +@interface SDWebImageActivityIndicator (Conveniences) + +/// These indicator use the fixed color without dark mode support +/// gray-style activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *grayIndicator; +/// large gray-style activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *grayLargeIndicator; +/// white-style activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *whiteIndicator; +/// large white-style activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *whiteLargeIndicator; +/// These indicator use the system style, supports dark mode if available (iOS 13+/macOS 10.14+) +/// large activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *largeIndicator; +/// medium activity indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageActivityIndicator *mediumIndicator; + +@end + +#pragma mark - Progress Indicator + +/** + Progress indicator class. + for UIKit(macOS), it use a `UIProgressView`. + for AppKit(macOS), it use a `NSProgressIndicator` with the bar style. + */ +@interface SDWebImageProgressIndicator : NSObject + +#if SD_UIKIT +@property (nonatomic, strong, readonly, nonnull) UIProgressView *indicatorView; +#else +@property (nonatomic, strong, readonly, nonnull) NSProgressIndicator *indicatorView; +#endif + +@end + +/** + Convenience way to create progress indicator. Remember to specify the indicator width or use layout constraint if need. + */ +@interface SDWebImageProgressIndicator (Conveniences) + +/// default-style progress indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageProgressIndicator *defaultIndicator; +/// bar-style progress indicator +@property (nonatomic, class, nonnull, readonly) SDWebImageProgressIndicator *barIndicator API_UNAVAILABLE(macos, tvos); + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.m new file mode 100644 index 0000000..49e6099 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageIndicator.m @@ -0,0 +1,284 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageIndicator.h" + +#if SD_UIKIT || SD_MAC + +#if SD_MAC +#import +#endif + +#if SD_UIKIT +#if __IPHONE_13_0 || __TVOS_13_0 || __MAC_10_15 +// Xcode 11 +#else +// Supports Xcode 10 users, for those users, define these enum +static NSInteger UIActivityIndicatorViewStyleMedium = 100; +static NSInteger UIActivityIndicatorViewStyleLarge = 101; +#endif +#endif + +#pragma mark - Activity Indicator + +@interface SDWebImageActivityIndicator () + +#if SD_UIKIT +@property (nonatomic, strong, readwrite, nonnull) UIActivityIndicatorView *indicatorView; +#else +@property (nonatomic, strong, readwrite, nonnull) NSProgressIndicator *indicatorView; +#endif + +@end + +@implementation SDWebImageActivityIndicator + +- (instancetype)init { + self = [super init]; + if (self) { + [self commonInit]; + } + return self; +} + +#if SD_UIKIT +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +- (void)commonInit { + self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; + self.indicatorView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin; +} +#pragma clang diagnostic pop +#endif + +#if SD_MAC +- (void)commonInit { + self.indicatorView = [[NSProgressIndicator alloc] initWithFrame:NSZeroRect]; + self.indicatorView.style = NSProgressIndicatorStyleSpinning; + self.indicatorView.controlSize = NSControlSizeSmall; + [self.indicatorView sizeToFit]; + self.indicatorView.autoresizingMask = NSViewMaxXMargin | NSViewMinXMargin | NSViewMaxYMargin | NSViewMinYMargin; +} +#endif + +- (void)startAnimatingIndicator { +#if SD_UIKIT + [self.indicatorView startAnimating]; +#else + [self.indicatorView startAnimation:nil]; +#endif + self.indicatorView.hidden = NO; +} + +- (void)stopAnimatingIndicator { +#if SD_UIKIT + [self.indicatorView stopAnimating]; +#else + [self.indicatorView stopAnimation:nil]; +#endif + self.indicatorView.hidden = YES; +} + +@end + +@implementation SDWebImageActivityIndicator (Conveniences) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" ++ (SDWebImageActivityIndicator *)grayIndicator { + SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new]; +#if SD_UIKIT +#if SD_IOS + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; +#else + indicator.indicatorView.color = [UIColor colorWithWhite:0 alpha:0.45]; // Color from `UIActivityIndicatorViewStyleGray` +#endif +#else + indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support +#endif + return indicator; +} + ++ (SDWebImageActivityIndicator *)grayLargeIndicator { + SDWebImageActivityIndicator *indicator = SDWebImageActivityIndicator.grayIndicator; +#if SD_UIKIT + UIColor *grayColor = indicator.indicatorView.color; + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge; + indicator.indicatorView.color = grayColor; +#else + indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support + indicator.indicatorView.controlSize = NSControlSizeRegular; +#endif + [indicator.indicatorView sizeToFit]; + return indicator; +} + ++ (SDWebImageActivityIndicator *)whiteIndicator { + SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new]; +#if SD_UIKIT + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite; +#else + indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support + CIFilter *lighten = [CIFilter filterWithName:@"CIColorControls"]; + [lighten setDefaults]; + [lighten setValue:@(1) forKey:kCIInputBrightnessKey]; + indicator.indicatorView.contentFilters = @[lighten]; +#endif + return indicator; +} + ++ (SDWebImageActivityIndicator *)whiteLargeIndicator { + SDWebImageActivityIndicator *indicator = SDWebImageActivityIndicator.whiteIndicator; +#if SD_UIKIT + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge; +#else + indicator.indicatorView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; // Disable dark mode support + indicator.indicatorView.controlSize = NSControlSizeRegular; + [indicator.indicatorView sizeToFit]; +#endif + return indicator; +} + ++ (SDWebImageActivityIndicator *)largeIndicator { + SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new]; +#if SD_UIKIT + if (@available(iOS 13.0, tvOS 13.0, *)) { + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleLarge; + } else { + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge; + } +#else + indicator.indicatorView.controlSize = NSControlSizeRegular; + [indicator.indicatorView sizeToFit]; +#endif + return indicator; +} + ++ (SDWebImageActivityIndicator *)mediumIndicator { + SDWebImageActivityIndicator *indicator = [SDWebImageActivityIndicator new]; +#if SD_UIKIT + if (@available(iOS 13.0, tvOS 13.0, *)) { + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleMedium; + } else { + indicator.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite; + } +#else + indicator.indicatorView.controlSize = NSControlSizeSmall; + [indicator.indicatorView sizeToFit]; +#endif + return indicator; +} +#pragma clang diagnostic pop + +@end + +#pragma mark - Progress Indicator + +@interface SDWebImageProgressIndicator () + +#if SD_UIKIT +@property (nonatomic, strong, readwrite, nonnull) UIProgressView *indicatorView; +#else +@property (nonatomic, strong, readwrite, nonnull) NSProgressIndicator *indicatorView; +#endif + +@end + +@implementation SDWebImageProgressIndicator + +- (instancetype)init { + self = [super init]; + if (self) { + [self commonInit]; + } + return self; +} + +#if SD_UIKIT +- (void)commonInit { + self.indicatorView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; + self.indicatorView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin; +} +#endif + +#if SD_MAC +- (void)commonInit { + self.indicatorView = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 160, 0)]; // Width from `UIProgressView` default width + self.indicatorView.style = NSProgressIndicatorStyleBar; + self.indicatorView.controlSize = NSControlSizeSmall; + [self.indicatorView sizeToFit]; + self.indicatorView.autoresizingMask = NSViewMaxXMargin | NSViewMinXMargin | NSViewMaxYMargin | NSViewMinYMargin; +} +#endif + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +- (void)startAnimatingIndicator { + self.indicatorView.hidden = NO; +#if SD_UIKIT + if ([self.indicatorView respondsToSelector:@selector(observedProgress)] && self.indicatorView.observedProgress) { + // Ignore NSProgress + } else { + self.indicatorView.progress = 0; + } +#else + self.indicatorView.indeterminate = YES; + self.indicatorView.doubleValue = 0; + [self.indicatorView startAnimation:nil]; +#endif +} + +- (void)stopAnimatingIndicator { + self.indicatorView.hidden = YES; +#if SD_UIKIT + if ([self.indicatorView respondsToSelector:@selector(observedProgress)] && self.indicatorView.observedProgress) { + // Ignore NSProgress + } else { + self.indicatorView.progress = 1; + } +#else + self.indicatorView.indeterminate = NO; + self.indicatorView.doubleValue = 100; + [self.indicatorView stopAnimation:nil]; +#endif +} + +- (void)updateIndicatorProgress:(double)progress { +#if SD_UIKIT + if ([self.indicatorView respondsToSelector:@selector(observedProgress)] && self.indicatorView.observedProgress) { + // Ignore NSProgress + } else { + [self.indicatorView setProgress:progress animated:YES]; + } +#else + self.indicatorView.indeterminate = progress > 0 ? NO : YES; + self.indicatorView.doubleValue = progress * 100; +#endif +} +#pragma clang diagnostic pop + +@end + +@implementation SDWebImageProgressIndicator (Conveniences) + ++ (SDWebImageProgressIndicator *)defaultIndicator { + SDWebImageProgressIndicator *indicator = [SDWebImageProgressIndicator new]; + return indicator; +} + +#if SD_IOS ++ (SDWebImageProgressIndicator *)barIndicator { + SDWebImageProgressIndicator *indicator = [SDWebImageProgressIndicator new]; + indicator.indicatorView.progressViewStyle = UIProgressViewStyleBar; + return indicator; +} +#endif + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.h new file mode 100644 index 0000000..d940f74 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.h @@ -0,0 +1,269 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" +#import "SDImageCacheDefine.h" +#import "SDImageLoader.h" +#import "SDImageTransformer.h" +#import "SDWebImageCacheKeyFilter.h" +#import "SDWebImageCacheSerializer.h" +#import "SDWebImageOptionsProcessor.h" + +typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL); + +typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL); + +/** + A combined operation representing the cache and loader operation. You can use it to cancel the load process. + */ +@interface SDWebImageCombinedOperation : NSObject + +/** + Cancel the current operation, including cache and loader process + */ +- (void)cancel; + +/** + The cache operation from the image cache query + */ +@property (strong, nonatomic, nullable, readonly) id cacheOperation; + +/** + The loader operation from the image loader (such as download operation) + */ +@property (strong, nonatomic, nullable, readonly) id loaderOperation; + +@end + + +@class SDWebImageManager; + +/** + The manager delegate protocol. + */ +@protocol SDWebImageManagerDelegate + +@optional + +/** + * Controls which image should be downloaded when the image is not found in the cache. + * + * @param imageManager The current `SDWebImageManager` + * @param imageURL The url of the image to be downloaded + * + * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. + */ +- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nonnull NSURL *)imageURL; + +/** + * Controls the complicated logic to mark as failed URLs when download error occur. + * If the delegate implement this method, we will not use the built-in way to mark URL as failed based on error code; + @param imageManager The current `SDWebImageManager` + @param imageURL The url of the image + @param error The download error for the url + @return Whether to block this url or not. Return YES to mark this URL as failed. + */ +- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldBlockFailedURL:(nonnull NSURL *)imageURL withError:(nonnull NSError *)error; + +@end + +/** + * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. + * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). + * You can use this class directly to benefit from web image downloading with caching in another context than + * a UIView. + * + * Here is a simple example of how to use SDWebImageManager: + * + * @code + +SDWebImageManager *manager = [SDWebImageManager sharedManager]; +[manager loadImageWithURL:imageURL + options:0 + progress:nil + completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (image) { + // do something with image + } + }]; + + * @endcode + */ +@interface SDWebImageManager : NSObject + +/** + * The delegate for manager. Defatuls to nil. + */ +@property (weak, nonatomic, nullable) id delegate; + +/** + * The image cache used by manager to query image cache. + */ +@property (strong, nonatomic, readonly, nonnull) id imageCache; + +/** + * The image loader used by manager to load image. + */ +@property (strong, nonatomic, readonly, nonnull) id imageLoader; + +/** + The image transformer for manager. It's used for image transform after the image load finished and store the transformed image to cache, see `SDImageTransformer`. + Defaults to nil, which means no transform is applied. + @note This will affect all the load requests for this manager if you provide. However, you can pass `SDWebImageContextImageTransformer` in context arg to explicitly use that transformer instead. + */ +@property (strong, nonatomic, nullable) id transformer; + +/** + * The cache filter is used to convert an URL into a cache key each time SDWebImageManager need cache key to use image cache. + * + * The following example sets a filter in the application delegate that will remove any query-string from the + * URL before to use it as a cache key: + * + * @code + SDWebImageManager.sharedManager.cacheKeyFilter =[SDWebImageCacheKeyFilter cacheKeyFilterWithBlock:^NSString * _Nullable(NSURL * _Nonnull url) { + url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; + return [url absoluteString]; + }]; + * @endcode + */ +@property (nonatomic, strong, nullable) id cacheKeyFilter; + +/** + * The cache serializer is used to convert the decoded image, the source downloaded data, to the actual data used for storing to the disk cache. If you return nil, means to generate the data from the image instance, see `SDImageCache`. + * For example, if you are using WebP images and facing the slow decoding time issue when later retriving from disk cache again. You can try to encode the decoded image to JPEG/PNG format to disk cache instead of source downloaded data. + * @note The `image` arg is nonnull, but when you also provide a image transformer and the image is transformed, the `data` arg may be nil, take attention to this case. + * @note This method is called from a global queue in order to not to block the main thread. + * @code + SDWebImageManager.sharedManager.cacheSerializer = [SDWebImageCacheSerializer cacheSerializerWithBlock:^NSData * _Nullable(UIImage * _Nonnull image, NSData * _Nullable data, NSURL * _Nullable imageURL) { + SDImageFormat format = [NSData sd_imageFormatForImageData:data]; + switch (format) { + case SDImageFormatWebP: + return image.images ? data : nil; + default: + return data; + } +}]; + * @endcode + * The default value is nil. Means we just store the source downloaded data to disk cache. + */ +@property (nonatomic, strong, nullable) id cacheSerializer; + +/** + The options processor is used, to have a global control for all the image request options and context option for current manager. + @note If you use `transformer`, `cacheKeyFilter` or `cacheSerializer` property of manager, the input context option already apply those properties before passed. This options processor is a better replacement for those property in common usage. + For example, you can control the global options, based on the URL or original context option like the below code. + + @code + SDWebImageManager.sharedManager.optionsProcessor = [SDWebImageOptionsProcessor optionsProcessorWithBlock:^SDWebImageOptionsResult * _Nullable(NSURL * _Nullable url, SDWebImageOptions options, SDWebImageContext * _Nullable context) { + // Only do animation on `SDAnimatedImageView` + if (!context[SDWebImageContextAnimatedImageClass]) { + options |= SDWebImageDecodeFirstFrameOnly; + } + // Do not force decode for png url + if ([url.lastPathComponent isEqualToString:@"png"]) { + options |= SDWebImageAvoidDecodeImage; + } + // Always use screen scale factor + SDWebImageMutableContext *mutableContext = [NSDictionary dictionaryWithDictionary:context]; + mutableContext[SDWebImageContextImageScaleFactor] = @(UIScreen.mainScreen.scale); + context = [mutableContext copy]; + + return [[SDWebImageOptionsResult alloc] initWithOptions:options context:context]; + }]; + @endcode + */ +@property (nonatomic, strong, nullable) id optionsProcessor; + +/** + * Check one or more operations running + */ +@property (nonatomic, assign, readonly, getter=isRunning) BOOL running; + +/** + The default image cache when the manager which is created with no arguments. Such as shared manager or init. + Defaults to nil. Means using `SDImageCache.sharedImageCache` + */ +@property (nonatomic, class, nullable) id defaultImageCache; + +/** + The default image loader for manager which is created with no arguments. Such as shared manager or init. + Defaults to nil. Means using `SDWebImageDownloader.sharedDownloader` + */ +@property (nonatomic, class, nullable) id defaultImageLoader; + +/** + * Returns global shared manager instance. + */ +@property (nonatomic, class, readonly, nonnull) SDWebImageManager *sharedManager; + +/** + * Allows to specify instance of cache and image loader used with image manager. + * @return new instance of `SDWebImageManager` with specified cache and loader. + */ +- (nonnull instancetype)initWithCache:(nonnull id)cache loader:(nonnull id)loader NS_DESIGNATED_INITIALIZER; + +/** + * Downloads the image at the given URL if not present in cache or return the cached version otherwise. + * + * @param url The URL to the image + * @param options A mask to specify options to use for this request + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. + * + * This parameter is required. + * + * This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter. + * In case of error the image parameter is nil and the third parameter may contain an NSError. + * + * The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache + * or from the memory cache or from the network. + * + * The fith parameter is set to NO when the SDWebImageProgressiveLoad option is used and the image is + * downloading. This block is thus called repeatedly with a partial image. When image is fully downloaded, the + * block is called a last time with the full image and the last parameter set to YES. + * + * The last parameter is the original image URL + * + * @return Returns an instance of SDWebImageCombinedOperation, which you can cancel the loading process. + */ +- (nullable SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nonnull SDInternalCompletionBlock)completedBlock; + +/** + * Downloads the image at the given URL if not present in cache or return the cached version otherwise. + * + * @param url The URL to the image + * @param options A mask to specify options to use for this request + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. + * + * @return Returns an instance of SDWebImageCombinedOperation, which you can cancel the loading process. + */ +- (nullable SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nonnull SDInternalCompletionBlock)completedBlock; + +/** + * Cancel all current operations + */ +- (void)cancelAll; + +/** + * Return the cache key for a given URL + */ +- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.m new file mode 100644 index 0000000..97ffb48 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageManager.m @@ -0,0 +1,545 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageManager.h" +#import "SDImageCache.h" +#import "SDWebImageDownloader.h" +#import "UIImage+Metadata.h" +#import "SDAssociatedObject.h" +#import "SDWebImageError.h" +#import "SDInternalMacros.h" + +static id _defaultImageCache; +static id _defaultImageLoader; + +@interface SDWebImageCombinedOperation () + +@property (assign, nonatomic, getter = isCancelled) BOOL cancelled; +@property (strong, nonatomic, readwrite, nullable) id loaderOperation; +@property (strong, nonatomic, readwrite, nullable) id cacheOperation; +@property (weak, nonatomic, nullable) SDWebImageManager *manager; + +@end + +@interface SDWebImageManager () + +@property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache; +@property (strong, nonatomic, readwrite, nonnull) id imageLoader; +@property (strong, nonatomic, nonnull) NSMutableSet *failedURLs; +@property (strong, nonatomic, nonnull) dispatch_semaphore_t failedURLsLock; // a lock to keep the access to `failedURLs` thread-safe +@property (strong, nonatomic, nonnull) NSMutableSet *runningOperations; +@property (strong, nonatomic, nonnull) dispatch_semaphore_t runningOperationsLock; // a lock to keep the access to `runningOperations` thread-safe + +@end + +@implementation SDWebImageManager + ++ (id)defaultImageCache { + return _defaultImageCache; +} + ++ (void)setDefaultImageCache:(id)defaultImageCache { + if (defaultImageCache && ![defaultImageCache conformsToProtocol:@protocol(SDImageCache)]) { + return; + } + _defaultImageCache = defaultImageCache; +} + ++ (id)defaultImageLoader { + return _defaultImageLoader; +} + ++ (void)setDefaultImageLoader:(id)defaultImageLoader { + if (defaultImageLoader && ![defaultImageLoader conformsToProtocol:@protocol(SDImageLoader)]) { + return; + } + _defaultImageLoader = defaultImageLoader; +} + ++ (nonnull instancetype)sharedManager { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (nonnull instancetype)init { + id cache = [[self class] defaultImageCache]; + if (!cache) { + cache = [SDImageCache sharedImageCache]; + } + id loader = [[self class] defaultImageLoader]; + if (!loader) { + loader = [SDWebImageDownloader sharedDownloader]; + } + return [self initWithCache:cache loader:loader]; +} + +- (nonnull instancetype)initWithCache:(nonnull id)cache loader:(nonnull id)loader { + if ((self = [super init])) { + _imageCache = cache; + _imageLoader = loader; + _failedURLs = [NSMutableSet new]; + _failedURLsLock = dispatch_semaphore_create(1); + _runningOperations = [NSMutableSet new]; + _runningOperationsLock = dispatch_semaphore_create(1); + } + return self; +} + +- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url { + return [self cacheKeyForURL:url context:nil]; +} + +- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context { + if (!url) { + return @""; + } + + NSString *key; + // Cache Key Filter + id cacheKeyFilter = self.cacheKeyFilter; + if (context[SDWebImageContextCacheKeyFilter]) { + cacheKeyFilter = context[SDWebImageContextCacheKeyFilter]; + } + if (cacheKeyFilter) { + key = [cacheKeyFilter cacheKeyForURL:url]; + } else { + key = url.absoluteString; + } + // Thumbnail Key Appending + NSValue *thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize]; + if (thumbnailSizeValue != nil) { + CGSize thumbnailSize = CGSizeZero; +#if SD_MAC + thumbnailSize = thumbnailSizeValue.sizeValue; +#else + thumbnailSize = thumbnailSizeValue.CGSizeValue; +#endif + + BOOL preserveAspectRatio = YES; + NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio]; + if (preserveAspectRatioValue != nil) { + preserveAspectRatio = preserveAspectRatioValue.boolValue; + } + NSString *transformerKey = [NSString stringWithFormat:@"Thumbnail({%f,%f},%d)", thumbnailSize.width, thumbnailSize.height, preserveAspectRatio]; + key = SDTransformedKeyForKey(key, transformerKey); + } + + return key; +} + +- (SDWebImageCombinedOperation *)loadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDInternalCompletionBlock)completedBlock { + return [self loadImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nonnull SDInternalCompletionBlock)completedBlock { + // Invoking this method without a completedBlock is pointless + NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead"); + + // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, Xcode won't + // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. + if ([url isKindOfClass:NSString.class]) { + url = [NSURL URLWithString:(NSString *)url]; + } + + // Prevents app crashing on argument type error like sending NSNull instead of NSURL + if (![url isKindOfClass:NSURL.class]) { + url = nil; + } + + SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; + operation.manager = self; + + BOOL isFailedUrl = NO; + if (url) { + SD_LOCK(self.failedURLsLock); + isFailedUrl = [self.failedURLs containsObject:url]; + SD_UNLOCK(self.failedURLsLock); + } + + if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { + [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidURL userInfo:@{NSLocalizedDescriptionKey : @"Image url is nil"}] url:url]; + return operation; + } + + SD_LOCK(self.runningOperationsLock); + [self.runningOperations addObject:operation]; + SD_UNLOCK(self.runningOperationsLock); + + // Preprocess the options and context arg to decide the final the result for manager + SDWebImageOptionsResult *result = [self processedResultForURL:url options:options context:context]; + + // Start the entry to load image from cache + [self callCacheProcessForOperation:operation url:url options:result.options context:result.context progress:progressBlock completed:completedBlock]; + + return operation; +} + +- (void)cancelAll { + SD_LOCK(self.runningOperationsLock); + NSSet *copiedOperations = [self.runningOperations copy]; + SD_UNLOCK(self.runningOperationsLock); + [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; // This will call `safelyRemoveOperationFromRunning:` and remove from the array +} + +- (BOOL)isRunning { + BOOL isRunning = NO; + SD_LOCK(self.runningOperationsLock); + isRunning = (self.runningOperations.count > 0); + SD_UNLOCK(self.runningOperationsLock); + return isRunning; +} + +#pragma mark - Private + +// Query cache process +- (void)callCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock { + // Check whether we should query cache + BOOL shouldQueryCache = !SD_OPTIONS_CONTAINS(options, SDWebImageFromLoaderOnly); + if (shouldQueryCache) { + NSString *key = [self cacheKeyForURL:url context:context]; + @weakify(operation); + operation.cacheOperation = [self.imageCache queryImageForKey:key options:options context:context completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) { + @strongify(operation); + if (!operation || operation.isCancelled) { + // Image combined operation cancelled by user + [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:nil] url:url]; + [self safelyRemoveOperationFromRunning:operation]; + return; + } + // Continue download process + [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:cachedImage cachedData:cachedData cacheType:cacheType progress:progressBlock completed:completedBlock]; + }]; + } else { + // Continue download process + [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock]; + } +} + +// Download process +- (void)callDownloadProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(SDWebImageContext *)context + cachedImage:(nullable UIImage *)cachedImage + cachedData:(nullable NSData *)cachedData + cacheType:(SDImageCacheType)cacheType + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock { + // Check whether we should download image from network + BOOL shouldDownload = !SD_OPTIONS_CONTAINS(options, SDWebImageFromCacheOnly); + shouldDownload &= (!cachedImage || options & SDWebImageRefreshCached); + shouldDownload &= (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url]); + shouldDownload &= [self.imageLoader canRequestImageForURL:url]; + if (shouldDownload) { + if (cachedImage && options & SDWebImageRefreshCached) { + // If image was found in the cache but SDWebImageRefreshCached is provided, notify about the cached image + // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. + [self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url]; + // Pass the cached image to the image loader. The image loader should check whether the remote image is equal to the cached image. + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextLoaderCachedImage] = cachedImage; + context = [mutableContext copy]; + } + + @weakify(operation); + operation.loaderOperation = [self.imageLoader requestImageWithURL:url options:options context:context progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) { + @strongify(operation); + if (!operation || operation.isCancelled) { + // Image combined operation cancelled by user + [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:nil] url:url]; + } else if (cachedImage && options & SDWebImageRefreshCached && [error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCacheNotModified) { + // Image refresh hit the NSURLCache cache, do not call the completion block + } else if ([error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCancelled) { + // Download operation cancelled by user before sending the request, don't block failed URL + [self callCompletionBlockForOperation:operation completion:completedBlock error:error url:url]; + } else if (error) { + [self callCompletionBlockForOperation:operation completion:completedBlock error:error url:url]; + BOOL shouldBlockFailedURL = [self shouldBlockFailedURLWithURL:url error:error]; + + if (shouldBlockFailedURL) { + SD_LOCK(self.failedURLsLock); + [self.failedURLs addObject:url]; + SD_UNLOCK(self.failedURLsLock); + } + } else { + if ((options & SDWebImageRetryFailed)) { + SD_LOCK(self.failedURLsLock); + [self.failedURLs removeObject:url]; + SD_UNLOCK(self.failedURLsLock); + } + // Continue store cache process + [self callStoreCacheProcessForOperation:operation url:url options:options context:context downloadedImage:downloadedImage downloadedData:downloadedData finished:finished progress:progressBlock completed:completedBlock]; + } + + if (finished) { + [self safelyRemoveOperationFromRunning:operation]; + } + }]; + } else if (cachedImage) { + [self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url]; + [self safelyRemoveOperationFromRunning:operation]; + } else { + // Image not in cache and download disallowed by delegate + [self callCompletionBlockForOperation:operation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url]; + [self safelyRemoveOperationFromRunning:operation]; + } +} + +// Store cache process +- (void)callStoreCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(SDWebImageContext *)context + downloadedImage:(nullable UIImage *)downloadedImage + downloadedData:(nullable NSData *)downloadedData + finished:(BOOL)finished + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock { + // the target image store cache type + SDImageCacheType storeCacheType = SDImageCacheTypeAll; + if (context[SDWebImageContextStoreCacheType]) { + storeCacheType = [context[SDWebImageContextStoreCacheType] integerValue]; + } + // the original store image cache type + SDImageCacheType originalStoreCacheType = SDImageCacheTypeNone; + if (context[SDWebImageContextOriginalStoreCacheType]) { + originalStoreCacheType = [context[SDWebImageContextOriginalStoreCacheType] integerValue]; + } + NSString *key = [self cacheKeyForURL:url context:context]; + id transformer = context[SDWebImageContextImageTransformer]; + id cacheSerializer = context[SDWebImageContextCacheSerializer]; + + BOOL shouldTransformImage = downloadedImage && (!downloadedImage.sd_isAnimated || (options & SDWebImageTransformAnimatedImage)) && transformer; + BOOL shouldCacheOriginal = downloadedImage && finished; + BOOL waitStoreCache = SD_OPTIONS_CONTAINS(options, SDWebImageWaitStoreCache); + + // if available, store original image to cache + if (shouldCacheOriginal) { + // normally use the store cache type, but if target image is transformed, use original store cache type instead + SDImageCacheType targetStoreCacheType = shouldTransformImage ? originalStoreCacheType : storeCacheType; + if (cacheSerializer && (targetStoreCacheType == SDImageCacheTypeDisk || targetStoreCacheType == SDImageCacheTypeAll)) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + @autoreleasepool { + NSData *cacheData = [cacheSerializer cacheDataWithImage:downloadedImage originalData:downloadedData imageURL:url]; + [self storeImage:downloadedImage imageData:cacheData forKey:key cacheType:targetStoreCacheType waitStoreCache:waitStoreCache completion:^{ + // Continue transform process + [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:downloadedImage originalData:downloadedData finished:finished progress:progressBlock completed:completedBlock]; + }]; + } + }); + } else { + [self storeImage:downloadedImage imageData:downloadedData forKey:key cacheType:targetStoreCacheType waitStoreCache:waitStoreCache completion:^{ + // Continue transform process + [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:downloadedImage originalData:downloadedData finished:finished progress:progressBlock completed:completedBlock]; + }]; + } + } else { + // Continue transform process + [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:downloadedImage originalData:downloadedData finished:finished progress:progressBlock completed:completedBlock]; + } +} + +// Transform process +- (void)callTransformProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation + url:(nonnull NSURL *)url + options:(SDWebImageOptions)options + context:(SDWebImageContext *)context + originalImage:(nullable UIImage *)originalImage + originalData:(nullable NSData *)originalData + finished:(BOOL)finished + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock { + // the target image store cache type + SDImageCacheType storeCacheType = SDImageCacheTypeAll; + if (context[SDWebImageContextStoreCacheType]) { + storeCacheType = [context[SDWebImageContextStoreCacheType] integerValue]; + } + NSString *key = [self cacheKeyForURL:url context:context]; + id transformer = context[SDWebImageContextImageTransformer]; + id cacheSerializer = context[SDWebImageContextCacheSerializer]; + BOOL shouldTransformImage = originalImage && (!originalImage.sd_isAnimated || (options & SDWebImageTransformAnimatedImage)) && transformer; + BOOL waitStoreCache = SD_OPTIONS_CONTAINS(options, SDWebImageWaitStoreCache); + // if available, store transformed image to cache + if (shouldTransformImage) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + @autoreleasepool { + UIImage *transformedImage = [transformer transformedImageWithImage:originalImage forKey:key]; + if (transformedImage && finished) { + NSString *transformerKey = [transformer transformerKey]; + NSString *cacheKey = SDTransformedKeyForKey(key, transformerKey); + BOOL imageWasTransformed = ![transformedImage isEqual:originalImage]; + NSData *cacheData; + // pass nil if the image was transformed, so we can recalculate the data from the image + if (cacheSerializer && (storeCacheType == SDImageCacheTypeDisk || storeCacheType == SDImageCacheTypeAll)) { + cacheData = [cacheSerializer cacheDataWithImage:transformedImage originalData:(imageWasTransformed ? nil : originalData) imageURL:url]; + } else { + cacheData = (imageWasTransformed ? nil : originalData); + } + // keep the original image format and extended data + SDImageCopyAssociatedObject(originalImage, transformedImage); + [self storeImage:transformedImage imageData:cacheData forKey:cacheKey cacheType:storeCacheType waitStoreCache:waitStoreCache completion:^{ + [self callCompletionBlockForOperation:operation completion:completedBlock image:transformedImage data:originalData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url]; + }]; + } else { + [self callCompletionBlockForOperation:operation completion:completedBlock image:transformedImage data:originalData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url]; + } + } + }); + } else { + [self callCompletionBlockForOperation:operation completion:completedBlock image:originalImage data:originalData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url]; + } +} + +#pragma mark - Helper + +- (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation { + if (!operation) { + return; + } + SD_LOCK(self.runningOperationsLock); + [self.runningOperations removeObject:operation]; + SD_UNLOCK(self.runningOperationsLock); +} + +- (void)storeImage:(nullable UIImage *)image + imageData:(nullable NSData *)data + forKey:(nullable NSString *)key + cacheType:(SDImageCacheType)cacheType + waitStoreCache:(BOOL)waitStoreCache + completion:(nullable SDWebImageNoParamsBlock)completion { + // Check whether we should wait the store cache finished. If not, callback immediately + [self.imageCache storeImage:image imageData:data forKey:key cacheType:cacheType completion:^{ + if (waitStoreCache) { + if (completion) { + completion(); + } + } + }]; + if (!waitStoreCache) { + if (completion) { + completion(); + } + } +} + +- (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation + completion:(nullable SDInternalCompletionBlock)completionBlock + error:(nullable NSError *)error + url:(nullable NSURL *)url { + [self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES url:url]; +} + +- (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation + completion:(nullable SDInternalCompletionBlock)completionBlock + image:(nullable UIImage *)image + data:(nullable NSData *)data + error:(nullable NSError *)error + cacheType:(SDImageCacheType)cacheType + finished:(BOOL)finished + url:(nullable NSURL *)url { + dispatch_main_async_safe(^{ + if (completionBlock) { + completionBlock(image, data, error, cacheType, finished, url); + } + }); +} + +- (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url + error:(nonnull NSError *)error { + // Check whether we should block failed url + BOOL shouldBlockFailedURL; + if ([self.delegate respondsToSelector:@selector(imageManager:shouldBlockFailedURL:withError:)]) { + shouldBlockFailedURL = [self.delegate imageManager:self shouldBlockFailedURL:url withError:error]; + } else { + shouldBlockFailedURL = [self.imageLoader shouldBlockFailedURLWithURL:url error:error]; + } + + return shouldBlockFailedURL; +} + +- (SDWebImageOptionsResult *)processedResultForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context { + SDWebImageOptionsResult *result; + SDWebImageMutableContext *mutableContext = [SDWebImageMutableContext dictionary]; + + // Image Transformer from manager + if (!context[SDWebImageContextImageTransformer]) { + id transformer = self.transformer; + [mutableContext setValue:transformer forKey:SDWebImageContextImageTransformer]; + } + // Cache key filter from manager + if (!context[SDWebImageContextCacheKeyFilter]) { + id cacheKeyFilter = self.cacheKeyFilter; + [mutableContext setValue:cacheKeyFilter forKey:SDWebImageContextCacheKeyFilter]; + } + // Cache serializer from manager + if (!context[SDWebImageContextCacheSerializer]) { + id cacheSerializer = self.cacheSerializer; + [mutableContext setValue:cacheSerializer forKey:SDWebImageContextCacheSerializer]; + } + + if (mutableContext.count > 0) { + if (context) { + [mutableContext addEntriesFromDictionary:context]; + } + context = [mutableContext copy]; + } + + // Apply options processor + if (self.optionsProcessor) { + result = [self.optionsProcessor processedResultForURL:url options:options context:context]; + } + if (!result) { + // Use default options result + result = [[SDWebImageOptionsResult alloc] initWithOptions:options context:context]; + } + + return result; +} + +@end + + +@implementation SDWebImageCombinedOperation + +- (void)cancel { + @synchronized(self) { + if (self.isCancelled) { + return; + } + self.cancelled = YES; + if (self.cacheOperation) { + [self.cacheOperation cancel]; + self.cacheOperation = nil; + } + if (self.loaderOperation) { + [self.loaderOperation cancel]; + self.loaderOperation = nil; + } + [self.manager safelyRemoveOperationFromRunning:self]; + } +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageOperation.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageOperation.h new file mode 100644 index 0000000..50266db --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageOperation.h @@ -0,0 +1,21 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +/// A protocol represents cancelable operation. +@protocol SDWebImageOperation + +- (void)cancel; + +@end + +/// NSOperation conform to `SDWebImageOperation`. +@interface NSOperation (SDWebImageOperation) + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.h new file mode 100644 index 0000000..31ef153 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.h @@ -0,0 +1,72 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" + +@class SDWebImageOptionsResult; + +typedef SDWebImageOptionsResult * _Nullable(^SDWebImageOptionsProcessorBlock)(NSURL * _Nullable url, SDWebImageOptions options, SDWebImageContext * _Nullable context); + +/** + The options result contains both options and context. + */ +@interface SDWebImageOptionsResult : NSObject + +/** + WebCache options. + */ +@property (nonatomic, assign, readonly) SDWebImageOptions options; + +/** + Context options. + */ +@property (nonatomic, copy, readonly, nullable) SDWebImageContext *context; + +/** + Create a new options result. + + @param options options + @param context context + @return The options result contains both options and context. + */ +- (nonnull instancetype)initWithOptions:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context; + +@end + +/** + This is the protocol for options processor. + Options processor can be used, to control the final result for individual image request's `SDWebImageOptions` and `SDWebImageContext` + Implements the protocol to have a global control for each indivadual image request's option. + */ +@protocol SDWebImageOptionsProcessor + +/** + Return the processed options result for specify image URL, with its options and context + + @param url The URL to the image + @param options A mask to specify options to use for this request + @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + @return The processed result, contains both options and context + */ +- (nullable SDWebImageOptionsResult *)processedResultForURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +@end + +/** + A options processor class with block. + */ +@interface SDWebImageOptionsProcessor : NSObject + +- (nonnull instancetype)initWithBlock:(nonnull SDWebImageOptionsProcessorBlock)block; ++ (nonnull instancetype)optionsProcessorWithBlock:(nonnull SDWebImageOptionsProcessorBlock)block; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.m new file mode 100644 index 0000000..8e7bc35 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageOptionsProcessor.m @@ -0,0 +1,59 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageOptionsProcessor.h" + +@interface SDWebImageOptionsResult () + +@property (nonatomic, assign) SDWebImageOptions options; +@property (nonatomic, copy, nullable) SDWebImageContext *context; + +@end + +@implementation SDWebImageOptionsResult + +- (instancetype)initWithOptions:(SDWebImageOptions)options context:(SDWebImageContext *)context { + self = [super init]; + if (self) { + self.options = options; + self.context = context; + } + return self; +} + +@end + +@interface SDWebImageOptionsProcessor () + +@property (nonatomic, copy, nonnull) SDWebImageOptionsProcessorBlock block; + +@end + +@implementation SDWebImageOptionsProcessor + +- (instancetype)initWithBlock:(SDWebImageOptionsProcessorBlock)block { + self = [super init]; + if (self) { + self.block = block; + } + return self; +} + ++ (instancetype)optionsProcessorWithBlock:(SDWebImageOptionsProcessorBlock)block { + SDWebImageOptionsProcessor *optionsProcessor = [[SDWebImageOptionsProcessor alloc] initWithBlock:block]; + return optionsProcessor; +} + +- (SDWebImageOptionsResult *)processedResultForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context { + if (!self.block) { + return nil; + } + return self.block(url, options, context); +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.h new file mode 100644 index 0000000..6ee37d3 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.h @@ -0,0 +1,143 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageManager.h" + +@class SDWebImagePrefetcher; + +/** + A token represents a list of URLs, can be used to cancel the download. + */ +@interface SDWebImagePrefetchToken : NSObject + +/** + * Cancel the current prefetching. + */ +- (void)cancel; + +/** + list of URLs of current prefetching. + */ +@property (nonatomic, copy, readonly, nullable) NSArray *urls; + +@end + +/** + The prefetcher delegate protocol + */ +@protocol SDWebImagePrefetcherDelegate + +@optional + +/** + * Called when an image was prefetched. Which means it's called when one URL from any of prefetching finished. + * + * @param imagePrefetcher The current image prefetcher + * @param imageURL The image url that was prefetched + * @param finishedCount The total number of images that were prefetched (successful or not) + * @param totalCount The total number of images that were to be prefetched + */ +- (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(nullable NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; + +/** + * Called when all images are prefetched. Which means it's called when all URLs from all of prefetching finished. + * @param imagePrefetcher The current image prefetcher + * @param totalCount The total number of images that were prefetched (whether successful or not) + * @param skippedCount The total number of images that were skipped + */ +- (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; + +@end + +typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); +typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); + +/** + * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. + */ +@interface SDWebImagePrefetcher : NSObject + +/** + * The web image manager used by prefetcher to prefetch images. + * @note You can specify a standalone manager and downloader with custom configuration suitable for image prefetching. Such as `currentDownloadCount` or `downloadTimeout`. + */ +@property (strong, nonatomic, readonly, nonnull) SDWebImageManager *manager; + +/** + * Maximum number of URLs to prefetch at the same time. Defaults to 3. + */ +@property (nonatomic, assign) NSUInteger maxConcurrentPrefetchCount; + +/** + * The options for prefetcher. Defaults to SDWebImageLowPriority. + */ +@property (nonatomic, assign) SDWebImageOptions options; + +/** + * The context for prefetcher. Defaults to nil. + */ +@property (nonatomic, copy, nullable) SDWebImageContext *context; + +/** + * Queue options for prefetcher when call the progressBlock, completionBlock and delegate methods. Defaults to Main Queue. + * @note The call is asynchronously to avoid blocking target queue. + * @note The delegate queue should be set before any prefetching start and may not be changed during prefetching to avoid thread-safe problem. + */ +@property (strong, nonatomic, nonnull) dispatch_queue_t delegateQueue; + +/** + * The delegate for the prefetcher. Defatuls to nil. + */ +@property (weak, nonatomic, nullable) id delegate; + +/** + * Returns the global shared image prefetcher instance. It use a standalone manager which is different from shared manager. + */ +@property (nonatomic, class, readonly, nonnull) SDWebImagePrefetcher *sharedImagePrefetcher; + +/** + * Allows you to instantiate a prefetcher with any arbitrary image manager. + */ +- (nonnull instancetype)initWithImageManager:(nonnull SDWebImageManager *)manager NS_DESIGNATED_INITIALIZER; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching. It based on the image manager so the image may from the cache and network according to the `options` property. + * Prefetching is seperate to each other, which means the progressBlock and completionBlock you provide is bind to the prefetching for the list of urls. + * Attention that call this will not cancel previous fetched urls. You should keep the token return by this to cancel or cancel all the prefetch. + * + * @param urls list of URLs to prefetch + * @return the token to cancel the current prefetching. + */ +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching. It based on the image manager so the image may from the cache and network according to the `options` property. + * Prefetching is seperate to each other, which means the progressBlock and completionBlock you provide is bind to the prefetching for the list of urls. + * Attention that call this will not cancel previous fetched urls. You should keep the token return by this to cancel or cancel all the prefetch. + * + * @param urls list of URLs to prefetch + * @param progressBlock block to be called when progress updates; + * first parameter is the number of completed (successful or not) requests, + * second parameter is the total number of images originally requested to be prefetched + * @param completionBlock block to be called when the current prefetching is completed + * first param is the number of completed (successful or not) requests, + * second parameter is the number of skipped requests + * @return the token to cancel the current prefetching. + */ +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls + progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock + completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock; + +/** + * Remove and cancel all the prefeching for the prefetcher. + */ +- (void)cancelPrefetching; + + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.m new file mode 100644 index 0000000..efcb5c7 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImagePrefetcher.m @@ -0,0 +1,288 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImagePrefetcher.h" +#import "SDAsyncBlockOperation.h" +#import "SDInternalMacros.h" +#import + +@interface SDWebImagePrefetchToken () { + @public + // Though current implementation, `SDWebImageManager` completion block is always on main queue. But however, there is no guarantee in docs. And we may introduce config to specify custom queue in the future. + // These value are just used as incrementing counter, keep thread-safe using memory_order_relaxed for performance. + atomic_ulong _skippedCount; + atomic_ulong _finishedCount; + atomic_flag _isAllFinished; + + unsigned long _totalCount; +} + +@property (nonatomic, copy, readwrite) NSArray *urls; +@property (nonatomic, strong) NSPointerArray *loadOperations; +@property (nonatomic, strong) NSPointerArray *prefetchOperations; +@property (nonatomic, weak) SDWebImagePrefetcher *prefetcher; +@property (nonatomic, copy, nullable) SDWebImagePrefetcherCompletionBlock completionBlock; +@property (nonatomic, copy, nullable) SDWebImagePrefetcherProgressBlock progressBlock; + +@end + +@interface SDWebImagePrefetcher () + +@property (strong, nonatomic, nonnull) SDWebImageManager *manager; +@property (strong, atomic, nonnull) NSMutableSet *runningTokens; +@property (strong, nonatomic, nonnull) NSOperationQueue *prefetchQueue; + +@end + +@implementation SDWebImagePrefetcher + ++ (nonnull instancetype)sharedImagePrefetcher { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (nonnull instancetype)init { + return [self initWithImageManager:[SDWebImageManager new]]; +} + +- (nonnull instancetype)initWithImageManager:(SDWebImageManager *)manager { + if ((self = [super init])) { + _manager = manager; + _runningTokens = [NSMutableSet set]; + _options = SDWebImageLowPriority; + _delegateQueue = dispatch_get_main_queue(); + _prefetchQueue = [NSOperationQueue new]; + self.maxConcurrentPrefetchCount = 3; + } + return self; +} + +- (void)setMaxConcurrentPrefetchCount:(NSUInteger)maxConcurrentPrefetchCount { + self.prefetchQueue.maxConcurrentOperationCount = maxConcurrentPrefetchCount; +} + +- (NSUInteger)maxConcurrentPrefetchCount { + return self.prefetchQueue.maxConcurrentOperationCount; +} + +#pragma mark - Prefetch +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls { + return [self prefetchURLs:urls progress:nil completed:nil]; +} + +- (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray *)urls + progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock + completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock { + if (!urls || urls.count == 0) { + if (completionBlock) { + completionBlock(0, 0); + } + return nil; + } + SDWebImagePrefetchToken *token = [SDWebImagePrefetchToken new]; + token.prefetcher = self; + token.urls = urls; + token->_skippedCount = 0; + token->_finishedCount = 0; + token->_totalCount = token.urls.count; + atomic_flag_clear(&(token->_isAllFinished)); + token.loadOperations = [NSPointerArray weakObjectsPointerArray]; + token.prefetchOperations = [NSPointerArray weakObjectsPointerArray]; + token.progressBlock = progressBlock; + token.completionBlock = completionBlock; + [self addRunningToken:token]; + [self startPrefetchWithToken:token]; + + return token; +} + +- (void)startPrefetchWithToken:(SDWebImagePrefetchToken * _Nonnull)token { + NSPointerArray *operations = token.loadOperations; + for (NSURL *url in token.urls) { + @autoreleasepool { + @weakify(self); + SDAsyncBlockOperation *prefetchOperation = [SDAsyncBlockOperation blockOperationWithBlock:^(SDAsyncBlockOperation * _Nonnull asyncOperation) { + @strongify(self); + if (!self || asyncOperation.isCancelled) { + return; + } + id operation = [self.manager loadImageWithURL:url options:self.options context:self.context progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + @strongify(self); + if (!self) { + return; + } + if (!finished) { + return; + } + atomic_fetch_add_explicit(&(token->_finishedCount), 1, memory_order_relaxed); + if (error) { + // Add last failed + atomic_fetch_add_explicit(&(token->_skippedCount), 1, memory_order_relaxed); + } + + // Current operation finished + [self callProgressBlockForToken:token imageURL:imageURL]; + + if (atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed) == token->_totalCount) { + // All finished + if (!atomic_flag_test_and_set_explicit(&(token->_isAllFinished), memory_order_relaxed)) { + [self callCompletionBlockForToken:token]; + [self removeRunningToken:token]; + } + } + [asyncOperation complete]; + }]; + NSAssert(operation != nil, @"Operation should not be nil, [SDWebImageManager loadImageWithURL:options:context:progress:completed:] break prefetch logic"); + @synchronized (token) { + [operations addPointer:(__bridge void *)operation]; + } + }]; + @synchronized (token) { + [token.prefetchOperations addPointer:(__bridge void *)prefetchOperation]; + } + [self.prefetchQueue addOperation:prefetchOperation]; + } + } +} + +#pragma mark - Cancel +- (void)cancelPrefetching { + @synchronized(self.runningTokens) { + NSSet *copiedTokens = [self.runningTokens copy]; + [copiedTokens makeObjectsPerformSelector:@selector(cancel)]; + [self.runningTokens removeAllObjects]; + } +} + +- (void)callProgressBlockForToken:(SDWebImagePrefetchToken *)token imageURL:(NSURL *)url { + if (!token) { + return; + } + BOOL shouldCallDelegate = [self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]; + NSUInteger tokenFinishedCount = [self tokenFinishedCount]; + NSUInteger tokenTotalCount = [self tokenTotalCount]; + NSUInteger finishedCount = atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed); + NSUInteger totalCount = token->_totalCount; + dispatch_async(self.delegateQueue, ^{ + if (shouldCallDelegate) { + [self.delegate imagePrefetcher:self didPrefetchURL:url finishedCount:tokenFinishedCount totalCount:tokenTotalCount]; + } + if (token.progressBlock) { + token.progressBlock(finishedCount, totalCount); + } + }); +} + +- (void)callCompletionBlockForToken:(SDWebImagePrefetchToken *)token { + if (!token) { + return; + } + BOOL shoulCallDelegate = [self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)] && ([self countOfRunningTokens] == 1); // last one + NSUInteger tokenTotalCount = [self tokenTotalCount]; + NSUInteger tokenSkippedCount = [self tokenSkippedCount]; + NSUInteger finishedCount = atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed); + NSUInteger skippedCount = atomic_load_explicit(&(token->_skippedCount), memory_order_relaxed); + dispatch_async(self.delegateQueue, ^{ + if (shoulCallDelegate) { + [self.delegate imagePrefetcher:self didFinishWithTotalCount:tokenTotalCount skippedCount:tokenSkippedCount]; + } + if (token.completionBlock) { + token.completionBlock(finishedCount, skippedCount); + } + }); +} + +#pragma mark - Helper +- (NSUInteger)tokenTotalCount { + NSUInteger tokenTotalCount = 0; + @synchronized (self.runningTokens) { + for (SDWebImagePrefetchToken *token in self.runningTokens) { + tokenTotalCount += token->_totalCount; + } + } + return tokenTotalCount; +} + +- (NSUInteger)tokenSkippedCount { + NSUInteger tokenSkippedCount = 0; + @synchronized (self.runningTokens) { + for (SDWebImagePrefetchToken *token in self.runningTokens) { + tokenSkippedCount += atomic_load_explicit(&(token->_skippedCount), memory_order_relaxed); + } + } + return tokenSkippedCount; +} + +- (NSUInteger)tokenFinishedCount { + NSUInteger tokenFinishedCount = 0; + @synchronized (self.runningTokens) { + for (SDWebImagePrefetchToken *token in self.runningTokens) { + tokenFinishedCount += atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed); + } + } + return tokenFinishedCount; +} + +- (void)addRunningToken:(SDWebImagePrefetchToken *)token { + if (!token) { + return; + } + @synchronized (self.runningTokens) { + [self.runningTokens addObject:token]; + } +} + +- (void)removeRunningToken:(SDWebImagePrefetchToken *)token { + if (!token) { + return; + } + @synchronized (self.runningTokens) { + [self.runningTokens removeObject:token]; + } +} + +- (NSUInteger)countOfRunningTokens { + NSUInteger count = 0; + @synchronized (self.runningTokens) { + count = self.runningTokens.count; + } + return count; +} + +@end + +@implementation SDWebImagePrefetchToken + +- (void)cancel { + @synchronized (self) { + [self.prefetchOperations compact]; + for (id operation in self.prefetchOperations) { + if ([operation conformsToProtocol:@protocol(SDWebImageOperation)]) { + [operation cancel]; + } + } + self.prefetchOperations.count = 0; + + [self.loadOperations compact]; + for (id operation in self.loadOperations) { + if ([operation conformsToProtocol:@protocol(SDWebImageOperation)]) { + [operation cancel]; + } + } + self.loadOperations.count = 0; + } + self.completionBlock = nil; + self.progressBlock = nil; + [self.prefetcher removeRunningToken:self]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.h new file mode 100644 index 0000000..ea52b31 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.h @@ -0,0 +1,89 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT || SD_MAC +#import "SDImageCache.h" + +#if SD_UIKIT +typedef UIViewAnimationOptions SDWebImageAnimationOptions; +#else +typedef NS_OPTIONS(NSUInteger, SDWebImageAnimationOptions) { + SDWebImageAnimationOptionAllowsImplicitAnimation = 1 << 0, // specify `allowsImplicitAnimation` for the `NSAnimationContext` +}; +#endif + +typedef void (^SDWebImageTransitionPreparesBlock)(__kindof UIView * _Nonnull view, UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL); +typedef void (^SDWebImageTransitionAnimationsBlock)(__kindof UIView * _Nonnull view, UIImage * _Nullable image); +typedef void (^SDWebImageTransitionCompletionBlock)(BOOL finished); + +/** + This class is used to provide a transition animation after the view category load image finished. Use this on `sd_imageTransition` in UIView+WebCache.h + for UIKit(iOS & tvOS), we use `+[UIView transitionWithView:duration:options:animations:completion]` for transition animation. + for AppKit(macOS), we use `+[NSAnimationContext runAnimationGroup:completionHandler:]` for transition animation. You can call `+[NSAnimationContext currentContext]` to grab the context during animations block. + @note These transition are provided for basic usage. If you need complicated animation, consider to directly use Core Animation or use `SDWebImageAvoidAutoSetImage` and implement your own after image load finished. + */ +@interface SDWebImageTransition : NSObject + +/** + By default, we set the image to the view at the beginning of the animtions. You can disable this and provide custom set image process + */ +@property (nonatomic, assign) BOOL avoidAutoSetImage; +/** + The duration of the transition animation, measured in seconds. Defaults to 0.5. + */ +@property (nonatomic, assign) NSTimeInterval duration; +/** + The timing function used for all animations within this transition animation (macOS). + */ +@property (nonatomic, strong, nullable) CAMediaTimingFunction *timingFunction API_UNAVAILABLE(ios, tvos, watchos); +/** + A mask of options indicating how you want to perform the animations. + */ +@property (nonatomic, assign) SDWebImageAnimationOptions animationOptions; +/** + A block object to be executed before the animation sequence starts. + */ +@property (nonatomic, copy, nullable) SDWebImageTransitionPreparesBlock prepares; +/** + A block object that contains the changes you want to make to the specified view. + */ +@property (nonatomic, copy, nullable) SDWebImageTransitionAnimationsBlock animations; +/** + A block object to be executed when the animation sequence ends. + */ +@property (nonatomic, copy, nullable) SDWebImageTransitionCompletionBlock completion; + +@end + +/** + Convenience way to create transition. Remember to specify the duration if needed. + for UIKit, these transition just use the correspond `animationOptions`. By default we enable `UIViewAnimationOptionAllowUserInteraction` to allow user interaction during transition. + for AppKit, these transition use Core Animation in `animations`. So your view must be layer-backed. Set `wantsLayer = YES` before you apply it. + */ +@interface SDWebImageTransition (Conveniences) + +/// Fade transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *fadeTransition; +/// Flip from left transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromLeftTransition; +/// Flip from right transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromRightTransition; +/// Flip from top transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromTopTransition; +/// Flip from bottom transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *flipFromBottomTransition; +/// Curl up transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *curlUpTransition; +/// Curl down transition. +@property (nonatomic, class, nonnull, readonly) SDWebImageTransition *curlDownTransition; + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.m new file mode 100644 index 0000000..b04a4c3 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/SDWebImageTransition.m @@ -0,0 +1,137 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageTransition.h" + +#if SD_UIKIT || SD_MAC + +#if SD_MAC +#import +#endif + +@implementation SDWebImageTransition + +- (instancetype)init { + self = [super init]; + if (self) { + self.duration = 0.5; + } + return self; +} + +@end + +@implementation SDWebImageTransition (Conveniences) + ++ (SDWebImageTransition *)fadeTransition { + SDWebImageTransition *transition = [SDWebImageTransition new]; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animations = ^(__kindof NSView * _Nonnull view, NSImage * _Nullable image) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionFade; + [view.layer addAnimation:trans forKey:kCATransition]; + }; +#endif + return transition; +} + ++ (SDWebImageTransition *)flipFromLeftTransition { + SDWebImageTransition *transition = [SDWebImageTransition new]; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionFlipFromLeft | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animations = ^(__kindof NSView * _Nonnull view, NSImage * _Nullable image) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionPush; + trans.subtype = kCATransitionFromLeft; + [view.layer addAnimation:trans forKey:kCATransition]; + }; +#endif + return transition; +} + ++ (SDWebImageTransition *)flipFromRightTransition { + SDWebImageTransition *transition = [SDWebImageTransition new]; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionFlipFromRight | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animations = ^(__kindof NSView * _Nonnull view, NSImage * _Nullable image) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionPush; + trans.subtype = kCATransitionFromRight; + [view.layer addAnimation:trans forKey:kCATransition]; + }; +#endif + return transition; +} + ++ (SDWebImageTransition *)flipFromTopTransition { + SDWebImageTransition *transition = [SDWebImageTransition new]; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionFlipFromTop | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animations = ^(__kindof NSView * _Nonnull view, NSImage * _Nullable image) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionPush; + trans.subtype = kCATransitionFromTop; + [view.layer addAnimation:trans forKey:kCATransition]; + }; +#endif + return transition; +} + ++ (SDWebImageTransition *)flipFromBottomTransition { + SDWebImageTransition *transition = [SDWebImageTransition new]; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionFlipFromBottom | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animations = ^(__kindof NSView * _Nonnull view, NSImage * _Nullable image) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionPush; + trans.subtype = kCATransitionFromBottom; + [view.layer addAnimation:trans forKey:kCATransition]; + }; +#endif + return transition; +} + ++ (SDWebImageTransition *)curlUpTransition { + SDWebImageTransition *transition = [SDWebImageTransition new]; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionCurlUp | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animations = ^(__kindof NSView * _Nonnull view, NSImage * _Nullable image) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionReveal; + trans.subtype = kCATransitionFromTop; + [view.layer addAnimation:trans forKey:kCATransition]; + }; +#endif + return transition; +} + ++ (SDWebImageTransition *)curlDownTransition { + SDWebImageTransition *transition = [SDWebImageTransition new]; +#if SD_UIKIT + transition.animationOptions = UIViewAnimationOptionTransitionCurlDown | UIViewAnimationOptionAllowUserInteraction; +#else + transition.animations = ^(__kindof NSView * _Nonnull view, NSImage * _Nullable image) { + CATransition *trans = [CATransition animation]; + trans.type = kCATransitionReveal; + trans.subtype = kCATransitionFromBottom; + [view.layer addAnimation:trans forKey:kCATransition]; + }; +#endif + return transition; +} + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.h new file mode 100644 index 0000000..89d94b4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.h @@ -0,0 +1,387 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT + +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIButton. + */ +@interface UIButton (WebCache) + +#pragma mark - Image + +/** + * Get the current image URL. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentImageURL; + +/** + * Get the image URL for a control state. + * + * @param state Which state you want to know the URL for. The values are described in UIControlState. + */ +- (nullable NSURL *)sd_imageURLForState:(UIControlState)state; + +/** + * Set the button `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the button `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +#pragma mark - Background Image + +/** + * Get the current background image URL. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_currentBackgroundImageURL; + +/** + * Get the background image URL for a control state. + * + * @param state Which state you want to know the URL for. The values are described in UIControlState. + */ +- (nullable NSURL *)sd_backgroundImageURLForState:(UIControlState)state; + +/** + * Set the button `backgroundImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state NS_REFINED_FOR_SWIFT; + +/** + * Set the button `backgroundImage` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the button `backgroundImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the button `backgroundImage` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the button `backgroundImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `backgroundImage` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param state The state that uses the specified title. The values are described in UIControlState. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the button `backgroundImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `backgroundImage` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the button `backgroundImage` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +#pragma mark - Cancel + +/** + * Cancel the current image download + */ +- (void)sd_cancelImageLoadForState:(UIControlState)state; + +/** + * Cancel the current backgroundImage download + */ +- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state; + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.m new file mode 100644 index 0000000..4ccd029 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIButton+WebCache.m @@ -0,0 +1,234 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIButton+WebCache.h" + +#if SD_UIKIT + +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCache.h" +#import "SDInternalMacros.h" + +static char imageURLStorageKey; + +typedef NSMutableDictionary SDStateImageURLDictionary; + +static inline NSString * imageURLKeyForState(UIControlState state) { + return [NSString stringWithFormat:@"image_%lu", (unsigned long)state]; +} + +static inline NSString * backgroundImageURLKeyForState(UIControlState state) { + return [NSString stringWithFormat:@"backgroundImage_%lu", (unsigned long)state]; +} + +static inline NSString * imageOperationKeyForState(UIControlState state) { + return [NSString stringWithFormat:@"UIButtonImageOperation%lu", (unsigned long)state]; +} + +static inline NSString * backgroundImageOperationKeyForState(UIControlState state) { + return [NSString stringWithFormat:@"UIButtonBackgroundImageOperation%lu", (unsigned long)state]; +} + +@implementation UIButton (WebCache) + +#pragma mark - Image + +- (nullable NSURL *)sd_currentImageURL { + NSURL *url = self.sd_imageURLStorage[imageURLKeyForState(self.state)]; + + if (!url) { + url = self.sd_imageURLStorage[imageURLKeyForState(UIControlStateNormal)]; + } + + return url; +} + +- (nullable NSURL *)sd_imageURLForState:(UIControlState)state { + return self.sd_imageURLStorage[imageURLKeyForState(state)]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { + [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + if (!url) { + [self.sd_imageURLStorage removeObjectForKey:imageURLKeyForState(state)]; + } else { + self.sd_imageURLStorage[imageURLKeyForState(state)] = url; + } + + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextSetImageOperationKey] = imageOperationKeyForState(state); + @weakify(self); + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:mutableContext + setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) { + @strongify(self); + [self setImage:image forState:state]; + } + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - Background Image + +- (nullable NSURL *)sd_currentBackgroundImageURL { + NSURL *url = self.sd_imageURLStorage[backgroundImageURLKeyForState(self.state)]; + + if (!url) { + url = self.sd_imageURLStorage[backgroundImageURLKeyForState(UIControlStateNormal)]; + } + + return url; +} + +- (nullable NSURL *)sd_backgroundImageURLForState:(UIControlState)state { + return self.sd_imageURLStorage[backgroundImageURLKeyForState(state)]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + if (!url) { + [self.sd_imageURLStorage removeObjectForKey:backgroundImageURLKeyForState(state)]; + } else { + self.sd_imageURLStorage[backgroundImageURLKeyForState(state)] = url; + } + + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextSetImageOperationKey] = backgroundImageOperationKeyForState(state); + @weakify(self); + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:mutableContext + setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) { + @strongify(self); + [self setBackgroundImage:image forState:state]; + } + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +#pragma mark - Cancel + +- (void)sd_cancelImageLoadForState:(UIControlState)state { + [self sd_cancelImageLoadOperationWithKey:imageOperationKeyForState(state)]; +} + +- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { + [self sd_cancelImageLoadOperationWithKey:backgroundImageOperationKeyForState(state)]; +} + +#pragma mark - Private + +- (SDStateImageURLDictionary *)sd_imageURLStorage { + SDStateImageURLDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); + if (!storage) { + storage = [NSMutableDictionary dictionary]; + objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + + return storage; +} + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.h new file mode 100644 index 0000000..482c8c4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.h @@ -0,0 +1,24 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* (c) Fabrice Aneche +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" + +@interface UIImage (ExtendedCacheData) + +/** + Read and Write the extended object and bind it to the image. Which can hold some extra metadata like Image's scale factor, URL rich link, date, etc. + The extended object should conforms to NSCoding, which we use `NSKeyedArchiver` and `NSKeyedUnarchiver` to archive it to data, and write to disk cache. + @note The disk cache preserve both of the data and extended data with the same cache key. For manual query, use the `SDDiskCache` protocol method `extendedDataForKey:` instead. + @note You can specify arbitrary object conforms to NSCoding (NSObject protocol here is used to support object using `NS_ROOT_CLASS`, which is not NSObject subclass). If you load image from disk cache, you should check the extended object class to avoid corrupted data. + @warning This object don't need to implements NSSecureCoding (but it's recommended), because we allows arbitrary class. + */ +@property (nonatomic, strong, nullable) id sd_extendedObject; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.m new file mode 100644 index 0000000..05d29cf --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ExtendedCacheData.m @@ -0,0 +1,23 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* (c) Fabrice Aneche +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "UIImage+ExtendedCacheData.h" +#import + +@implementation UIImage (ExtendedCacheData) + +- (id)sd_extendedObject { + return objc_getAssociatedObject(self, @selector(sd_extendedObject)); +} + +- (void)setSd_extendedObject:(id)sd_extendedObject { + objc_setAssociatedObject(self, @selector(sd_extendedObject), sd_extendedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.h new file mode 100644 index 0000000..f368746 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.h @@ -0,0 +1,46 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +/** + UIImage category about force decode feature (avoid Image/IO's lazy decoding during rendering behavior). + */ +@interface UIImage (ForceDecode) + +/** + A bool value indicating whether the image has already been decoded. This can help to avoid extra force decode. + */ +@property (nonatomic, assign) BOOL sd_isDecoded; + +/** + Decode the provided image. This is useful if you want to force decode the image before rendering to improve performance. + + @param image The image to be decoded + @return The decoded image + */ ++ (nullable UIImage *)sd_decodedImageWithImage:(nullable UIImage *)image; + +/** + Decode and scale down the provided image + + @param image The image to be decoded + @return The decoded and scaled down image + */ ++ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image; + +/** + Decode and scale down the provided image with limit bytes + + @param image The image to be decoded + @param bytes The limit bytes size. Provide 0 to use the build-in limit. + @return The decoded and scaled down image + */ ++ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image limitBytes:(NSUInteger)bytes; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.m new file mode 100644 index 0000000..1b20bbd --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+ForceDecode.m @@ -0,0 +1,42 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+ForceDecode.h" +#import "SDImageCoderHelper.h" +#import "objc/runtime.h" + +@implementation UIImage (ForceDecode) + +- (BOOL)sd_isDecoded { + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_isDecoded)); + return value.boolValue; +} + +- (void)setSd_isDecoded:(BOOL)sd_isDecoded { + objc_setAssociatedObject(self, @selector(sd_isDecoded), @(sd_isDecoded), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + ++ (nullable UIImage *)sd_decodedImageWithImage:(nullable UIImage *)image { + if (!image) { + return nil; + } + return [SDImageCoderHelper decodedImageWithImage:image]; +} + ++ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image { + return [self sd_decodedAndScaledDownImageWithImage:image limitBytes:0]; +} + ++ (nullable UIImage *)sd_decodedAndScaledDownImageWithImage:(nullable UIImage *)image limitBytes:(NSUInteger)bytes { + if (!image) { + return nil; + } + return [SDImageCoderHelper decodedAndScaledDownImageWithImage:image limitBytes:bytes]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.h new file mode 100644 index 0000000..7504c71 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.h @@ -0,0 +1,26 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Laurin Brandner + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +/** + This category is just use as a convenience method. For more detail control, use methods in `UIImage+MultiFormat.h` or directlly use `SDImageCoder`. + */ +@interface UIImage (GIF) + +/** + Creates an animated UIImage from an NSData. + This will create animated image if the data is Animated GIF. And will create a static image is the data is Static GIF. + + @param data The GIF data + @return The created image + */ ++ (nullable UIImage *)sd_imageWithGIFData:(nullable NSData *)data; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.m new file mode 100644 index 0000000..7158cf3 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+GIF.m @@ -0,0 +1,22 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Laurin Brandner + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+GIF.h" +#import "SDImageGIFCoder.h" + +@implementation UIImage (GIF) + ++ (nullable UIImage *)sd_imageWithGIFData:(nullable NSData *)data { + if (!data) { + return nil; + } + return [[SDImageGIFCoder sharedCoder] decodedImageWithData:data options:0]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.h new file mode 100644 index 0000000..5b0fe58 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.h @@ -0,0 +1,27 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +/** + UIImage category for memory cache cost. + */ +@interface UIImage (MemoryCacheCost) + +/** + The memory cache cost for specify image used by image cache. The cost function is the bytes size held in memory. + If you set some associated object to `UIImage`, you can set the custom value to indicate the memory cost. + + For `UIImage`, this method return the single frame bytes size when `image.images` is nil for static image. Retuen full frame bytes size when `image.images` is not nil for animated image. + For `NSImage`, this method return the single frame bytes size because `NSImage` does not store all frames in memory. + @note Note that because of the limitations of category this property can get out of sync if you create another instance with CGImage or other methods. + @note For custom animated class conforms to `SDAnimatedImage`, you can override this getter method in your subclass to return a more proper value instead, which representing the current frame's total bytes. + */ +@property (assign, nonatomic) NSUInteger sd_memoryCost; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.m new file mode 100644 index 0000000..b0883b1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MemoryCacheCost.m @@ -0,0 +1,46 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+MemoryCacheCost.h" +#import "objc/runtime.h" +#import "NSImage+Compatibility.h" + +FOUNDATION_STATIC_INLINE NSUInteger SDMemoryCacheCostForImage(UIImage *image) { + CGImageRef imageRef = image.CGImage; + if (!imageRef) { + return 0; + } + NSUInteger bytesPerFrame = CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef); + NSUInteger frameCount; +#if SD_MAC + frameCount = 1; +#elif SD_UIKIT || SD_WATCH + frameCount = image.images.count > 0 ? image.images.count : 1; +#endif + NSUInteger cost = bytesPerFrame * frameCount; + return cost; +} + +@implementation UIImage (MemoryCacheCost) + +- (NSUInteger)sd_memoryCost { + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_memoryCost)); + NSUInteger memoryCost; + if (value != nil) { + memoryCost = [value unsignedIntegerValue]; + } else { + memoryCost = SDMemoryCacheCostForImage(self); + } + return memoryCost; +} + +- (void)setSd_memoryCost:(NSUInteger)sd_memoryCost { + objc_setAssociatedObject(self, @selector(sd_memoryCost), @(sd_memoryCost), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.h new file mode 100644 index 0000000..e42ff69 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.h @@ -0,0 +1,49 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "NSData+ImageContentType.h" + +/** + UIImage category for image metadata, including animation, loop count, format, incremental, etc. + */ +@interface UIImage (Metadata) + +/** + * UIKit: + * For static image format, this value is always 0. + * For animated image format, 0 means infinite looping. + * Note that because of the limitations of categories this property can get out of sync if you create another instance with CGImage or other methods. + * AppKit: + * NSImage currently only support animated via GIF imageRep unlike UIImage. + * The getter of this property will get the loop count from GIF imageRep + * The setter of this property will set the loop count from GIF imageRep + */ +@property (nonatomic, assign) NSUInteger sd_imageLoopCount; + +/** + * UIKit: + * Check the `images` array property + * AppKit: + * NSImage currently only support animated via GIF imageRep unlike UIImage. It will check the imageRep's frame count. + */ +@property (nonatomic, assign, readonly) BOOL sd_isAnimated; + +/** + * The image format represent the original compressed image data format. + * If you don't manually specify a format, this information is retrieve from CGImage using `CGImageGetUTType`, which may return nil for non-CG based image. At this time it will return `SDImageFormatUndefined` as default value. + * @note Note that because of the limitations of categories this property can get out of sync if you create another instance with CGImage or other methods. + */ +@property (nonatomic, assign) SDImageFormat sd_imageFormat; + +/** + A bool value indicating whether the image is during incremental decoding and may not contains full pixels. + */ +@property (nonatomic, assign) BOOL sd_isIncremental; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.m new file mode 100644 index 0000000..3c9bf92 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Metadata.m @@ -0,0 +1,108 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+Metadata.h" +#import "NSImage+Compatibility.h" +#import "objc/runtime.h" + +@implementation UIImage (Metadata) + +#if SD_UIKIT || SD_WATCH + +- (NSUInteger)sd_imageLoopCount { + NSUInteger imageLoopCount = 0; + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_imageLoopCount)); + if ([value isKindOfClass:[NSNumber class]]) { + imageLoopCount = value.unsignedIntegerValue; + } + return imageLoopCount; +} + +- (void)setSd_imageLoopCount:(NSUInteger)sd_imageLoopCount { + NSNumber *value = @(sd_imageLoopCount); + objc_setAssociatedObject(self, @selector(sd_imageLoopCount), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)sd_isAnimated { + return (self.images != nil); +} + +#else + +- (NSUInteger)sd_imageLoopCount { + NSUInteger imageLoopCount = 0; + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (bitmapImageRep) { + imageLoopCount = [[bitmapImageRep valueForProperty:NSImageLoopCount] unsignedIntegerValue]; + } + return imageLoopCount; +} + +- (void)setSd_imageLoopCount:(NSUInteger)sd_imageLoopCount { + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (bitmapImageRep) { + [bitmapImageRep setProperty:NSImageLoopCount withValue:@(sd_imageLoopCount)]; + } +} + +- (BOOL)sd_isAnimated { + BOOL isGIF = NO; + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + NSImageRep *imageRep = [self bestRepresentationForRect:imageRect context:nil hints:nil]; + NSBitmapImageRep *bitmapImageRep; + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapImageRep = (NSBitmapImageRep *)imageRep; + } + if (bitmapImageRep) { + NSUInteger frameCount = [[bitmapImageRep valueForProperty:NSImageFrameCount] unsignedIntegerValue]; + isGIF = frameCount > 1 ? YES : NO; + } + return isGIF; +} + +#endif + +- (SDImageFormat)sd_imageFormat { + SDImageFormat imageFormat = SDImageFormatUndefined; + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_imageFormat)); + if ([value isKindOfClass:[NSNumber class]]) { + imageFormat = value.integerValue; + return imageFormat; + } + // Check CGImage's UTType, may return nil for non-Image/IO based image + if (@available(iOS 9.0, tvOS 9.0, macOS 10.11, watchOS 2.0, *)) { + CFStringRef uttype = CGImageGetUTType(self.CGImage); + imageFormat = [NSData sd_imageFormatFromUTType:uttype]; + } + return imageFormat; +} + +- (void)setSd_imageFormat:(SDImageFormat)sd_imageFormat { + objc_setAssociatedObject(self, @selector(sd_imageFormat), @(sd_imageFormat), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (void)setSd_isIncremental:(BOOL)sd_isIncremental { + objc_setAssociatedObject(self, @selector(sd_isIncremental), @(sd_isIncremental), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)sd_isIncremental { + NSNumber *value = objc_getAssociatedObject(self, @selector(sd_isIncremental)); + return value.boolValue; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.h new file mode 100644 index 0000000..8431334 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.h @@ -0,0 +1,79 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "NSData+ImageContentType.h" + +/** + UIImage category for convenient image format decoding/encoding. + */ +@interface UIImage (MultiFormat) +#pragma mark - Decode +/** + Create and decode a image with the specify image data + + @param data The image data + @return The created image + */ ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data; + +/** + Create and decode a image with the specify image data and scale + + @param data The image data + @param scale The image scale factor. Should be greater than or equal to 1.0. + @return The created image + */ ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale; + +/** + Create and decode a image with the specify image data and scale, allow specify animate/static control + + @param data The image data + @param scale The image scale factor. Should be greater than or equal to 1.0. + @param firstFrameOnly Even if the image data is animated image format, decode the first frame only as static image. + @return The created image + */ ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale firstFrameOnly:(BOOL)firstFrameOnly; + +#pragma mark - Encode +/** + Encode the current image to the data, the image format is unspecified + + @return The encoded data. If can't encode, return nil + */ +- (nullable NSData *)sd_imageData; + +/** + Encode the current image to data with the specify image format + + @param imageFormat The specify image format + @return The encoded data. If can't encode, return nil + */ +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat NS_SWIFT_NAME(sd_imageData(as:)); + +/** + Encode the current image to data with the specify image format and compression quality + + @param imageFormat The specify image format + @param compressionQuality The quality of the resulting image data. Value between 0.0-1.0. Some coders may not support compression quality. + @return The encoded data. If can't encode, return nil + */ +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality NS_SWIFT_NAME(sd_imageData(as:compressionQuality:)); + +/** + Encode the current image to data with the specify image format and compression quality, allow specify animate/static control + + @param imageFormat The specify image format + @param compressionQuality The quality of the resulting image data. Value between 0.0-1.0. Some coders may not support compression quality. + @param firstFrameOnly Even if the image is animated image, encode the first frame only as static image. + @return The encoded data. If can't encode, return nil + */ +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality firstFrameOnly:(BOOL)firstFrameOnly NS_SWIFT_NAME(sd_imageData(as:compressionQuality:firstFrameOnly:)); + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.m new file mode 100644 index 0000000..04d08c5 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+MultiFormat.m @@ -0,0 +1,47 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+MultiFormat.h" +#import "SDImageCodersManager.h" + +@implementation UIImage (MultiFormat) + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data { + return [self sd_imageWithData:data scale:1]; +} + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale { + return [self sd_imageWithData:data scale:scale firstFrameOnly:NO]; +} + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale firstFrameOnly:(BOOL)firstFrameOnly { + if (!data) { + return nil; + } + SDImageCoderOptions *options = @{SDImageCoderDecodeScaleFactor : @(MAX(scale, 1)), SDImageCoderDecodeFirstFrameOnly : @(firstFrameOnly)}; + return [[SDImageCodersManager sharedManager] decodedImageWithData:data options:options]; +} + +- (nullable NSData *)sd_imageData { + return [self sd_imageDataAsFormat:SDImageFormatUndefined]; +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat { + return [self sd_imageDataAsFormat:imageFormat compressionQuality:1]; +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality { + return [self sd_imageDataAsFormat:imageFormat compressionQuality:compressionQuality firstFrameOnly:NO]; +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat compressionQuality:(double)compressionQuality firstFrameOnly:(BOOL)firstFrameOnly { + SDImageCoderOptions *options = @{SDImageCoderEncodeCompressionQuality : @(compressionQuality), SDImageCoderEncodeFirstFrameOnly : @(firstFrameOnly)}; + return [[SDImageCodersManager sharedManager] encodedDataWithImage:self format:imageFormat options:options]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.h new file mode 100644 index 0000000..717c08c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.h @@ -0,0 +1,146 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +typedef NS_ENUM(NSUInteger, SDImageScaleMode) { + SDImageScaleModeFill = 0, + SDImageScaleModeAspectFit = 1, + SDImageScaleModeAspectFill = 2 +}; + +#if SD_UIKIT || SD_WATCH +typedef UIRectCorner SDRectCorner; +#else +typedef NS_OPTIONS(NSUInteger, SDRectCorner) { + SDRectCornerTopLeft = 1 << 0, + SDRectCornerTopRight = 1 << 1, + SDRectCornerBottomLeft = 1 << 2, + SDRectCornerBottomRight = 1 << 3, + SDRectCornerAllCorners = ~0UL +}; +#endif + +/** + Provide some commen method for `UIImage`. + Image process is based on Core Graphics and vImage. + */ +@interface UIImage (Transform) + +#pragma mark - Image Geometry + +/** + Returns a new image which is resized from this image. + You can specify a larger or smaller size than the image size. The image content will be changed with the scale mode. + + @param size The new size to be resized, values should be positive. + @param scaleMode The scale mode for image content. + @return The new image with the given size. + */ +- (nullable UIImage *)sd_resizedImageWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode; + +/** + Returns a new image which is cropped from this image. + + @param rect Image's inner rect. + @return The new image with the cropping rect. + */ +- (nullable UIImage *)sd_croppedImageWithRect:(CGRect)rect; + +/** + Rounds a new image with a given corner radius and corners. + + @param cornerRadius The radius of each corner oval. Values larger than half the + rectangle's width or height are clamped appropriately to + half the width or height. + @param corners A bitmask value that identifies the corners that you want + rounded. You can use this parameter to round only a subset + of the corners of the rectangle. + @param borderWidth The inset border line width. Values larger than half the rectangle's + width or height are clamped appropriately to half the width + or height. + @param borderColor The border stroke color. nil means clear color. + @return The new image with the round corner. + */ +- (nullable UIImage *)sd_roundedCornerImageWithRadius:(CGFloat)cornerRadius + corners:(SDRectCorner)corners + borderWidth:(CGFloat)borderWidth + borderColor:(nullable UIColor *)borderColor; + +/** + Returns a new rotated image (relative to the center). + + @param angle Rotated radians in counterclockwise.⟲ + @param fitSize YES: new image's size is extend to fit all content. + NO: image's size will not change, content may be clipped. + @return The new image with the rotation. + */ +- (nullable UIImage *)sd_rotatedImageWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize; + +/** + Returns a new horizontally(vertically) flipped image. + + @param horizontal YES to flip the image horizontally. ⇋ + @param vertical YES to flip the image vertically. ⥯ + @return The new image with the flipping. + */ +- (nullable UIImage *)sd_flippedImageWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical; + +#pragma mark - Image Blending + +/** + Return a tinted image with the given color. This actually use alpha blending of current image and the tint color. + + @param tintColor The tint color. + @return The new image with the tint color. + */ +- (nullable UIImage *)sd_tintedImageWithColor:(nonnull UIColor *)tintColor; + +/** + Return the pixel color at specify position. The point is from the top-left to the bottom-right and 0-based. The returned the color is always be RGBA format. The image must be CG-based. + @note The point's x/y should not be smaller than 0, or greater than or equal to width/height. + @note The overhead of object creation means this method is best suited for infrequent color sampling. For heavy image processing, grab the raw bitmap data and process yourself. + + @param point The position of pixel + @return The color for specify pixel, or nil if any error occur + */ +- (nullable UIColor *)sd_colorAtPoint:(CGPoint)point; + +/** + Return the pixel color array with specify rectangle. The rect is from the top-left to the bottom-right and 0-based. The returned the color is always be RGBA format. The image must be CG-based. + @note The rect's width/height should not be smaller than or equal to 0. The minX/minY should not be smaller than 0. The maxX/maxY should not be greater than width/height. Attention this limit is different from `sd_colorAtPoint:` (point: (0, 0) like rect: (0, 0, 1, 1)) + @note The overhead of object creation means this method is best suited for infrequent color sampling. For heavy image processing, grab the raw bitmap data and process yourself. + + @param rect The rectangle of pixels + @return The color array for specify pixels, or nil if any error occur + */ +- (nullable NSArray *)sd_colorsWithRect:(CGRect)rect; + +#pragma mark - Image Effect + +/** + Return a new image applied a blur effect. + + @param blurRadius The radius of the blur in points, 0 means no blur effect. + + @return The new image with blur effect, or nil if an error occurs (e.g. no enough memory). + */ +- (nullable UIImage *)sd_blurredImageWithRadius:(CGFloat)blurRadius; + +#if SD_UIKIT || SD_MAC +/** + Return a new image applied a CIFilter. + + @param filter The CIFilter to be applied to the image. + @return The new image with the CIFilter, or nil if an error occurs (e.g. no + enough memory). + */ +- (nullable UIImage *)sd_filteredImageWithFilter:(nonnull CIFilter *)filter; +#endif + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.m new file mode 100644 index 0000000..a01cf12 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImage+Transform.m @@ -0,0 +1,711 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImage+Transform.h" +#import "NSImage+Compatibility.h" +#import "SDImageGraphics.h" +#import "SDGraphicsImageRenderer.h" +#import "NSBezierPath+RoundedCorners.h" +#import +#if SD_UIKIT || SD_MAC +#import +#endif + +static inline CGRect SDCGRectFitWithScaleMode(CGRect rect, CGSize size, SDImageScaleMode scaleMode) { + rect = CGRectStandardize(rect); + size.width = size.width < 0 ? -size.width : size.width; + size.height = size.height < 0 ? -size.height : size.height; + CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect)); + switch (scaleMode) { + case SDImageScaleModeAspectFit: + case SDImageScaleModeAspectFill: { + if (rect.size.width < 0.01 || rect.size.height < 0.01 || + size.width < 0.01 || size.height < 0.01) { + rect.origin = center; + rect.size = CGSizeZero; + } else { + CGFloat scale; + if (scaleMode == SDImageScaleModeAspectFit) { + if (size.width / size.height < rect.size.width / rect.size.height) { + scale = rect.size.height / size.height; + } else { + scale = rect.size.width / size.width; + } + } else { + if (size.width / size.height < rect.size.width / rect.size.height) { + scale = rect.size.width / size.width; + } else { + scale = rect.size.height / size.height; + } + } + size.width *= scale; + size.height *= scale; + rect.size = size; + rect.origin = CGPointMake(center.x - size.width * 0.5, center.y - size.height * 0.5); + } + } break; + case SDImageScaleModeFill: + default: { + rect = rect; + } + } + return rect; +} + +static inline UIColor * SDGetColorFromPixel(Pixel_8888 pixel, CGBitmapInfo bitmapInfo) { + // Get alpha info, byteOrder info + CGImageAlphaInfo alphaInfo = bitmapInfo & kCGBitmapAlphaInfoMask; + CGBitmapInfo byteOrderInfo = bitmapInfo & kCGBitmapByteOrderMask; + CGFloat r = 0, g = 0, b = 0, a = 1; + + BOOL byteOrderNormal = NO; + switch (byteOrderInfo) { + case kCGBitmapByteOrderDefault: { + byteOrderNormal = YES; + } break; + case kCGBitmapByteOrder32Little: { + } break; + case kCGBitmapByteOrder32Big: { + byteOrderNormal = YES; + } break; + default: break; + } + switch (alphaInfo) { + case kCGImageAlphaPremultipliedFirst: + case kCGImageAlphaFirst: { + if (byteOrderNormal) { + // ARGB8888 + a = pixel[0] / 255.0; + r = pixel[1] / 255.0; + g = pixel[2] / 255.0; + b = pixel[3] / 255.0; + } else { + // BGRA8888 + b = pixel[0] / 255.0; + g = pixel[1] / 255.0; + r = pixel[2] / 255.0; + a = pixel[3] / 255.0; + } + } + break; + case kCGImageAlphaPremultipliedLast: + case kCGImageAlphaLast: { + if (byteOrderNormal) { + // RGBA8888 + r = pixel[0] / 255.0; + g = pixel[1] / 255.0; + b = pixel[2] / 255.0; + a = pixel[3] / 255.0; + } else { + // ABGR8888 + a = pixel[0] / 255.0; + b = pixel[1] / 255.0; + g = pixel[2] / 255.0; + r = pixel[3] / 255.0; + } + } + break; + case kCGImageAlphaNone: { + if (byteOrderNormal) { + // RGB + r = pixel[0] / 255.0; + g = pixel[1] / 255.0; + b = pixel[2] / 255.0; + } else { + // BGR + b = pixel[0] / 255.0; + g = pixel[1] / 255.0; + r = pixel[2] / 255.0; + } + } + break; + case kCGImageAlphaNoneSkipLast: { + if (byteOrderNormal) { + // RGBX + r = pixel[0] / 255.0; + g = pixel[1] / 255.0; + b = pixel[2] / 255.0; + } else { + // XBGR + b = pixel[1] / 255.0; + g = pixel[2] / 255.0; + r = pixel[3] / 255.0; + } + } + break; + case kCGImageAlphaNoneSkipFirst: { + if (byteOrderNormal) { + // XRGB + r = pixel[1] / 255.0; + g = pixel[2] / 255.0; + b = pixel[3] / 255.0; + } else { + // BGRX + b = pixel[0] / 255.0; + g = pixel[1] / 255.0; + r = pixel[2] / 255.0; + } + } + break; + case kCGImageAlphaOnly: { + // A + a = pixel[0] / 255.0; + } + break; + default: + break; + } + + return [UIColor colorWithRed:r green:g blue:b alpha:a]; +} + +#if SD_UIKIT || SD_MAC +// Create-Rule, caller should call CGImageRelease +static inline CGImageRef _Nullable SDCreateCGImageFromCIImage(CIImage * _Nonnull ciImage) { + CGImageRef imageRef = NULL; + if (@available(iOS 10, macOS 10.12, tvOS 10, *)) { + imageRef = ciImage.CGImage; + } + if (!imageRef) { + CIContext *context = [CIContext context]; + imageRef = [context createCGImage:ciImage fromRect:ciImage.extent]; + } else { + CGImageRetain(imageRef); + } + return imageRef; +} +#endif + +@implementation UIImage (Transform) + +- (void)sd_drawInRect:(CGRect)rect context:(CGContextRef)context scaleMode:(SDImageScaleMode)scaleMode clipsToBounds:(BOOL)clips { + CGRect drawRect = SDCGRectFitWithScaleMode(rect, self.size, scaleMode); + if (drawRect.size.width == 0 || drawRect.size.height == 0) return; + if (clips) { + if (context) { + CGContextSaveGState(context); + CGContextAddRect(context, rect); + CGContextClip(context); + [self drawInRect:drawRect]; + CGContextRestoreGState(context); + } + } else { + [self drawInRect:drawRect]; + } +} + +- (nullable UIImage *)sd_resizedImageWithSize:(CGSize)size scaleMode:(SDImageScaleMode)scaleMode { + if (size.width <= 0 || size.height <= 0) return nil; + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = self.scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + [self sd_drawInRect:CGRectMake(0, 0, size.width, size.height) context:context scaleMode:scaleMode clipsToBounds:NO]; + }]; + return image; +} + +- (nullable UIImage *)sd_croppedImageWithRect:(CGRect)rect { + rect.origin.x *= self.scale; + rect.origin.y *= self.scale; + rect.size.width *= self.scale; + rect.size.height *= self.scale; + if (rect.size.width <= 0 || rect.size.height <= 0) return nil; + +#if SD_UIKIT || SD_MAC + // CIImage shortcut + if (self.CIImage) { + CGRect croppingRect = CGRectMake(rect.origin.x, self.size.height - CGRectGetMaxY(rect), rect.size.width, rect.size.height); + CIImage *ciImage = [self.CIImage imageByCroppingToRect:croppingRect]; +#if SD_UIKIT + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } +#endif + + CGImageRef imageRef = self.CGImage; + if (!imageRef) { + return nil; + } + + CGImageRef croppedImageRef = CGImageCreateWithImageInRect(imageRef, rect); + if (!croppedImageRef) { + return nil; + } +#if SD_UIKIT || SD_WATCH + UIImage *image = [UIImage imageWithCGImage:croppedImageRef scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCGImage:croppedImageRef scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + CGImageRelease(croppedImageRef); + return image; +} + +- (nullable UIImage *)sd_roundedCornerImageWithRadius:(CGFloat)cornerRadius corners:(SDRectCorner)corners borderWidth:(CGFloat)borderWidth borderColor:(nullable UIColor *)borderColor { + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = self.scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:self.size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height); + + CGFloat minSize = MIN(self.size.width, self.size.height); + if (borderWidth < minSize / 2) { +#if SD_UIKIT || SD_WATCH + UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(rect, borderWidth, borderWidth) byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)]; +#else + NSBezierPath *path = [NSBezierPath sd_bezierPathWithRoundedRect:CGRectInset(rect, borderWidth, borderWidth) byRoundingCorners:corners cornerRadius:cornerRadius]; +#endif + [path closePath]; + + CGContextSaveGState(context); + [path addClip]; + [self drawInRect:rect]; + CGContextRestoreGState(context); + } + + if (borderColor && borderWidth < minSize / 2 && borderWidth > 0) { + CGFloat strokeInset = (floor(borderWidth * self.scale) + 0.5) / self.scale; + CGRect strokeRect = CGRectInset(rect, strokeInset, strokeInset); + CGFloat strokeRadius = cornerRadius > self.scale / 2 ? cornerRadius - self.scale / 2 : 0; +#if SD_UIKIT || SD_WATCH + UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:strokeRect byRoundingCorners:corners cornerRadii:CGSizeMake(strokeRadius, strokeRadius)]; +#else + NSBezierPath *path = [NSBezierPath sd_bezierPathWithRoundedRect:strokeRect byRoundingCorners:corners cornerRadius:strokeRadius]; +#endif + [path closePath]; + + path.lineWidth = borderWidth; + [borderColor setStroke]; + [path stroke]; + } + }]; + return image; +} + +- (nullable UIImage *)sd_rotatedImageWithAngle:(CGFloat)angle fitSize:(BOOL)fitSize { + size_t width = self.size.width; + size_t height = self.size.height; + CGRect newRect = CGRectApplyAffineTransform(CGRectMake(0, 0, width, height), + fitSize ? CGAffineTransformMakeRotation(angle) : CGAffineTransformIdentity); + +#if SD_UIKIT || SD_MAC + // CIImage shortcut + if (self.CIImage) { + CIImage *ciImage = self.CIImage; + if (fitSize) { + CGAffineTransform transform = CGAffineTransformMakeRotation(angle); + ciImage = [ciImage imageByApplyingTransform:transform]; + } else { + CIFilter *filter = [CIFilter filterWithName:@"CIStraightenFilter"]; + [filter setValue:ciImage forKey:kCIInputImageKey]; + [filter setValue:@(angle) forKey:kCIInputAngleKey]; + ciImage = filter.outputImage; + } +#if SD_UIKIT || SD_WATCH + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } +#endif + + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = self.scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:newRect.size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + CGContextSetShouldAntialias(context, true); + CGContextSetAllowsAntialiasing(context, true); + CGContextSetInterpolationQuality(context, kCGInterpolationHigh); + CGContextTranslateCTM(context, +(newRect.size.width * 0.5), +(newRect.size.height * 0.5)); +#if SD_UIKIT || SD_WATCH + // Use UIKit coordinate system counterclockwise (⟲) + CGContextRotateCTM(context, -angle); +#else + CGContextRotateCTM(context, angle); +#endif + + [self drawInRect:CGRectMake(-(width * 0.5), -(height * 0.5), width, height)]; + }]; + return image; +} + +- (nullable UIImage *)sd_flippedImageWithHorizontal:(BOOL)horizontal vertical:(BOOL)vertical { + size_t width = self.size.width; + size_t height = self.size.height; + +#if SD_UIKIT || SD_MAC + // CIImage shortcut + if (self.CIImage) { + CGAffineTransform transform = CGAffineTransformIdentity; + // Use UIKit coordinate system + if (horizontal) { + CGAffineTransform flipHorizontal = CGAffineTransformMake(-1, 0, 0, 1, width, 0); + transform = CGAffineTransformConcat(transform, flipHorizontal); + } + if (vertical) { + CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, height); + transform = CGAffineTransformConcat(transform, flipVertical); + } + CIImage *ciImage = [self.CIImage imageByApplyingTransform:transform]; +#if SD_UIKIT + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } +#endif + + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = self.scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:self.size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + // Use UIKit coordinate system + if (horizontal) { + CGAffineTransform flipHorizontal = CGAffineTransformMake(-1, 0, 0, 1, width, 0); + CGContextConcatCTM(context, flipHorizontal); + } + if (vertical) { + CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, height); + CGContextConcatCTM(context, flipVertical); + } + [self drawInRect:CGRectMake(0, 0, width, height)]; + }]; + return image; +} + +#pragma mark - Image Blending + +- (nullable UIImage *)sd_tintedImageWithColor:(nonnull UIColor *)tintColor { + BOOL hasTint = CGColorGetAlpha(tintColor.CGColor) > __FLT_EPSILON__; + if (!hasTint) { + return self; + } + +#if SD_UIKIT || SD_MAC + // CIImage shortcut + if (self.CIImage) { + CIImage *ciImage = self.CIImage; + CIImage *colorImage = [CIImage imageWithColor:[[CIColor alloc] initWithColor:tintColor]]; + colorImage = [colorImage imageByCroppingToRect:ciImage.extent]; + CIFilter *filter = [CIFilter filterWithName:@"CISourceAtopCompositing"]; + [filter setValue:colorImage forKey:kCIInputImageKey]; + [filter setValue:ciImage forKey:kCIInputBackgroundImageKey]; + ciImage = filter.outputImage; +#if SD_UIKIT + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } +#endif + + CGSize size = self.size; + CGRect rect = { CGPointZero, size }; + CGFloat scale = self.scale; + + // blend mode, see https://en.wikipedia.org/wiki/Alpha_compositing + CGBlendMode blendMode = kCGBlendModeSourceAtop; + + SDGraphicsImageRendererFormat *format = [[SDGraphicsImageRendererFormat alloc] init]; + format.scale = scale; + SDGraphicsImageRenderer *renderer = [[SDGraphicsImageRenderer alloc] initWithSize:size format:format]; + UIImage *image = [renderer imageWithActions:^(CGContextRef _Nonnull context) { + [self drawInRect:rect]; + CGContextSetBlendMode(context, blendMode); + CGContextSetFillColorWithColor(context, tintColor.CGColor); + CGContextFillRect(context, rect); + }]; + return image; +} + +- (nullable UIColor *)sd_colorAtPoint:(CGPoint)point { + CGImageRef imageRef = NULL; + // CIImage compatible +#if SD_UIKIT || SD_MAC + if (self.CIImage) { + imageRef = SDCreateCGImageFromCIImage(self.CIImage); + } +#endif + if (!imageRef) { + imageRef = self.CGImage; + CGImageRetain(imageRef); + } + if (!imageRef) { + return nil; + } + + // Check point + CGFloat width = CGImageGetWidth(imageRef); + CGFloat height = CGImageGetHeight(imageRef); + if (point.x < 0 || point.y < 0 || point.x >= width || point.y >= height) { + CGImageRelease(imageRef); + return nil; + } + + // Get pixels + CGDataProviderRef provider = CGImageGetDataProvider(imageRef); + if (!provider) { + CGImageRelease(imageRef); + return nil; + } + CFDataRef data = CGDataProviderCopyData(provider); + if (!data) { + CGImageRelease(imageRef); + return nil; + } + + // Get pixel at point + size_t bytesPerRow = CGImageGetBytesPerRow(imageRef); + size_t components = CGImageGetBitsPerPixel(imageRef) / CGImageGetBitsPerComponent(imageRef); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + CFRange range = CFRangeMake(bytesPerRow * point.y + components * point.x, 4); + if (CFDataGetLength(data) < range.location + range.length) { + CFRelease(data); + CGImageRelease(imageRef); + return nil; + } + Pixel_8888 pixel = {0}; + CFDataGetBytes(data, range, pixel); + CFRelease(data); + CGImageRelease(imageRef); + // Convert to color + return SDGetColorFromPixel(pixel, bitmapInfo); +} + +- (nullable NSArray *)sd_colorsWithRect:(CGRect)rect { + CGImageRef imageRef = NULL; + // CIImage compatible +#if SD_UIKIT || SD_MAC + if (self.CIImage) { + imageRef = SDCreateCGImageFromCIImage(self.CIImage); + } +#endif + if (!imageRef) { + imageRef = self.CGImage; + CGImageRetain(imageRef); + } + if (!imageRef) { + return nil; + } + + // Check rect + CGFloat width = CGImageGetWidth(imageRef); + CGFloat height = CGImageGetHeight(imageRef); + if (CGRectGetWidth(rect) <= 0 || CGRectGetHeight(rect) <= 0 || CGRectGetMinX(rect) < 0 || CGRectGetMinY(rect) < 0 || CGRectGetMaxX(rect) > width || CGRectGetMaxY(rect) > height) { + CGImageRelease(imageRef); + return nil; + } + + // Get pixels + CGDataProviderRef provider = CGImageGetDataProvider(imageRef); + if (!provider) { + CGImageRelease(imageRef); + return nil; + } + CFDataRef data = CGDataProviderCopyData(provider); + if (!data) { + CGImageRelease(imageRef); + return nil; + } + + // Get pixels with rect + size_t bytesPerRow = CGImageGetBytesPerRow(imageRef); + size_t components = CGImageGetBitsPerPixel(imageRef) / CGImageGetBitsPerComponent(imageRef); + + size_t start = bytesPerRow * CGRectGetMinY(rect) + components * CGRectGetMinX(rect); + size_t end = bytesPerRow * (CGRectGetMaxY(rect) - 1) + components * CGRectGetMaxX(rect); + if (CFDataGetLength(data) < (CFIndex)end) { + CFRelease(data); + CGImageRelease(imageRef); + return nil; + } + + const UInt8 *pixels = CFDataGetBytePtr(data); + size_t row = CGRectGetMinY(rect); + size_t col = CGRectGetMaxX(rect); + + // Convert to color + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + NSMutableArray *colors = [NSMutableArray arrayWithCapacity:CGRectGetWidth(rect) * CGRectGetHeight(rect)]; + for (size_t index = start; index < end; index += 4) { + if (index >= row * bytesPerRow + col * components) { + // Index beyond the end of current row, go next row + row++; + index = row * bytesPerRow + CGRectGetMinX(rect) * components; + index -= 4; + continue; + } + Pixel_8888 pixel = {pixels[index], pixels[index+1], pixels[index+2], pixels[index+3]}; + UIColor *color = SDGetColorFromPixel(pixel, bitmapInfo); + [colors addObject:color]; + } + CFRelease(data); + CGImageRelease(imageRef); + + return [colors copy]; +} + +#pragma mark - Image Effect + +// We use vImage to do box convolve for performance and support for watchOS. However, you can just use `CIFilter.CIGaussianBlur`. For other blur effect, use any filter in `CICategoryBlur` +- (nullable UIImage *)sd_blurredImageWithRadius:(CGFloat)blurRadius { + if (self.size.width < 1 || self.size.height < 1) { + return nil; + } + BOOL hasBlur = blurRadius > __FLT_EPSILON__; + if (!hasBlur) { + return self; + } + + CGFloat scale = self.scale; + CGFloat inputRadius = blurRadius * scale; +#if SD_UIKIT || SD_MAC + if (self.CIImage) { + CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"]; + [filter setValue:self.CIImage forKey:kCIInputImageKey]; + [filter setValue:@(inputRadius) forKey:kCIInputRadiusKey]; + CIImage *ciImage = filter.outputImage; + ciImage = [ciImage imageByCroppingToRect:CGRectMake(0, 0, self.size.width, self.size.height)]; +#if SD_UIKIT + UIImage *image = [UIImage imageWithCIImage:ciImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCIImage:ciImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + return image; + } +#endif + + CGImageRef imageRef = self.CGImage; + + //convert to BGRA if it isn't + if (CGImageGetBitsPerPixel(imageRef) != 32 || + CGImageGetBitsPerComponent(imageRef) != 8 || + !((CGImageGetBitmapInfo(imageRef) & kCGBitmapAlphaInfoMask))) { + SDGraphicsBeginImageContextWithOptions(self.size, NO, self.scale); + [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)]; + imageRef = SDGraphicsGetImageFromCurrentImageContext().CGImage; + SDGraphicsEndImageContext(); + } + + vImage_Buffer effect = {}, scratch = {}; + vImage_Buffer *input = NULL, *output = NULL; + + vImage_CGImageFormat format = { + .bitsPerComponent = 8, + .bitsPerPixel = 32, + .colorSpace = NULL, + .bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, //requests a BGRA buffer. + .version = 0, + .decode = NULL, + .renderingIntent = kCGRenderingIntentDefault + }; + + vImage_Error err; + err = vImageBuffer_InitWithCGImage(&effect, &format, NULL, imageRef, kvImageNoFlags); + if (err != kvImageNoError) { + NSLog(@"UIImage+Transform error: vImageBuffer_InitWithCGImage returned error code %zi for inputImage: %@", err, self); + return nil; + } + err = vImageBuffer_Init(&scratch, effect.height, effect.width, format.bitsPerPixel, kvImageNoFlags); + if (err != kvImageNoError) { + NSLog(@"UIImage+Transform error: vImageBuffer_Init returned error code %zi for inputImage: %@", err, self); + return nil; + } + + input = &effect; + output = &scratch; + + if (hasBlur) { + // A description of how to compute the box kernel width from the Gaussian + // radius (aka standard deviation) appears in the SVG spec: + // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement + // + // For larger values of 's' (s >= 2.0), an approximation can be used: Three + // successive box-blurs build a piece-wise quadratic convolution kernel, which + // approximates the Gaussian kernel to within roughly 3%. + // + // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) + // + // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. + // + if (inputRadius - 2.0 < __FLT_EPSILON__) inputRadius = 2.0; + uint32_t radius = floor(inputRadius * 3.0 * sqrt(2 * M_PI) / 4 + 0.5); + radius |= 1; // force radius to be odd so that the three box-blur methodology works. + int iterations; + if (blurRadius * scale < 0.5) iterations = 1; + else if (blurRadius * scale < 1.5) iterations = 2; + else iterations = 3; + NSInteger tempSize = vImageBoxConvolve_ARGB8888(input, output, NULL, 0, 0, radius, radius, NULL, kvImageGetTempBufferSize | kvImageEdgeExtend); + void *temp = malloc(tempSize); + for (int i = 0; i < iterations; i++) { + vImageBoxConvolve_ARGB8888(input, output, temp, 0, 0, radius, radius, NULL, kvImageEdgeExtend); + vImage_Buffer *tmp = input; + input = output; + output = tmp; + } + free(temp); + } + + CGImageRef effectCGImage = NULL; + effectCGImage = vImageCreateCGImageFromBuffer(input, &format, NULL, NULL, kvImageNoAllocate, NULL); + if (effectCGImage == NULL) { + effectCGImage = vImageCreateCGImageFromBuffer(input, &format, NULL, NULL, kvImageNoFlags, NULL); + free(input->data); + } + free(output->data); +#if SD_UIKIT || SD_WATCH + UIImage *outputImage = [UIImage imageWithCGImage:effectCGImage scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *outputImage = [[UIImage alloc] initWithCGImage:effectCGImage scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + CGImageRelease(effectCGImage); + + return outputImage; +} + +#if SD_UIKIT || SD_MAC +- (nullable UIImage *)sd_filteredImageWithFilter:(nonnull CIFilter *)filter { + CIImage *inputImage; + if (self.CIImage) { + inputImage = self.CIImage; + } else { + CGImageRef imageRef = self.CGImage; + if (!imageRef) { + return nil; + } + inputImage = [CIImage imageWithCGImage:imageRef]; + } + if (!inputImage) return nil; + + CIContext *context = [CIContext context]; + [filter setValue:inputImage forKey:kCIInputImageKey]; + CIImage *outputImage = filter.outputImage; + if (!outputImage) return nil; + + CGImageRef imageRef = [context createCGImage:outputImage fromRect:outputImage.extent]; + if (!imageRef) return nil; + +#if SD_UIKIT + UIImage *image = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation]; +#else + UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:self.scale orientation:kCGImagePropertyOrientationUp]; +#endif + CGImageRelease(imageRef); + + return image; +} +#endif + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.h new file mode 100644 index 0000000..6cd3ba6 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.h @@ -0,0 +1,129 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_UIKIT + +#import "SDWebImageManager.h" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state. + */ +@interface UIImageView (HighlightedWebCache) + +/** + * Set the imageView `highlightedImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `highlightedImage` with an `url` and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `highlightedImage` with an `url`, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the imageView `highlightedImage` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `highlightedImage` with an `url` and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `highlightedImage` with an `url` and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `highlightedImage` with an `url`, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.m new file mode 100644 index 0000000..96c09c1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+HighlightedWebCache.m @@ -0,0 +1,76 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImageView+HighlightedWebCache.h" + +#if SD_UIKIT + +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCache.h" +#import "SDInternalMacros.h" + +static NSString * const SDHighlightedImageOperationKey = @"UIImageViewImageOperationHighlighted"; + +@implementation UIImageView (HighlightedWebCache) + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url { + [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options { + [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setHighlightedImageWithURL:url options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setHighlightedImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + @weakify(self); + SDWebImageMutableContext *mutableContext; + if (context) { + mutableContext = [context mutableCopy]; + } else { + mutableContext = [NSMutableDictionary dictionary]; + } + mutableContext[SDWebImageContextSetImageOperationKey] = SDHighlightedImageOperationKey; + [self sd_internalSetImageWithURL:url + placeholderImage:nil + options:options + context:mutableContext + setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) { + @strongify(self); + self.highlightedImage = image; + } + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.h new file mode 100644 index 0000000..626de9d --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.h @@ -0,0 +1,194 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageManager.h" + +/** + * Usage with a UITableViewCell sub-class: + * + * @code + +#import + +... + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + static NSString *MyIdentifier = @"MyIdentifier"; + + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; + + if (cell == nil) { + cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]; + } + + // Here we use the provided sd_setImageWithURL:placeholderImage: method to load the web image + // Ensure you use a placeholder image otherwise cells will be initialized with no image + [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] + placeholderImage:[UIImage imageNamed:@"placeholder"]]; + + cell.textLabel.text = @"My Text"; + return cell; +} + + * @endcode + */ + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIImageView. + */ +@interface UIImageView (WebCache) + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url` and a placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @see sd_setImageWithURL:placeholderImage:options: + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context; + +/** + * Set the imageView `image` with an `url`. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder and custom options. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url`, placeholder, custom options and context. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. This block has no return value + * and takes the requested UIImage as first parameter. In case of error the image parameter + * is nil and the second parameter may contain an NSError. The third parameter is a Boolean + * indicating if the image was retrieved from the local cache or from the network. + * The fourth parameter is the original image url. + */ +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.m new file mode 100644 index 0000000..9d7f18e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIImageView+WebCache.m @@ -0,0 +1,67 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIImageView+WebCache.h" +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" +#import "UIView+WebCache.h" + +@implementation UIImageView (WebCache) + +- (void)sd_setImageWithURL:(nullable NSURL *)url { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options context:(nullable SDWebImageContext *)context { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:context progress:nil completed:nil]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_setImageWithURL:url placeholderImage:placeholder options:options context:nil progress:progressBlock completed:completedBlock]; +} + +- (void)sd_setImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + context:context + setImageBlock:nil + progress:progressBlock + completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) { + if (completedBlock) { + completedBlock(image, error, cacheType, imageURL); + } + }]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.h new file mode 100644 index 0000000..d0a7966 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.h @@ -0,0 +1,101 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDWebImageManager.h" +#import "SDWebImageTransition.h" +#import "SDWebImageIndicator.h" + +/** + The value specify that the image progress unit count cannot be determined because the progressBlock is not been called. + */ +FOUNDATION_EXPORT const int64_t SDWebImageProgressUnitCountUnknown; /* 1LL */ + +typedef void(^SDSetImageBlock)(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL); + +/** + Integrates SDWebImage async downloading and caching of remote images with UIView subclass. + */ +@interface UIView (WebCache) + +/** + * Get the current image URL. + * + * @note Note that because of the limitations of categories this property can get out of sync if you use setImage: directly. + */ +@property (nonatomic, strong, readonly, nullable) NSURL *sd_imageURL; + +/** + * The current image loading progress associated to the view. The unit count is the received size and excepted size of download. + * The `totalUnitCount` and `completedUnitCount` will be reset to 0 after a new image loading start (change from current queue). And they will be set to `SDWebImageProgressUnitCountUnknown` if the progressBlock not been called but the image loading success to mark the progress finished (change from main queue). + * @note You can use Key-Value Observing on the progress, but you should take care that the change to progress is from a background queue during download(the same as progressBlock). If you want to using KVO and update the UI, make sure to dispatch on the main queue. And it's recommand to use some KVO libs like KVOController because it's more safe and easy to use. + * @note The getter will create a progress instance if the value is nil. But by default, we don't create one. If you need to use Key-Value Observing, you must trigger the getter or set a custom progresss instance before the loading start. The default value is nil. + * @note Note that because of the limitations of categories this property can get out of sync if you update the progress directly. + */ +@property (nonatomic, strong, null_resettable) NSProgress *sd_imageProgress; + +/** + * Set the imageView `image` with an `url` and optionally a placeholder image. + * + * The download is asynchronous and cached. + * + * @param url The url for the image. + * @param placeholder The image to be set initially, until the image request finishes. + * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. + * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold. + * @param setImageBlock Block used for custom set image code. If not provide, use the built-in set image code (supports `UIImageView/NSImageView` and `UIButton/NSButton` currently) + * @param progressBlock A block called while image is downloading + * @note the progress block is executed on a background queue + * @param completedBlock A block called when operation has been completed. + * This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter. + * In case of error the image parameter is nil and the third parameter may contain an NSError. + * + * The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache + * or from the memory cache or from the network. + * + * The fith parameter normally is always YES. However, if you provide SDWebImageAvoidAutoSetImage with SDWebImageProgressiveLoad options to enable progressive downloading and set the image yourself. This block is thus called repeatedly with a partial image. When image is fully downloaded, the + * block is called a last time with the full image and the last parameter set to YES. + * + * The last parameter is the original image URL + */ +- (void)sd_internalSetImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + setImageBlock:(nullable SDSetImageBlock)setImageBlock + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock; + +/** + * Cancel the current image load + */ +- (void)sd_cancelCurrentImageLoad; + +#if SD_UIKIT || SD_MAC + +#pragma mark - Image Transition + +/** + The image transition when image load finished. See `SDWebImageTransition`. + If you specify nil, do not do transition. Defautls to nil. + */ +@property (nonatomic, strong, nullable) SDWebImageTransition *sd_imageTransition; + +#pragma mark - Image Indicator + +/** + The image indicator during the image loading. If you do not need indicator, specify nil. Defaults to nil + The setter will remove the old indicator view and add new indicator view to current view's subview. + @note Because this is UI related, you should access only from the main queue. + */ +@property (nonatomic, strong, nullable) id sd_imageIndicator; + +#endif + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.m new file mode 100644 index 0000000..311dd1b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCache.m @@ -0,0 +1,357 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIView+WebCache.h" +#import "objc/runtime.h" +#import "UIView+WebCacheOperation.h" +#import "SDWebImageError.h" +#import "SDInternalMacros.h" + +const int64_t SDWebImageProgressUnitCountUnknown = 1LL; + +@implementation UIView (WebCache) + +- (nullable NSURL *)sd_imageURL { + return objc_getAssociatedObject(self, @selector(sd_imageURL)); +} + +- (void)setSd_imageURL:(NSURL * _Nullable)sd_imageURL { + objc_setAssociatedObject(self, @selector(sd_imageURL), sd_imageURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (nullable NSString *)sd_latestOperationKey { + return objc_getAssociatedObject(self, @selector(sd_latestOperationKey)); +} + +- (void)setSd_latestOperationKey:(NSString * _Nullable)sd_latestOperationKey { + objc_setAssociatedObject(self, @selector(sd_latestOperationKey), sd_latestOperationKey, OBJC_ASSOCIATION_COPY_NONATOMIC); +} + +- (NSProgress *)sd_imageProgress { + NSProgress *progress = objc_getAssociatedObject(self, @selector(sd_imageProgress)); + if (!progress) { + progress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + self.sd_imageProgress = progress; + } + return progress; +} + +- (void)setSd_imageProgress:(NSProgress *)sd_imageProgress { + objc_setAssociatedObject(self, @selector(sd_imageProgress), sd_imageProgress, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (void)sd_internalSetImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + context:(nullable SDWebImageContext *)context + setImageBlock:(nullable SDSetImageBlock)setImageBlock + progress:(nullable SDImageLoaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock { + context = [context copy]; // copy to avoid mutable object + NSString *validOperationKey = context[SDWebImageContextSetImageOperationKey]; + if (!validOperationKey) { + validOperationKey = NSStringFromClass([self class]); + } + self.sd_latestOperationKey = validOperationKey; + [self sd_cancelImageLoadOperationWithKey:validOperationKey]; + self.sd_imageURL = url; + + if (!(options & SDWebImageDelayPlaceholder)) { + dispatch_main_async_safe(^{ + [self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock cacheType:SDImageCacheTypeNone imageURL:url]; + }); + } + + if (url) { + // reset the progress + NSProgress *imageProgress = objc_getAssociatedObject(self, @selector(sd_imageProgress)); + if (imageProgress) { + imageProgress.totalUnitCount = 0; + imageProgress.completedUnitCount = 0; + } + +#if SD_UIKIT || SD_MAC + // check and start image indicator + [self sd_startImageIndicator]; + id imageIndicator = self.sd_imageIndicator; +#endif + + SDWebImageManager *manager = context[SDWebImageContextCustomManager]; + if (!manager) { + manager = [SDWebImageManager sharedManager]; + } + + SDImageLoaderProgressBlock combinedProgressBlock = ^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) { + if (imageProgress) { + imageProgress.totalUnitCount = expectedSize; + imageProgress.completedUnitCount = receivedSize; + } +#if SD_UIKIT || SD_MAC + if ([imageIndicator respondsToSelector:@selector(updateIndicatorProgress:)]) { + double progress = 0; + if (expectedSize != 0) { + progress = (double)receivedSize / expectedSize; + } + progress = MAX(MIN(progress, 1), 0); // 0.0 - 1.0 + dispatch_async(dispatch_get_main_queue(), ^{ + [imageIndicator updateIndicatorProgress:progress]; + }); + } +#endif + if (progressBlock) { + progressBlock(receivedSize, expectedSize, targetURL); + } + }; + @weakify(self); + id operation = [manager loadImageWithURL:url options:options context:context progress:combinedProgressBlock completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + @strongify(self); + if (!self) { return; } + // if the progress not been updated, mark it to complete state + if (imageProgress && finished && !error && imageProgress.totalUnitCount == 0 && imageProgress.completedUnitCount == 0) { + imageProgress.totalUnitCount = SDWebImageProgressUnitCountUnknown; + imageProgress.completedUnitCount = SDWebImageProgressUnitCountUnknown; + } + +#if SD_UIKIT || SD_MAC + // check and stop image indicator + if (finished) { + [self sd_stopImageIndicator]; + } +#endif + + BOOL shouldCallCompletedBlock = finished || (options & SDWebImageAvoidAutoSetImage); + BOOL shouldNotSetImage = ((image && (options & SDWebImageAvoidAutoSetImage)) || + (!image && !(options & SDWebImageDelayPlaceholder))); + SDWebImageNoParamsBlock callCompletedBlockClojure = ^{ + if (!self) { return; } + if (!shouldNotSetImage) { + [self sd_setNeedsLayout]; + } + if (completedBlock && shouldCallCompletedBlock) { + completedBlock(image, data, error, cacheType, finished, url); + } + }; + + // case 1a: we got an image, but the SDWebImageAvoidAutoSetImage flag is set + // OR + // case 1b: we got no image and the SDWebImageDelayPlaceholder is not set + if (shouldNotSetImage) { + dispatch_main_async_safe(callCompletedBlockClojure); + return; + } + + UIImage *targetImage = nil; + NSData *targetData = nil; + if (image) { + // case 2a: we got an image and the SDWebImageAvoidAutoSetImage is not set + targetImage = image; + targetData = data; + } else if (options & SDWebImageDelayPlaceholder) { + // case 2b: we got no image and the SDWebImageDelayPlaceholder flag is set + targetImage = placeholder; + targetData = nil; + } + +#if SD_UIKIT || SD_MAC + // check whether we should use the image transition + SDWebImageTransition *transition = nil; + if (finished && (options & SDWebImageForceTransition || cacheType == SDImageCacheTypeNone)) { + transition = self.sd_imageTransition; + } +#endif + dispatch_main_async_safe(^{ +#if SD_UIKIT || SD_MAC + [self sd_setImage:targetImage imageData:targetData basedOnClassOrViaCustomSetImageBlock:setImageBlock transition:transition cacheType:cacheType imageURL:imageURL]; +#else + [self sd_setImage:targetImage imageData:targetData basedOnClassOrViaCustomSetImageBlock:setImageBlock cacheType:cacheType imageURL:imageURL]; +#endif + callCompletedBlockClojure(); + }); + }]; + [self sd_setImageLoadOperation:operation forKey:validOperationKey]; + } else { +#if SD_UIKIT || SD_MAC + [self sd_stopImageIndicator]; +#endif + dispatch_main_async_safe(^{ + if (completedBlock) { + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidURL userInfo:@{NSLocalizedDescriptionKey : @"Image url is nil"}]; + completedBlock(nil, nil, error, SDImageCacheTypeNone, YES, url); + } + }); + } +} + +- (void)sd_cancelCurrentImageLoad { + [self sd_cancelImageLoadOperationWithKey:self.sd_latestOperationKey]; +} + +- (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock cacheType:(SDImageCacheType)cacheType imageURL:(NSURL *)imageURL { +#if SD_UIKIT || SD_MAC + [self sd_setImage:image imageData:imageData basedOnClassOrViaCustomSetImageBlock:setImageBlock transition:nil cacheType:cacheType imageURL:imageURL]; +#else + // watchOS does not support view transition. Simplify the logic + if (setImageBlock) { + setImageBlock(image, imageData, cacheType, imageURL); + } else if ([self isKindOfClass:[UIImageView class]]) { + UIImageView *imageView = (UIImageView *)self; + [imageView setImage:image]; + } +#endif +} + +#if SD_UIKIT || SD_MAC +- (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock transition:(SDWebImageTransition *)transition cacheType:(SDImageCacheType)cacheType imageURL:(NSURL *)imageURL { + UIView *view = self; + SDSetImageBlock finalSetImageBlock; + if (setImageBlock) { + finalSetImageBlock = setImageBlock; + } else if ([view isKindOfClass:[UIImageView class]]) { + UIImageView *imageView = (UIImageView *)view; + finalSetImageBlock = ^(UIImage *setImage, NSData *setImageData, SDImageCacheType setCacheType, NSURL *setImageURL) { + imageView.image = setImage; + }; + } +#if SD_UIKIT + else if ([view isKindOfClass:[UIButton class]]) { + UIButton *button = (UIButton *)view; + finalSetImageBlock = ^(UIImage *setImage, NSData *setImageData, SDImageCacheType setCacheType, NSURL *setImageURL) { + [button setImage:setImage forState:UIControlStateNormal]; + }; + } +#endif +#if SD_MAC + else if ([view isKindOfClass:[NSButton class]]) { + NSButton *button = (NSButton *)view; + finalSetImageBlock = ^(UIImage *setImage, NSData *setImageData, SDImageCacheType setCacheType, NSURL *setImageURL) { + button.image = setImage; + }; + } +#endif + + if (transition) { +#if SD_UIKIT + [UIView transitionWithView:view duration:0 options:0 animations:^{ + // 0 duration to let UIKit render placeholder and prepares block + if (transition.prepares) { + transition.prepares(view, image, imageData, cacheType, imageURL); + } + } completion:^(BOOL finished) { + [UIView transitionWithView:view duration:transition.duration options:transition.animationOptions animations:^{ + if (finalSetImageBlock && !transition.avoidAutoSetImage) { + finalSetImageBlock(image, imageData, cacheType, imageURL); + } + if (transition.animations) { + transition.animations(view, image); + } + } completion:transition.completion]; + }]; +#elif SD_MAC + [NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull prepareContext) { + // 0 duration to let AppKit render placeholder and prepares block + prepareContext.duration = 0; + if (transition.prepares) { + transition.prepares(view, image, imageData, cacheType, imageURL); + } + } completionHandler:^{ + [NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) { + context.duration = transition.duration; + context.timingFunction = transition.timingFunction; + context.allowsImplicitAnimation = SD_OPTIONS_CONTAINS(transition.animationOptions, SDWebImageAnimationOptionAllowsImplicitAnimation); + if (finalSetImageBlock && !transition.avoidAutoSetImage) { + finalSetImageBlock(image, imageData, cacheType, imageURL); + } + if (transition.animations) { + transition.animations(view, image); + } + } completionHandler:^{ + if (transition.completion) { + transition.completion(YES); + } + }]; + }]; +#endif + } else { + if (finalSetImageBlock) { + finalSetImageBlock(image, imageData, cacheType, imageURL); + } + } +} +#endif + +- (void)sd_setNeedsLayout { +#if SD_UIKIT + [self setNeedsLayout]; +#elif SD_MAC + [self setNeedsLayout:YES]; +#elif SD_WATCH + // Do nothing because WatchKit automatically layout the view after property change +#endif +} + +#if SD_UIKIT || SD_MAC + +#pragma mark - Image Transition +- (SDWebImageTransition *)sd_imageTransition { + return objc_getAssociatedObject(self, @selector(sd_imageTransition)); +} + +- (void)setSd_imageTransition:(SDWebImageTransition *)sd_imageTransition { + objc_setAssociatedObject(self, @selector(sd_imageTransition), sd_imageTransition, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - Indicator +- (id)sd_imageIndicator { + return objc_getAssociatedObject(self, @selector(sd_imageIndicator)); +} + +- (void)setSd_imageIndicator:(id)sd_imageIndicator { + // Remove the old indicator view + id previousIndicator = self.sd_imageIndicator; + [previousIndicator.indicatorView removeFromSuperview]; + + objc_setAssociatedObject(self, @selector(sd_imageIndicator), sd_imageIndicator, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + // Add the new indicator view + UIView *view = sd_imageIndicator.indicatorView; + if (CGRectEqualToRect(view.frame, CGRectZero)) { + view.frame = self.bounds; + } + // Center the indicator view +#if SD_MAC + [view setFrameOrigin:CGPointMake(round((NSWidth(self.bounds) - NSWidth(view.frame)) / 2), round((NSHeight(self.bounds) - NSHeight(view.frame)) / 2))]; +#else + view.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)); +#endif + view.hidden = NO; + [self addSubview:view]; +} + +- (void)sd_startImageIndicator { + id imageIndicator = self.sd_imageIndicator; + if (!imageIndicator) { + return; + } + dispatch_main_async_safe(^{ + [imageIndicator startAnimatingIndicator]; + }); +} + +- (void)sd_stopImageIndicator { + id imageIndicator = self.sd_imageIndicator; + if (!imageIndicator) { + return; + } + dispatch_main_async_safe(^{ + [imageIndicator stopAnimatingIndicator]; + }); +} + +#endif + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.h new file mode 100644 index 0000000..3a0eb2a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.h @@ -0,0 +1,48 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" + +/** + These methods are used to support canceling for UIView image loading, it's designed to be used internal but not external. + All the stored operations are weak, so it will be dalloced after image loading finished. If you need to store operations, use your own class to keep a strong reference for them. + */ +@interface UIView (WebCacheOperation) + +/** + * Get the image load operation for key + * + * @param key key for identifying the operations + * @return the image load operation + */ +- (nullable id)sd_imageLoadOperationForKey:(nullable NSString *)key; + +/** + * Set the image load operation (storage in a UIView based weak map table) + * + * @param operation the operation + * @param key key for storing the operation + */ +- (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key; + +/** + * Cancel all operations for the current UIView and key + * + * @param key key for identifying the operations + */ +- (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key; + +/** + * Just remove the operations corresponding to the current UIView and key without cancelling them + * + * @param key key for identifying the operations + */ +- (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.m new file mode 100644 index 0000000..83cec8a --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Core/UIView+WebCacheOperation.m @@ -0,0 +1,84 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIView+WebCacheOperation.h" +#import "objc/runtime.h" + +static char loadOperationKey; + +// key is strong, value is weak because operation instance is retained by SDWebImageManager's runningOperations property +// we should use lock to keep thread-safe because these method may not be acessed from main queue +typedef NSMapTable> SDOperationsDictionary; + +@implementation UIView (WebCacheOperation) + +- (SDOperationsDictionary *)sd_operationDictionary { + @synchronized(self) { + SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); + if (operations) { + return operations; + } + operations = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0]; + objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return operations; + } +} + +- (nullable id)sd_imageLoadOperationForKey:(nullable NSString *)key { + id operation; + if (key) { + SDOperationsDictionary *operationDictionary = [self sd_operationDictionary]; + @synchronized (self) { + operation = [operationDictionary objectForKey:key]; + } + } + return operation; +} + +- (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key { + if (key) { + [self sd_cancelImageLoadOperationWithKey:key]; + if (operation) { + SDOperationsDictionary *operationDictionary = [self sd_operationDictionary]; + @synchronized (self) { + [operationDictionary setObject:operation forKey:key]; + } + } + } +} + +- (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key { + if (key) { + // Cancel in progress downloader from queue + SDOperationsDictionary *operationDictionary = [self sd_operationDictionary]; + id operation; + + @synchronized (self) { + operation = [operationDictionary objectForKey:key]; + } + if (operation) { + if ([operation conformsToProtocol:@protocol(SDWebImageOperation)]) { + [operation cancel]; + } + @synchronized (self) { + [operationDictionary removeObjectForKey:key]; + } + } + } +} + +- (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key { + if (key) { + SDOperationsDictionary *operationDictionary = [self sd_operationDictionary]; + @synchronized (self) { + [operationDictionary removeObjectForKey:key]; + } + } +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+RoundedCorners.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+RoundedCorners.h new file mode 100644 index 0000000..224f259 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+RoundedCorners.h @@ -0,0 +1,24 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +#if SD_MAC + +#import "UIImage+Transform.h" + +@interface NSBezierPath (RoundedCorners) + +/** + Convenience way to create a bezier path with the specify rounding corners on macOS. Same as the one on `UIBezierPath`. + */ ++ (nonnull instancetype)sd_bezierPathWithRoundedRect:(NSRect)rect byRoundingCorners:(SDRectCorner)corners cornerRadius:(CGFloat)cornerRadius; + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+RoundedCorners.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+RoundedCorners.m new file mode 100644 index 0000000..d217bf1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/NSBezierPath+RoundedCorners.m @@ -0,0 +1,42 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "NSBezierPath+RoundedCorners.h" + +#if SD_MAC + +@implementation NSBezierPath (RoundedCorners) + ++ (instancetype)sd_bezierPathWithRoundedRect:(NSRect)rect byRoundingCorners:(SDRectCorner)corners cornerRadius:(CGFloat)cornerRadius { + NSBezierPath *path = [NSBezierPath bezierPath]; + + CGFloat maxCorner = MIN(NSWidth(rect), NSHeight(rect)) / 2; + + CGFloat topLeftRadius = MIN(maxCorner, (corners & SDRectCornerTopLeft) ? cornerRadius : 0); + CGFloat topRightRadius = MIN(maxCorner, (corners & SDRectCornerTopRight) ? cornerRadius : 0); + CGFloat bottomLeftRadius = MIN(maxCorner, (corners & SDRectCornerBottomLeft) ? cornerRadius : 0); + CGFloat bottomRightRadius = MIN(maxCorner, (corners & SDRectCornerBottomRight) ? cornerRadius : 0); + + NSPoint topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect)); + NSPoint topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect)); + NSPoint bottomLeft = NSMakePoint(NSMinX(rect), NSMinY(rect)); + NSPoint bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect)); + + [path moveToPoint:NSMakePoint(NSMidX(rect), NSMaxY(rect))]; + [path appendBezierPathWithArcFromPoint:topLeft toPoint:bottomLeft radius:topLeftRadius]; + [path appendBezierPathWithArcFromPoint:bottomLeft toPoint:bottomRight radius:bottomLeftRadius]; + [path appendBezierPathWithArcFromPoint:bottomRight toPoint:topRight radius:bottomRightRadius]; + [path appendBezierPathWithArcFromPoint:topRight toPoint:topLeft radius:topRightRadius]; + [path closePath]; + + return path; +} + +@end + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.h new file mode 100644 index 0000000..199cf4f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.h @@ -0,0 +1,14 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDWebImageCompat.h" + +/// Copy the associated object from source image to target image. The associated object including all the category read/write properties. +/// @param source source +/// @param target target +FOUNDATION_EXPORT void SDImageCopyAssociatedObject(UIImage * _Nullable source, UIImage * _Nullable target); diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.m new file mode 100644 index 0000000..a7c7076 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAssociatedObject.m @@ -0,0 +1,27 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDAssociatedObject.h" +#import "UIImage+Metadata.h" +#import "UIImage+ExtendedCacheData.h" +#import "UIImage+MemoryCacheCost.h" +#import "UIImage+ForceDecode.h" + +void SDImageCopyAssociatedObject(UIImage * _Nullable source, UIImage * _Nullable target) { + if (!source || !target) { + return; + } + // Image Metadata + target.sd_isIncremental = source.sd_isIncremental; + target.sd_imageLoopCount = source.sd_imageLoopCount; + target.sd_imageFormat = source.sd_imageFormat; + // Force Decode + target.sd_isDecoded = source.sd_isDecoded; + // Extended Cache Data + target.sd_extendedObject = source.sd_extendedObject; +} diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.h new file mode 100644 index 0000000..ecc68be --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.h @@ -0,0 +1,20 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +@class SDAsyncBlockOperation; +typedef void (^SDAsyncBlock)(SDAsyncBlockOperation * __nonnull asyncOperation); + +@interface SDAsyncBlockOperation : NSOperation + +- (nonnull instancetype)initWithBlock:(nonnull SDAsyncBlock)block; ++ (nonnull instancetype)blockOperationWithBlock:(nonnull SDAsyncBlock)block; +- (void)complete; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.m new file mode 100644 index 0000000..8862ef8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDAsyncBlockOperation.m @@ -0,0 +1,67 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDAsyncBlockOperation.h" + +@interface SDAsyncBlockOperation () + +@property (assign, nonatomic, getter = isExecuting) BOOL executing; +@property (assign, nonatomic, getter = isFinished) BOOL finished; +@property (nonatomic, copy, nonnull) SDAsyncBlock executionBlock; + +@end + +@implementation SDAsyncBlockOperation + +@synthesize executing = _executing; +@synthesize finished = _finished; + +- (nonnull instancetype)initWithBlock:(nonnull SDAsyncBlock)block { + self = [super init]; + if (self) { + self.executionBlock = block; + } + return self; +} + ++ (nonnull instancetype)blockOperationWithBlock:(nonnull SDAsyncBlock)block { + SDAsyncBlockOperation *operation = [[SDAsyncBlockOperation alloc] initWithBlock:block]; + return operation; +} + +- (void)start { + if (self.isCancelled) { + return; + } + + [self willChangeValueForKey:@"isExecuting"]; + self.executing = YES; + [self didChangeValueForKey:@"isExecuting"]; + + if (self.executionBlock) { + self.executionBlock(self); + } else { + [self complete]; + } +} + +- (void)cancel { + [super cancel]; + [self complete]; +} + +- (void)complete { + [self willChangeValueForKey:@"isExecuting"]; + [self willChangeValueForKey:@"isFinished"]; + self.executing = NO; + self.finished = YES; + [self didChangeValueForKey:@"isExecuting"]; + [self didChangeValueForKey:@"isFinished"]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.h new file mode 100644 index 0000000..740fb2e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.h @@ -0,0 +1,17 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" + +@interface SDDeviceHelper : NSObject + ++ (NSUInteger)totalMemory; ++ (NSUInteger)freeMemory; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.m new file mode 100644 index 0000000..83d0229 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDeviceHelper.m @@ -0,0 +1,32 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDDeviceHelper.h" +#import + +@implementation SDDeviceHelper + ++ (NSUInteger)totalMemory { + return (NSUInteger)[[NSProcessInfo processInfo] physicalMemory]; +} + ++ (NSUInteger)freeMemory { + mach_port_t host_port = mach_host_self(); + mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t); + vm_size_t page_size; + vm_statistics_data_t vm_stat; + kern_return_t kern; + + kern = host_page_size(host_port, &page_size); + if (kern != KERN_SUCCESS) return 0; + kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size); + if (kern != KERN_SUCCESS) return 0; + return vm_stat.free_count * page_size; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.h new file mode 100644 index 0000000..60d4e80 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.h @@ -0,0 +1,30 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDWebImageCompat.h" + +// Cross-platform display link wrapper. Do not retain the target +// Use `CADisplayLink` on iOS/tvOS, `CVDisplayLink` on macOS, `NSTimer` on watchOS + +@interface SDDisplayLink : NSObject + +@property (readonly, nonatomic, weak, nullable) id target; +@property (readonly, nonatomic, assign, nonnull) SEL selector; +@property (readonly, nonatomic) CFTimeInterval duration; +@property (readonly, nonatomic) BOOL isRunning; + ++ (nonnull instancetype)displayLinkWithTarget:(nonnull id)target selector:(nonnull SEL)sel; + +- (void)addToRunLoop:(nonnull NSRunLoop *)runloop forMode:(nonnull NSRunLoopMode)mode; +- (void)removeFromRunLoop:(nonnull NSRunLoop *)runloop forMode:(nonnull NSRunLoopMode)mode; + +- (void)start; +- (void)stop; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.m new file mode 100644 index 0000000..8ff0fc1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDDisplayLink.m @@ -0,0 +1,222 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import "SDDisplayLink.h" +#import "SDWeakProxy.h" +#if SD_MAC +#import +#elif SD_IOS || SD_TV +#import +#endif + +#if SD_MAC +static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *inNow, const CVTimeStamp *inOutputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *displayLinkContext); +#endif + +#define kSDDisplayLinkInterval 1.0 / 60 + +@interface SDDisplayLink () + +#if SD_MAC +@property (nonatomic, assign) CVDisplayLinkRef displayLink; +@property (nonatomic, assign) CVTimeStamp outputTime; +@property (nonatomic, copy) NSRunLoopMode runloopMode; +#elif SD_IOS || SD_TV +@property (nonatomic, strong) CADisplayLink *displayLink; +#else +@property (nonatomic, strong) NSTimer *displayLink; +@property (nonatomic, strong) NSRunLoop *runloop; +@property (nonatomic, copy) NSRunLoopMode runloopMode; +@property (nonatomic, assign) NSTimeInterval currentFireDate; +#endif + +@end + +@implementation SDDisplayLink + +- (void)dealloc { +#if SD_MAC + if (_displayLink) { + CVDisplayLinkRelease(_displayLink); + _displayLink = NULL; + } +#elif SD_IOS || SD_TV + [_displayLink invalidate]; + _displayLink = nil; +#else + [_displayLink invalidate]; + _displayLink = nil; +#endif +} + +- (instancetype)initWithTarget:(id)target selector:(SEL)sel { + self = [super init]; + if (self) { + _target = target; + _selector = sel; +#if SD_MAC + CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink); + CVDisplayLinkSetOutputCallback(_displayLink, DisplayLinkCallback, (__bridge void *)self); +#elif SD_IOS || SD_TV + SDWeakProxy *weakProxy = [SDWeakProxy proxyWithTarget:self]; + _displayLink = [CADisplayLink displayLinkWithTarget:weakProxy selector:@selector(displayLinkDidRefresh:)]; +#else + SDWeakProxy *weakProxy = [SDWeakProxy proxyWithTarget:self]; + _displayLink = [NSTimer timerWithTimeInterval:kSDDisplayLinkInterval target:weakProxy selector:@selector(displayLinkDidRefresh:) userInfo:nil repeats:YES]; +#endif + } + return self; +} + ++ (instancetype)displayLinkWithTarget:(id)target selector:(SEL)sel { + SDDisplayLink *displayLink = [[SDDisplayLink alloc] initWithTarget:target selector:sel]; + return displayLink; +} + +- (CFTimeInterval)duration { +#if SD_MAC + CVTimeStamp outputTime = self.outputTime; + NSTimeInterval duration = 0; + double periodPerSecond = (double)outputTime.videoTimeScale * outputTime.rateScalar; + if (periodPerSecond > 0) { + duration = (double)outputTime.videoRefreshPeriod / periodPerSecond; + } +#elif SD_IOS || SD_TV +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + NSTimeInterval duration = self.displayLink.duration * self.displayLink.frameInterval; +#pragma clang diagnostic pop +#else + NSTimeInterval duration = 0; + if (self.displayLink.isValid && self.currentFireDate != 0) { + NSTimeInterval nextFireDate = CFRunLoopTimerGetNextFireDate((__bridge CFRunLoopTimerRef)self.displayLink); + duration = nextFireDate - self.currentFireDate; + } +#endif + if (duration == 0) { + duration = kSDDisplayLinkInterval; + } + return duration; +} + +- (BOOL)isRunning { +#if SD_MAC + return CVDisplayLinkIsRunning(self.displayLink); +#elif SD_IOS || SD_TV + return !self.displayLink.isPaused; +#else + return self.displayLink.isValid; +#endif +} + +- (void)addToRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode { + if (!runloop || !mode) { + return; + } +#if SD_MAC + self.runloopMode = mode; +#elif SD_IOS || SD_TV + [self.displayLink addToRunLoop:runloop forMode:mode]; +#else + self.runloop = runloop; + self.runloopMode = mode; + CFRunLoopMode cfMode; + if ([mode isEqualToString:NSDefaultRunLoopMode]) { + cfMode = kCFRunLoopDefaultMode; + } else if ([mode isEqualToString:NSRunLoopCommonModes]) { + cfMode = kCFRunLoopCommonModes; + } else { + cfMode = (__bridge CFStringRef)mode; + } + CFRunLoopAddTimer(runloop.getCFRunLoop, (__bridge CFRunLoopTimerRef)self.displayLink, cfMode); +#endif +} + +- (void)removeFromRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode { + if (!runloop || !mode) { + return; + } +#if SD_MAC + self.runloopMode = nil; +#elif SD_IOS || SD_TV + [self.displayLink removeFromRunLoop:runloop forMode:mode]; +#else + self.runloop = nil; + self.runloopMode = nil; + CFRunLoopMode cfMode; + if ([mode isEqualToString:NSDefaultRunLoopMode]) { + cfMode = kCFRunLoopDefaultMode; + } else if ([mode isEqualToString:NSRunLoopCommonModes]) { + cfMode = kCFRunLoopCommonModes; + } else { + cfMode = (__bridge CFStringRef)mode; + } + CFRunLoopRemoveTimer(runloop.getCFRunLoop, (__bridge CFRunLoopTimerRef)self.displayLink, cfMode); +#endif +} + +- (void)start { +#if SD_MAC + CVDisplayLinkStart(self.displayLink); +#elif SD_IOS || SD_TV + self.displayLink.paused = NO; +#else + if (self.displayLink.isValid) { + [self.displayLink fire]; + } else { + SDWeakProxy *weakProxy = [SDWeakProxy proxyWithTarget:self]; + self.displayLink = [NSTimer timerWithTimeInterval:kSDDisplayLinkInterval target:weakProxy selector:@selector(displayLinkDidRefresh:) userInfo:nil repeats:YES]; + [self addToRunLoop:self.runloop forMode:self.runloopMode]; + } +#endif +} + +- (void)stop { +#if SD_MAC + CVDisplayLinkStop(self.displayLink); +#elif SD_IOS || SD_TV + self.displayLink.paused = YES; +#else + [self.displayLink invalidate]; +#endif +} + +- (void)displayLinkDidRefresh:(id)displayLink { +#if SD_MAC + // CVDisplayLink does not use runloop, but we can provide similar behavior for modes + // May use `default` runloop to avoid extra callback when in `eventTracking` (mouse drag, scroll) or `modalPanel` (modal panel) + NSString *runloopMode = self.runloopMode; + if (![runloopMode isEqualToString:NSRunLoopCommonModes] && ![runloopMode isEqualToString:NSRunLoop.mainRunLoop.currentMode]) { + return; + } +#endif +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + [_target performSelector:_selector withObject:self]; +#pragma clang diagnostic pop +#if SD_WATCH + self.currentFireDate = CFRunLoopTimerGetNextFireDate((__bridge CFRunLoopTimerRef)self.displayLink); +#endif +} + +@end + +#if SD_MAC +static CVReturn DisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp *inNow, const CVTimeStamp *inOutputTime, CVOptionFlags flagsIn, CVOptionFlags *flagsOut, void *displayLinkContext) { + // CVDisplayLink callback is not on main queue + SDDisplayLink *object = (__bridge SDDisplayLink *)displayLinkContext; + if (inOutputTime) { + object.outputTime = *inOutputTime; + } + __weak SDDisplayLink *weakObject = object; + dispatch_async(dispatch_get_main_queue(), ^{ + [weakObject displayLinkDidRefresh:(__bridge id)(displayLink)]; + }); + return kCVReturnSuccess; +} +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.h new file mode 100644 index 0000000..1e66ded --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.h @@ -0,0 +1,18 @@ +// +// This file is from https://gist.github.com/zydeco/6292773 +// +// Created by Jesús A. Álvarez on 2008-12-17. +// Copyright 2008-2009 namedfork.net. All rights reserved. +// + +#import + +@interface SDFileAttributeHelper : NSObject + ++ (NSArray*)extendedAttributeNamesAtPath:(NSString*)path traverseLink:(BOOL)follow error:(NSError**)err; ++ (BOOL)hasExtendedAttribute:(NSString*)name atPath:(NSString*)path traverseLink:(BOOL)follow error:(NSError**)err; ++ (NSData*)extendedAttribute:(NSString*)name atPath:(NSString*)path traverseLink:(BOOL)follow error:(NSError**)err; ++ (BOOL)setExtendedAttribute:(NSString*)name value:(NSData*)value atPath:(NSString*)path traverseLink:(BOOL)follow overwrite:(BOOL)overwrite error:(NSError**)err; ++ (BOOL)removeExtendedAttribute:(NSString*)name atPath:(NSString*)path traverseLink:(BOOL)follow error:(NSError**)err; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.m new file mode 100644 index 0000000..fcb8ad4 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDFileAttributeHelper.m @@ -0,0 +1,127 @@ +// +// This file is from https://gist.github.com/zydeco/6292773 +// +// Created by Jesús A. Álvarez on 2008-12-17. +// Copyright 2008-2009 namedfork.net. All rights reserved. +// + +#import "SDFileAttributeHelper.h" +#import + +@implementation SDFileAttributeHelper + ++ (NSArray*)extendedAttributeNamesAtPath:(NSString*)path traverseLink:(BOOL)follow error:(NSError**)err { + int flags = follow? 0 : XATTR_NOFOLLOW; + + // get size of name list + ssize_t nameBuffLen = listxattr([path fileSystemRepresentation], NULL, 0, flags); + if (nameBuffLen == -1) { + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + [NSString stringWithUTF8String:strerror(errno)], @"error", + @"listxattr", @"function", + path, @":path", + [NSNumber numberWithBool:follow], @":traverseLink", + nil] + ]; + return nil; + } else if (nameBuffLen == 0) return [NSArray array]; + + // get name list + NSMutableData *nameBuff = [NSMutableData dataWithLength:nameBuffLen]; + listxattr([path fileSystemRepresentation], [nameBuff mutableBytes], nameBuffLen, flags); + + // convert to array + NSMutableArray * names = [NSMutableArray arrayWithCapacity:5]; + char *nextName, *endOfNames = [nameBuff mutableBytes] + nameBuffLen; + for(nextName = [nameBuff mutableBytes]; nextName < endOfNames; nextName += 1+strlen(nextName)) + [names addObject:[NSString stringWithUTF8String:nextName]]; + return [NSArray arrayWithArray:names]; +} + ++ (BOOL)hasExtendedAttribute:(NSString*)name atPath:(NSString*)path traverseLink:(BOOL)follow error:(NSError**)err { + int flags = follow? 0 : XATTR_NOFOLLOW; + + // get size of name list + ssize_t nameBuffLen = listxattr([path fileSystemRepresentation], NULL, 0, flags); + if (nameBuffLen == -1) { + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + [NSString stringWithUTF8String:strerror(errno)], @"error", + @"listxattr", @"function", + path, @":path", + [NSNumber numberWithBool:follow], @":traverseLink", + nil] + ]; + return NO; + } else if (nameBuffLen == 0) return NO; + + // get name list + NSMutableData *nameBuff = [NSMutableData dataWithLength:nameBuffLen]; + listxattr([path fileSystemRepresentation], [nameBuff mutableBytes], nameBuffLen, flags); + + // find our name + char *nextName, *endOfNames = [nameBuff mutableBytes] + nameBuffLen; + for(nextName = [nameBuff mutableBytes]; nextName < endOfNames; nextName += 1+strlen(nextName)) + if (strcmp(nextName, [name UTF8String]) == 0) return YES; + return NO; +} + ++ (NSData*)extendedAttribute:(NSString*)name atPath:(NSString*)path traverseLink:(BOOL)follow error:(NSError**)err { + int flags = follow? 0 : XATTR_NOFOLLOW; + // get length + ssize_t attrLen = getxattr([path fileSystemRepresentation], [name UTF8String], NULL, 0, 0, flags); + if (attrLen == -1) { + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + [NSString stringWithUTF8String:strerror(errno)], @"error", + @"getxattr", @"function", + name, @":name", + path, @":path", + [NSNumber numberWithBool:follow], @":traverseLink", + nil] + ]; + return nil; + } + + // get attribute data + NSMutableData * attrData = [NSMutableData dataWithLength:attrLen]; + getxattr([path fileSystemRepresentation], [name UTF8String], [attrData mutableBytes], attrLen, 0, flags); + return attrData; +} + ++ (BOOL)setExtendedAttribute:(NSString*)name value:(NSData*)value atPath:(NSString*)path traverseLink:(BOOL)follow overwrite:(BOOL)overwrite error:(NSError**)err { + int flags = (follow? 0 : XATTR_NOFOLLOW) | (overwrite? 0 : XATTR_CREATE); + if (0 == setxattr([path fileSystemRepresentation], [name UTF8String], [value bytes], [value length], 0, flags)) return YES; + // error + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + [NSString stringWithUTF8String:strerror(errno)], @"error", + @"setxattr", @"function", + name, @":name", + [NSNumber numberWithUnsignedInteger:[value length]], @":value.length", + path, @":path", + [NSNumber numberWithBool:follow], @":traverseLink", + [NSNumber numberWithBool:overwrite], @":overwrite", + nil] + ]; + return NO; +} + ++ (BOOL)removeExtendedAttribute:(NSString*)name atPath:(NSString*)path traverseLink:(BOOL)follow error:(NSError**)err { + int flags = (follow? 0 : XATTR_NOFOLLOW); + if (0 == removexattr([path fileSystemRepresentation], [name UTF8String], flags)) return YES; + // error + if (err) *err = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + [NSString stringWithUTF8String:strerror(errno)], @"error", + @"removexattr", @"function", + name, @":name", + path, @":path", + [NSNumber numberWithBool:follow], @":traverseLink", + nil] + ]; + return NO; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.h new file mode 100644 index 0000000..6818418 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.h @@ -0,0 +1,23 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +// Apple parse the Asset Catalog compiled file(`Assets.car`) by CoreUI.framework, however it's a private framework and there are no other ways to directly get the data. So we just process the normal bundle files :) + +@interface SDImageAssetManager : NSObject + +@property (nonatomic, strong, nonnull) NSMapTable *imageTable; + ++ (nonnull instancetype)sharedAssetManager; +- (nullable NSString *)getPathForName:(nonnull NSString *)name bundle:(nonnull NSBundle *)bundle preferredScale:(nonnull CGFloat *)scale; +- (nullable UIImage *)imageForName:(nonnull NSString *)name; +- (void)storeImage:(nonnull UIImage *)image forName:(nonnull NSString *)name; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.m new file mode 100644 index 0000000..fa92e74 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageAssetManager.m @@ -0,0 +1,158 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageAssetManager.h" +#import "SDInternalMacros.h" + +static NSArray *SDBundlePreferredScales() { + static NSArray *scales; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ +#if SD_WATCH + CGFloat screenScale = [WKInterfaceDevice currentDevice].screenScale; +#elif SD_UIKIT + CGFloat screenScale = [UIScreen mainScreen].scale; +#elif SD_MAC + CGFloat screenScale = [NSScreen mainScreen].backingScaleFactor; +#endif + if (screenScale <= 1) { + scales = @[@1,@2,@3]; + } else if (screenScale <= 2) { + scales = @[@2,@3,@1]; + } else { + scales = @[@3,@2,@1]; + } + }); + return scales; +} + +@implementation SDImageAssetManager { + dispatch_semaphore_t _lock; +} + ++ (instancetype)sharedAssetManager { + static dispatch_once_t onceToken; + static SDImageAssetManager *assetManager; + dispatch_once(&onceToken, ^{ + assetManager = [[SDImageAssetManager alloc] init]; + }); + return assetManager; +} + +- (instancetype)init { + self = [super init]; + if (self) { + NSPointerFunctionsOptions valueOptions; +#if SD_MAC + // Apple says that NSImage use a weak reference to value + valueOptions = NSPointerFunctionsWeakMemory; +#else + // Apple says that UIImage use a strong reference to value + valueOptions = NSPointerFunctionsStrongMemory; +#endif + _imageTable = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsCopyIn valueOptions:valueOptions]; + _lock = dispatch_semaphore_create(1); +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif + } + return self; +} + +- (void)dealloc { +#if SD_UIKIT + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +#endif +} + +- (void)didReceiveMemoryWarning:(NSNotification *)notification { + SD_LOCK(_lock); + [self.imageTable removeAllObjects]; + SD_UNLOCK(_lock); +} + +- (NSString *)getPathForName:(NSString *)name bundle:(NSBundle *)bundle preferredScale:(CGFloat *)scale { + NSParameterAssert(name); + NSParameterAssert(bundle); + NSString *path; + if (name.length == 0) { + return path; + } + if ([name hasSuffix:@"/"]) { + return path; + } + NSString *extension = name.pathExtension; + if (extension.length == 0) { + // If no extension, follow Apple's doc, check PNG format + extension = @"png"; + } + name = [name stringByDeletingPathExtension]; + + CGFloat providedScale = *scale; + NSArray *scales = SDBundlePreferredScales(); + + // Check if file name contains scale + for (size_t i = 0; i < scales.count; i++) { + NSNumber *scaleValue = scales[i]; + if ([name hasSuffix:[NSString stringWithFormat:@"@%@x", scaleValue]]) { + path = [bundle pathForResource:name ofType:extension]; + if (path) { + *scale = scaleValue.doubleValue; // override + return path; + } + } + } + + // Search with provided scale first + if (providedScale != 0) { + NSString *scaledName = [name stringByAppendingFormat:@"@%@x", @(providedScale)]; + path = [bundle pathForResource:scaledName ofType:extension]; + if (path) { + return path; + } + } + + // Search with preferred scale + for (size_t i = 0; i < scales.count; i++) { + NSNumber *scaleValue = scales[i]; + if (scaleValue.doubleValue == providedScale) { + // Ignore provided scale + continue; + } + NSString *scaledName = [name stringByAppendingFormat:@"@%@x", scaleValue]; + path = [bundle pathForResource:scaledName ofType:extension]; + if (path) { + *scale = scaleValue.doubleValue; // override + return path; + } + } + + // Search without scale + path = [bundle pathForResource:name ofType:extension]; + + return path; +} + +- (UIImage *)imageForName:(NSString *)name { + NSParameterAssert(name); + UIImage *image; + SD_LOCK(_lock); + image = [self.imageTable objectForKey:name]; + SD_UNLOCK(_lock); + return image; +} + +- (void)storeImage:(UIImage *)image forName:(NSString *)name { + NSParameterAssert(image); + NSParameterAssert(name); + SD_LOCK(_lock); + [self.imageTable setObject:image forKey:name]; + SD_UNLOCK(_lock); +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.h new file mode 100644 index 0000000..fddf78c --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.h @@ -0,0 +1,21 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +// This is used for operation management, but not for operation queue execute +@interface SDImageCachesManagerOperation : NSOperation + +@property (nonatomic, assign, readonly) NSUInteger pendingCount; + +- (void)beginWithTotalCount:(NSUInteger)totalCount; +- (void)completeOne; +- (void)done; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.m new file mode 100644 index 0000000..1a1ae69 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageCachesManagerOperation.m @@ -0,0 +1,84 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDImageCachesManagerOperation.h" +#import "SDInternalMacros.h" + +@implementation SDImageCachesManagerOperation +{ + dispatch_semaphore_t _pendingCountLock; +} + +@synthesize executing = _executing; +@synthesize finished = _finished; +@synthesize cancelled = _cancelled; +@synthesize pendingCount = _pendingCount; + +- (instancetype)init { + if (self = [super init]) { + _pendingCountLock = dispatch_semaphore_create(1); + _pendingCount = 0; + } + return self; +} + +- (void)beginWithTotalCount:(NSUInteger)totalCount { + self.executing = YES; + self.finished = NO; + _pendingCount = totalCount; +} + +- (NSUInteger)pendingCount { + SD_LOCK(_pendingCountLock); + NSUInteger pendingCount = _pendingCount; + SD_UNLOCK(_pendingCountLock); + return pendingCount; +} + +- (void)completeOne { + SD_LOCK(_pendingCountLock); + _pendingCount = _pendingCount > 0 ? _pendingCount - 1 : 0; + SD_UNLOCK(_pendingCountLock); +} + +- (void)cancel { + self.cancelled = YES; + [self reset]; +} + +- (void)done { + self.finished = YES; + self.executing = NO; + [self reset]; +} + +- (void)reset { + SD_LOCK(_pendingCountLock); + _pendingCount = 0; + SD_UNLOCK(_pendingCountLock); +} + +- (void)setFinished:(BOOL)finished { + [self willChangeValueForKey:@"isFinished"]; + _finished = finished; + [self didChangeValueForKey:@"isFinished"]; +} + +- (void)setExecuting:(BOOL)executing { + [self willChangeValueForKey:@"isExecuting"]; + _executing = executing; + [self didChangeValueForKey:@"isExecuting"]; +} + +- (void)setCancelled:(BOOL)cancelled { + [self willChangeValueForKey:@"isCancelled"]; + _cancelled = cancelled; + [self didChangeValueForKey:@"isCancelled"]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageHEICCoderInternal.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageHEICCoderInternal.h new file mode 100644 index 0000000..e7017bb --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageHEICCoderInternal.h @@ -0,0 +1,25 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDImageHEICCoder.h" + +// AVFileTypeHEIC/AVFileTypeHEIF is defined in AVFoundation via iOS 11, we use this without import AVFoundation +#define kSDUTTypeHEIC ((__bridge CFStringRef)@"public.heic") +#define kSDUTTypeHEIF ((__bridge CFStringRef)@"public.heif") +// HEIC Sequence (Animated Image) +#define kSDUTTypeHEICS ((__bridge CFStringRef)@"public.heics") + +@interface SDImageHEICCoder () + ++ (BOOL)canDecodeFromHEICFormat; ++ (BOOL)canDecodeFromHEIFFormat; ++ (BOOL)canEncodeToHEICFormat; ++ (BOOL)canEncodeToHEIFFormat; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageIOAnimatedCoderInternal.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageIOAnimatedCoderInternal.h new file mode 100644 index 0000000..f2976ea --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDImageIOAnimatedCoderInternal.h @@ -0,0 +1,18 @@ +/* +* This file is part of the SDWebImage package. +* (c) Olivier Poitrey +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +#import +#import "SDImageIOAnimatedCoder.h" + +@interface SDImageIOAnimatedCoder () + ++ (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index source:(nonnull CGImageSourceRef)source; ++ (NSUInteger)imageLoopCountWithSource:(nonnull CGImageSourceRef)source; ++ (nullable UIImage *)createFrameAtIndex:(NSUInteger)index source:(nonnull CGImageSourceRef)source scale:(CGFloat)scale preserveAspectRatio:(BOOL)preserveAspectRatio thumbnailSize:(CGSize)thumbnailSize; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.h new file mode 100644 index 0000000..837d77b --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.h @@ -0,0 +1,65 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDmetamacros.h" + +#ifndef SD_LOCK +#define SD_LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); +#endif + +#ifndef SD_UNLOCK +#define SD_UNLOCK(lock) dispatch_semaphore_signal(lock); +#endif + +#ifndef SD_OPTIONS_CONTAINS +#define SD_OPTIONS_CONTAINS(options, value) (((options) & (value)) == (value)) +#endif + +#ifndef weakify +#define weakify(...) \ +sd_keywordify \ +metamacro_foreach_cxt(sd_weakify_,, __weak, __VA_ARGS__) +#endif + +#ifndef strongify +#define strongify(...) \ +sd_keywordify \ +_Pragma("clang diagnostic push") \ +_Pragma("clang diagnostic ignored \"-Wshadow\"") \ +metamacro_foreach(sd_strongify_,, __VA_ARGS__) \ +_Pragma("clang diagnostic pop") +#endif + +#define sd_weakify_(INDEX, CONTEXT, VAR) \ +CONTEXT __typeof__(VAR) metamacro_concat(VAR, _weak_) = (VAR); + +#define sd_strongify_(INDEX, VAR) \ +__strong __typeof__(VAR) VAR = metamacro_concat(VAR, _weak_); + +#if DEBUG +#define sd_keywordify autoreleasepool {} +#else +#define sd_keywordify try {} @catch (...) {} +#endif + +#ifndef onExit +#define onExit \ +sd_keywordify \ +__strong sd_cleanupBlock_t metamacro_concat(sd_exitBlock_, __LINE__) __attribute__((cleanup(sd_executeCleanupBlock), unused)) = ^ +#endif + +typedef void (^sd_cleanupBlock_t)(void); + +#if defined(__cplusplus) +extern "C" { +#endif + void sd_executeCleanupBlock (__strong sd_cleanupBlock_t *block); +#if defined(__cplusplus) +} +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.m new file mode 100644 index 0000000..e4981af --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDInternalMacros.m @@ -0,0 +1,13 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDInternalMacros.h" + +void sd_executeCleanupBlock (__strong sd_cleanupBlock_t *block) { + (*block)(); +} diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.h new file mode 100644 index 0000000..4fd1622 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.h @@ -0,0 +1,19 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import +#import "SDWebImageCompat.h" + +@interface SDWeakProxy : NSProxy + +@property (nonatomic, weak, readonly, nullable) id target; + +- (nonnull instancetype)initWithTarget:(nonnull id)target; ++ (nonnull instancetype)proxyWithTarget:(nonnull id)target; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.m new file mode 100644 index 0000000..19a4593 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDWeakProxy.m @@ -0,0 +1,79 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWeakProxy.h" + +@implementation SDWeakProxy + +- (instancetype)initWithTarget:(id)target { + _target = target; + return self; +} + ++ (instancetype)proxyWithTarget:(id)target { + return [[SDWeakProxy alloc] initWithTarget:target]; +} + +- (id)forwardingTargetForSelector:(SEL)selector { + return _target; +} + +- (void)forwardInvocation:(NSInvocation *)invocation { + void *null = NULL; + [invocation setReturnValue:&null]; +} + +- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { + return [NSObject instanceMethodSignatureForSelector:@selector(init)]; +} + +- (BOOL)respondsToSelector:(SEL)aSelector { + return [_target respondsToSelector:aSelector]; +} + +- (BOOL)isEqual:(id)object { + return [_target isEqual:object]; +} + +- (NSUInteger)hash { + return [_target hash]; +} + +- (Class)superclass { + return [_target superclass]; +} + +- (Class)class { + return [_target class]; +} + +- (BOOL)isKindOfClass:(Class)aClass { + return [_target isKindOfClass:aClass]; +} + +- (BOOL)isMemberOfClass:(Class)aClass { + return [_target isMemberOfClass:aClass]; +} + +- (BOOL)conformsToProtocol:(Protocol *)aProtocol { + return [_target conformsToProtocol:aProtocol]; +} + +- (BOOL)isProxy { + return YES; +} + +- (NSString *)description { + return [_target description]; +} + +- (NSString *)debugDescription { + return [_target debugDescription]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDmetamacros.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDmetamacros.h new file mode 100644 index 0000000..dd90d99 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/SDmetamacros.h @@ -0,0 +1,667 @@ +/** + * Macros for metaprogramming + * ExtendedC + * + * Copyright (C) 2012 Justin Spahr-Summers + * Released under the MIT license + */ + +#ifndef EXTC_METAMACROS_H +#define EXTC_METAMACROS_H + + +/** + * Executes one or more expressions (which may have a void type, such as a call + * to a function that returns no value) and always returns true. + */ +#define metamacro_exprify(...) \ + ((__VA_ARGS__), true) + +/** + * Returns a string representation of VALUE after full macro expansion. + */ +#define metamacro_stringify(VALUE) \ + metamacro_stringify_(VALUE) + +/** + * Returns A and B concatenated after full macro expansion. + */ +#define metamacro_concat(A, B) \ + metamacro_concat_(A, B) + +/** + * Returns the Nth variadic argument (starting from zero). At least + * N + 1 variadic arguments must be given. N must be between zero and twenty, + * inclusive. + */ +#define metamacro_at(N, ...) \ + metamacro_concat(metamacro_at, N)(__VA_ARGS__) + +/** + * Returns the number of arguments (up to twenty) provided to the macro. At + * least one argument must be provided. + * + * Inspired by P99: http://p99.gforge.inria.fr + */ +#define metamacro_argcount(...) \ + metamacro_at(20, __VA_ARGS__, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1) + +/** + * Identical to #metamacro_foreach_cxt, except that no CONTEXT argument is + * given. Only the index and current argument will thus be passed to MACRO. + */ +#define metamacro_foreach(MACRO, SEP, ...) \ + metamacro_foreach_cxt(metamacro_foreach_iter, SEP, MACRO, __VA_ARGS__) + +/** + * For each consecutive variadic argument (up to twenty), MACRO is passed the + * zero-based index of the current argument, CONTEXT, and then the argument + * itself. The results of adjoining invocations of MACRO are then separated by + * SEP. + * + * Inspired by P99: http://p99.gforge.inria.fr + */ +#define metamacro_foreach_cxt(MACRO, SEP, CONTEXT, ...) \ + metamacro_concat(metamacro_foreach_cxt, metamacro_argcount(__VA_ARGS__))(MACRO, SEP, CONTEXT, __VA_ARGS__) + +/** + * Identical to #metamacro_foreach_cxt. This can be used when the former would + * fail due to recursive macro expansion. + */ +#define metamacro_foreach_cxt_recursive(MACRO, SEP, CONTEXT, ...) \ + metamacro_concat(metamacro_foreach_cxt_recursive, metamacro_argcount(__VA_ARGS__))(MACRO, SEP, CONTEXT, __VA_ARGS__) + +/** + * In consecutive order, appends each variadic argument (up to twenty) onto + * BASE. The resulting concatenations are then separated by SEP. + * + * This is primarily useful to manipulate a list of macro invocations into instead + * invoking a different, possibly related macro. + */ +#define metamacro_foreach_concat(BASE, SEP, ...) \ + metamacro_foreach_cxt(metamacro_foreach_concat_iter, SEP, BASE, __VA_ARGS__) + +/** + * Iterates COUNT times, each time invoking MACRO with the current index + * (starting at zero) and CONTEXT. The results of adjoining invocations of MACRO + * are then separated by SEP. + * + * COUNT must be an integer between zero and twenty, inclusive. + */ +#define metamacro_for_cxt(COUNT, MACRO, SEP, CONTEXT) \ + metamacro_concat(metamacro_for_cxt, COUNT)(MACRO, SEP, CONTEXT) + +/** + * Returns the first argument given. At least one argument must be provided. + * + * This is useful when implementing a variadic macro, where you may have only + * one variadic argument, but no way to retrieve it (for example, because \c ... + * always needs to match at least one argument). + * + * @code + +#define varmacro(...) \ + metamacro_head(__VA_ARGS__) + + * @endcode + */ +#define metamacro_head(...) \ + metamacro_head_(__VA_ARGS__, 0) + +/** + * Returns every argument except the first. At least two arguments must be + * provided. + */ +#define metamacro_tail(...) \ + metamacro_tail_(__VA_ARGS__) + +/** + * Returns the first N (up to twenty) variadic arguments as a new argument list. + * At least N variadic arguments must be provided. + */ +#define metamacro_take(N, ...) \ + metamacro_concat(metamacro_take, N)(__VA_ARGS__) + +/** + * Removes the first N (up to twenty) variadic arguments from the given argument + * list. At least N variadic arguments must be provided. + */ +#define metamacro_drop(N, ...) \ + metamacro_concat(metamacro_drop, N)(__VA_ARGS__) + +/** + * Decrements VAL, which must be a number between zero and twenty, inclusive. + * + * This is primarily useful when dealing with indexes and counts in + * metaprogramming. + */ +#define metamacro_dec(VAL) \ + metamacro_at(VAL, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) + +/** + * Increments VAL, which must be a number between zero and twenty, inclusive. + * + * This is primarily useful when dealing with indexes and counts in + * metaprogramming. + */ +#define metamacro_inc(VAL) \ + metamacro_at(VAL, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21) + +/** + * If A is equal to B, the next argument list is expanded; otherwise, the + * argument list after that is expanded. A and B must be numbers between zero + * and twenty, inclusive. Additionally, B must be greater than or equal to A. + * + * @code + +// expands to true +metamacro_if_eq(0, 0)(true)(false) + +// expands to false +metamacro_if_eq(0, 1)(true)(false) + + * @endcode + * + * This is primarily useful when dealing with indexes and counts in + * metaprogramming. + */ +#define metamacro_if_eq(A, B) \ + metamacro_concat(metamacro_if_eq, A)(B) + +/** + * Identical to #metamacro_if_eq. This can be used when the former would fail + * due to recursive macro expansion. + */ +#define metamacro_if_eq_recursive(A, B) \ + metamacro_concat(metamacro_if_eq_recursive, A)(B) + +/** + * Returns 1 if N is an even number, or 0 otherwise. N must be between zero and + * twenty, inclusive. + * + * For the purposes of this test, zero is considered even. + */ +#define metamacro_is_even(N) \ + metamacro_at(N, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1) + +/** + * Returns the logical NOT of B, which must be the number zero or one. + */ +#define metamacro_not(B) \ + metamacro_at(B, 1, 0) + +// IMPLEMENTATION DETAILS FOLLOW! +// Do not write code that depends on anything below this line. +#define metamacro_stringify_(VALUE) # VALUE +#define metamacro_concat_(A, B) A ## B +#define metamacro_foreach_iter(INDEX, MACRO, ARG) MACRO(INDEX, ARG) +#define metamacro_head_(FIRST, ...) FIRST +#define metamacro_tail_(FIRST, ...) __VA_ARGS__ +#define metamacro_consume_(...) +#define metamacro_expand_(...) __VA_ARGS__ + +// implemented from scratch so that metamacro_concat() doesn't end up nesting +#define metamacro_foreach_concat_iter(INDEX, BASE, ARG) metamacro_foreach_concat_iter_(BASE, ARG) +#define metamacro_foreach_concat_iter_(BASE, ARG) BASE ## ARG + +// metamacro_at expansions +#define metamacro_at0(...) metamacro_head(__VA_ARGS__) +#define metamacro_at1(_0, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at2(_0, _1, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at3(_0, _1, _2, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at4(_0, _1, _2, _3, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at5(_0, _1, _2, _3, _4, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at6(_0, _1, _2, _3, _4, _5, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at7(_0, _1, _2, _3, _4, _5, _6, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at8(_0, _1, _2, _3, _4, _5, _6, _7, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at9(_0, _1, _2, _3, _4, _5, _6, _7, _8, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at10(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at11(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at12(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at13(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at14(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at15(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at16(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at17(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at18(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at19(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, ...) metamacro_head(__VA_ARGS__) +#define metamacro_at20(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, ...) metamacro_head(__VA_ARGS__) + +// metamacro_foreach_cxt expansions +#define metamacro_foreach_cxt0(MACRO, SEP, CONTEXT) +#define metamacro_foreach_cxt1(MACRO, SEP, CONTEXT, _0) MACRO(0, CONTEXT, _0) + +#define metamacro_foreach_cxt2(MACRO, SEP, CONTEXT, _0, _1) \ + metamacro_foreach_cxt1(MACRO, SEP, CONTEXT, _0) \ + SEP \ + MACRO(1, CONTEXT, _1) + +#define metamacro_foreach_cxt3(MACRO, SEP, CONTEXT, _0, _1, _2) \ + metamacro_foreach_cxt2(MACRO, SEP, CONTEXT, _0, _1) \ + SEP \ + MACRO(2, CONTEXT, _2) + +#define metamacro_foreach_cxt4(MACRO, SEP, CONTEXT, _0, _1, _2, _3) \ + metamacro_foreach_cxt3(MACRO, SEP, CONTEXT, _0, _1, _2) \ + SEP \ + MACRO(3, CONTEXT, _3) + +#define metamacro_foreach_cxt5(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4) \ + metamacro_foreach_cxt4(MACRO, SEP, CONTEXT, _0, _1, _2, _3) \ + SEP \ + MACRO(4, CONTEXT, _4) + +#define metamacro_foreach_cxt6(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5) \ + metamacro_foreach_cxt5(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4) \ + SEP \ + MACRO(5, CONTEXT, _5) + +#define metamacro_foreach_cxt7(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6) \ + metamacro_foreach_cxt6(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5) \ + SEP \ + MACRO(6, CONTEXT, _6) + +#define metamacro_foreach_cxt8(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7) \ + metamacro_foreach_cxt7(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6) \ + SEP \ + MACRO(7, CONTEXT, _7) + +#define metamacro_foreach_cxt9(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8) \ + metamacro_foreach_cxt8(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7) \ + SEP \ + MACRO(8, CONTEXT, _8) + +#define metamacro_foreach_cxt10(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \ + metamacro_foreach_cxt9(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8) \ + SEP \ + MACRO(9, CONTEXT, _9) + +#define metamacro_foreach_cxt11(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \ + metamacro_foreach_cxt10(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \ + SEP \ + MACRO(10, CONTEXT, _10) + +#define metamacro_foreach_cxt12(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) \ + metamacro_foreach_cxt11(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \ + SEP \ + MACRO(11, CONTEXT, _11) + +#define metamacro_foreach_cxt13(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) \ + metamacro_foreach_cxt12(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) \ + SEP \ + MACRO(12, CONTEXT, _12) + +#define metamacro_foreach_cxt14(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) \ + metamacro_foreach_cxt13(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) \ + SEP \ + MACRO(13, CONTEXT, _13) + +#define metamacro_foreach_cxt15(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) \ + metamacro_foreach_cxt14(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) \ + SEP \ + MACRO(14, CONTEXT, _14) + +#define metamacro_foreach_cxt16(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) \ + metamacro_foreach_cxt15(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) \ + SEP \ + MACRO(15, CONTEXT, _15) + +#define metamacro_foreach_cxt17(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) \ + metamacro_foreach_cxt16(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) \ + SEP \ + MACRO(16, CONTEXT, _16) + +#define metamacro_foreach_cxt18(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) \ + metamacro_foreach_cxt17(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) \ + SEP \ + MACRO(17, CONTEXT, _17) + +#define metamacro_foreach_cxt19(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) \ + metamacro_foreach_cxt18(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) \ + SEP \ + MACRO(18, CONTEXT, _18) + +#define metamacro_foreach_cxt20(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19) \ + metamacro_foreach_cxt19(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) \ + SEP \ + MACRO(19, CONTEXT, _19) + +// metamacro_foreach_cxt_recursive expansions +#define metamacro_foreach_cxt_recursive0(MACRO, SEP, CONTEXT) +#define metamacro_foreach_cxt_recursive1(MACRO, SEP, CONTEXT, _0) MACRO(0, CONTEXT, _0) + +#define metamacro_foreach_cxt_recursive2(MACRO, SEP, CONTEXT, _0, _1) \ + metamacro_foreach_cxt_recursive1(MACRO, SEP, CONTEXT, _0) \ + SEP \ + MACRO(1, CONTEXT, _1) + +#define metamacro_foreach_cxt_recursive3(MACRO, SEP, CONTEXT, _0, _1, _2) \ + metamacro_foreach_cxt_recursive2(MACRO, SEP, CONTEXT, _0, _1) \ + SEP \ + MACRO(2, CONTEXT, _2) + +#define metamacro_foreach_cxt_recursive4(MACRO, SEP, CONTEXT, _0, _1, _2, _3) \ + metamacro_foreach_cxt_recursive3(MACRO, SEP, CONTEXT, _0, _1, _2) \ + SEP \ + MACRO(3, CONTEXT, _3) + +#define metamacro_foreach_cxt_recursive5(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4) \ + metamacro_foreach_cxt_recursive4(MACRO, SEP, CONTEXT, _0, _1, _2, _3) \ + SEP \ + MACRO(4, CONTEXT, _4) + +#define metamacro_foreach_cxt_recursive6(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5) \ + metamacro_foreach_cxt_recursive5(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4) \ + SEP \ + MACRO(5, CONTEXT, _5) + +#define metamacro_foreach_cxt_recursive7(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6) \ + metamacro_foreach_cxt_recursive6(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5) \ + SEP \ + MACRO(6, CONTEXT, _6) + +#define metamacro_foreach_cxt_recursive8(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7) \ + metamacro_foreach_cxt_recursive7(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6) \ + SEP \ + MACRO(7, CONTEXT, _7) + +#define metamacro_foreach_cxt_recursive9(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8) \ + metamacro_foreach_cxt_recursive8(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7) \ + SEP \ + MACRO(8, CONTEXT, _8) + +#define metamacro_foreach_cxt_recursive10(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \ + metamacro_foreach_cxt_recursive9(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8) \ + SEP \ + MACRO(9, CONTEXT, _9) + +#define metamacro_foreach_cxt_recursive11(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \ + metamacro_foreach_cxt_recursive10(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \ + SEP \ + MACRO(10, CONTEXT, _10) + +#define metamacro_foreach_cxt_recursive12(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) \ + metamacro_foreach_cxt_recursive11(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \ + SEP \ + MACRO(11, CONTEXT, _11) + +#define metamacro_foreach_cxt_recursive13(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) \ + metamacro_foreach_cxt_recursive12(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) \ + SEP \ + MACRO(12, CONTEXT, _12) + +#define metamacro_foreach_cxt_recursive14(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) \ + metamacro_foreach_cxt_recursive13(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) \ + SEP \ + MACRO(13, CONTEXT, _13) + +#define metamacro_foreach_cxt_recursive15(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) \ + metamacro_foreach_cxt_recursive14(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) \ + SEP \ + MACRO(14, CONTEXT, _14) + +#define metamacro_foreach_cxt_recursive16(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) \ + metamacro_foreach_cxt_recursive15(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) \ + SEP \ + MACRO(15, CONTEXT, _15) + +#define metamacro_foreach_cxt_recursive17(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) \ + metamacro_foreach_cxt_recursive16(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) \ + SEP \ + MACRO(16, CONTEXT, _16) + +#define metamacro_foreach_cxt_recursive18(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) \ + metamacro_foreach_cxt_recursive17(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) \ + SEP \ + MACRO(17, CONTEXT, _17) + +#define metamacro_foreach_cxt_recursive19(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) \ + metamacro_foreach_cxt_recursive18(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) \ + SEP \ + MACRO(18, CONTEXT, _18) + +#define metamacro_foreach_cxt_recursive20(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19) \ + metamacro_foreach_cxt_recursive19(MACRO, SEP, CONTEXT, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) \ + SEP \ + MACRO(19, CONTEXT, _19) + +// metamacro_for_cxt expansions +#define metamacro_for_cxt0(MACRO, SEP, CONTEXT) +#define metamacro_for_cxt1(MACRO, SEP, CONTEXT) MACRO(0, CONTEXT) + +#define metamacro_for_cxt2(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt1(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(1, CONTEXT) + +#define metamacro_for_cxt3(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt2(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(2, CONTEXT) + +#define metamacro_for_cxt4(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt3(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(3, CONTEXT) + +#define metamacro_for_cxt5(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt4(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(4, CONTEXT) + +#define metamacro_for_cxt6(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt5(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(5, CONTEXT) + +#define metamacro_for_cxt7(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt6(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(6, CONTEXT) + +#define metamacro_for_cxt8(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt7(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(7, CONTEXT) + +#define metamacro_for_cxt9(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt8(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(8, CONTEXT) + +#define metamacro_for_cxt10(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt9(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(9, CONTEXT) + +#define metamacro_for_cxt11(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt10(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(10, CONTEXT) + +#define metamacro_for_cxt12(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt11(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(11, CONTEXT) + +#define metamacro_for_cxt13(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt12(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(12, CONTEXT) + +#define metamacro_for_cxt14(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt13(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(13, CONTEXT) + +#define metamacro_for_cxt15(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt14(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(14, CONTEXT) + +#define metamacro_for_cxt16(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt15(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(15, CONTEXT) + +#define metamacro_for_cxt17(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt16(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(16, CONTEXT) + +#define metamacro_for_cxt18(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt17(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(17, CONTEXT) + +#define metamacro_for_cxt19(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt18(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(18, CONTEXT) + +#define metamacro_for_cxt20(MACRO, SEP, CONTEXT) \ + metamacro_for_cxt19(MACRO, SEP, CONTEXT) \ + SEP \ + MACRO(19, CONTEXT) + +// metamacro_if_eq expansions +#define metamacro_if_eq0(VALUE) \ + metamacro_concat(metamacro_if_eq0_, VALUE) + +#define metamacro_if_eq0_0(...) __VA_ARGS__ metamacro_consume_ +#define metamacro_if_eq0_1(...) metamacro_expand_ +#define metamacro_if_eq0_2(...) metamacro_expand_ +#define metamacro_if_eq0_3(...) metamacro_expand_ +#define metamacro_if_eq0_4(...) metamacro_expand_ +#define metamacro_if_eq0_5(...) metamacro_expand_ +#define metamacro_if_eq0_6(...) metamacro_expand_ +#define metamacro_if_eq0_7(...) metamacro_expand_ +#define metamacro_if_eq0_8(...) metamacro_expand_ +#define metamacro_if_eq0_9(...) metamacro_expand_ +#define metamacro_if_eq0_10(...) metamacro_expand_ +#define metamacro_if_eq0_11(...) metamacro_expand_ +#define metamacro_if_eq0_12(...) metamacro_expand_ +#define metamacro_if_eq0_13(...) metamacro_expand_ +#define metamacro_if_eq0_14(...) metamacro_expand_ +#define metamacro_if_eq0_15(...) metamacro_expand_ +#define metamacro_if_eq0_16(...) metamacro_expand_ +#define metamacro_if_eq0_17(...) metamacro_expand_ +#define metamacro_if_eq0_18(...) metamacro_expand_ +#define metamacro_if_eq0_19(...) metamacro_expand_ +#define metamacro_if_eq0_20(...) metamacro_expand_ + +#define metamacro_if_eq1(VALUE) metamacro_if_eq0(metamacro_dec(VALUE)) +#define metamacro_if_eq2(VALUE) metamacro_if_eq1(metamacro_dec(VALUE)) +#define metamacro_if_eq3(VALUE) metamacro_if_eq2(metamacro_dec(VALUE)) +#define metamacro_if_eq4(VALUE) metamacro_if_eq3(metamacro_dec(VALUE)) +#define metamacro_if_eq5(VALUE) metamacro_if_eq4(metamacro_dec(VALUE)) +#define metamacro_if_eq6(VALUE) metamacro_if_eq5(metamacro_dec(VALUE)) +#define metamacro_if_eq7(VALUE) metamacro_if_eq6(metamacro_dec(VALUE)) +#define metamacro_if_eq8(VALUE) metamacro_if_eq7(metamacro_dec(VALUE)) +#define metamacro_if_eq9(VALUE) metamacro_if_eq8(metamacro_dec(VALUE)) +#define metamacro_if_eq10(VALUE) metamacro_if_eq9(metamacro_dec(VALUE)) +#define metamacro_if_eq11(VALUE) metamacro_if_eq10(metamacro_dec(VALUE)) +#define metamacro_if_eq12(VALUE) metamacro_if_eq11(metamacro_dec(VALUE)) +#define metamacro_if_eq13(VALUE) metamacro_if_eq12(metamacro_dec(VALUE)) +#define metamacro_if_eq14(VALUE) metamacro_if_eq13(metamacro_dec(VALUE)) +#define metamacro_if_eq15(VALUE) metamacro_if_eq14(metamacro_dec(VALUE)) +#define metamacro_if_eq16(VALUE) metamacro_if_eq15(metamacro_dec(VALUE)) +#define metamacro_if_eq17(VALUE) metamacro_if_eq16(metamacro_dec(VALUE)) +#define metamacro_if_eq18(VALUE) metamacro_if_eq17(metamacro_dec(VALUE)) +#define metamacro_if_eq19(VALUE) metamacro_if_eq18(metamacro_dec(VALUE)) +#define metamacro_if_eq20(VALUE) metamacro_if_eq19(metamacro_dec(VALUE)) + +// metamacro_if_eq_recursive expansions +#define metamacro_if_eq_recursive0(VALUE) \ + metamacro_concat(metamacro_if_eq_recursive0_, VALUE) + +#define metamacro_if_eq_recursive0_0(...) __VA_ARGS__ metamacro_consume_ +#define metamacro_if_eq_recursive0_1(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_2(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_3(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_4(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_5(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_6(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_7(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_8(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_9(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_10(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_11(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_12(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_13(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_14(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_15(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_16(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_17(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_18(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_19(...) metamacro_expand_ +#define metamacro_if_eq_recursive0_20(...) metamacro_expand_ + +#define metamacro_if_eq_recursive1(VALUE) metamacro_if_eq_recursive0(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive2(VALUE) metamacro_if_eq_recursive1(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive3(VALUE) metamacro_if_eq_recursive2(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive4(VALUE) metamacro_if_eq_recursive3(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive5(VALUE) metamacro_if_eq_recursive4(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive6(VALUE) metamacro_if_eq_recursive5(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive7(VALUE) metamacro_if_eq_recursive6(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive8(VALUE) metamacro_if_eq_recursive7(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive9(VALUE) metamacro_if_eq_recursive8(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive10(VALUE) metamacro_if_eq_recursive9(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive11(VALUE) metamacro_if_eq_recursive10(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive12(VALUE) metamacro_if_eq_recursive11(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive13(VALUE) metamacro_if_eq_recursive12(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive14(VALUE) metamacro_if_eq_recursive13(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive15(VALUE) metamacro_if_eq_recursive14(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive16(VALUE) metamacro_if_eq_recursive15(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive17(VALUE) metamacro_if_eq_recursive16(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive18(VALUE) metamacro_if_eq_recursive17(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive19(VALUE) metamacro_if_eq_recursive18(metamacro_dec(VALUE)) +#define metamacro_if_eq_recursive20(VALUE) metamacro_if_eq_recursive19(metamacro_dec(VALUE)) + +// metamacro_take expansions +#define metamacro_take0(...) +#define metamacro_take1(...) metamacro_head(__VA_ARGS__) +#define metamacro_take2(...) metamacro_head(__VA_ARGS__), metamacro_take1(metamacro_tail(__VA_ARGS__)) +#define metamacro_take3(...) metamacro_head(__VA_ARGS__), metamacro_take2(metamacro_tail(__VA_ARGS__)) +#define metamacro_take4(...) metamacro_head(__VA_ARGS__), metamacro_take3(metamacro_tail(__VA_ARGS__)) +#define metamacro_take5(...) metamacro_head(__VA_ARGS__), metamacro_take4(metamacro_tail(__VA_ARGS__)) +#define metamacro_take6(...) metamacro_head(__VA_ARGS__), metamacro_take5(metamacro_tail(__VA_ARGS__)) +#define metamacro_take7(...) metamacro_head(__VA_ARGS__), metamacro_take6(metamacro_tail(__VA_ARGS__)) +#define metamacro_take8(...) metamacro_head(__VA_ARGS__), metamacro_take7(metamacro_tail(__VA_ARGS__)) +#define metamacro_take9(...) metamacro_head(__VA_ARGS__), metamacro_take8(metamacro_tail(__VA_ARGS__)) +#define metamacro_take10(...) metamacro_head(__VA_ARGS__), metamacro_take9(metamacro_tail(__VA_ARGS__)) +#define metamacro_take11(...) metamacro_head(__VA_ARGS__), metamacro_take10(metamacro_tail(__VA_ARGS__)) +#define metamacro_take12(...) metamacro_head(__VA_ARGS__), metamacro_take11(metamacro_tail(__VA_ARGS__)) +#define metamacro_take13(...) metamacro_head(__VA_ARGS__), metamacro_take12(metamacro_tail(__VA_ARGS__)) +#define metamacro_take14(...) metamacro_head(__VA_ARGS__), metamacro_take13(metamacro_tail(__VA_ARGS__)) +#define metamacro_take15(...) metamacro_head(__VA_ARGS__), metamacro_take14(metamacro_tail(__VA_ARGS__)) +#define metamacro_take16(...) metamacro_head(__VA_ARGS__), metamacro_take15(metamacro_tail(__VA_ARGS__)) +#define metamacro_take17(...) metamacro_head(__VA_ARGS__), metamacro_take16(metamacro_tail(__VA_ARGS__)) +#define metamacro_take18(...) metamacro_head(__VA_ARGS__), metamacro_take17(metamacro_tail(__VA_ARGS__)) +#define metamacro_take19(...) metamacro_head(__VA_ARGS__), metamacro_take18(metamacro_tail(__VA_ARGS__)) +#define metamacro_take20(...) metamacro_head(__VA_ARGS__), metamacro_take19(metamacro_tail(__VA_ARGS__)) + +// metamacro_drop expansions +#define metamacro_drop0(...) __VA_ARGS__ +#define metamacro_drop1(...) metamacro_tail(__VA_ARGS__) +#define metamacro_drop2(...) metamacro_drop1(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop3(...) metamacro_drop2(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop4(...) metamacro_drop3(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop5(...) metamacro_drop4(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop6(...) metamacro_drop5(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop7(...) metamacro_drop6(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop8(...) metamacro_drop7(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop9(...) metamacro_drop8(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop10(...) metamacro_drop9(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop11(...) metamacro_drop10(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop12(...) metamacro_drop11(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop13(...) metamacro_drop12(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop14(...) metamacro_drop13(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop15(...) metamacro_drop14(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop16(...) metamacro_drop15(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop17(...) metamacro_drop16(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop18(...) metamacro_drop17(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop19(...) metamacro_drop18(metamacro_tail(__VA_ARGS__)) +#define metamacro_drop20(...) metamacro_drop19(metamacro_tail(__VA_ARGS__)) + +#endif diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/UIColor+HexString.h b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/UIColor+HexString.h new file mode 100644 index 0000000..2a8a3d8 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/UIColor+HexString.h @@ -0,0 +1,18 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "SDWebImageCompat.h" + +@interface UIColor (HexString) + +/** + Convenience way to get hex string from color. The output should always be 32-bit RGBA hex string like `#00000000`. + */ +@property (nonatomic, copy, readonly, nonnull) NSString *sd_hexString; + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/UIColor+HexString.m b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/UIColor+HexString.m new file mode 100644 index 0000000..aebb6e3 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/SDWebImage/Private/UIColor+HexString.m @@ -0,0 +1,42 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import "UIColor+HexString.h" + +@implementation UIColor (HexString) + +- (NSString *)sd_hexString { + CGFloat red, green, blue, alpha; +#if SD_UIKIT + if (![self getRed:&red green:&green blue:&blue alpha:&alpha]) { + [self getWhite:&red alpha:&alpha]; + green = red; + blue = red; + } +#else + @try { + [self getRed:&red green:&green blue:&blue alpha:&alpha]; + } + @catch (NSException *exception) { + [self getWhite:&red alpha:&alpha]; + green = red; + blue = red; + } +#endif + + red = roundf(red * 255.f); + green = roundf(green * 255.f); + blue = roundf(blue * 255.f); + alpha = roundf(alpha * 255.f); + + uint hex = ((uint)alpha << 24) | ((uint)red << 16) | ((uint)green << 8) | ((uint)blue); + + return [NSString stringWithFormat:@"#%08x", hex]; +} + +@end diff --git a/TesteArenaFelipePerius/Pods/SDWebImage/WebImage/SDWebImage.h b/TesteArenaFelipePerius/Pods/SDWebImage/WebImage/SDWebImage.h new file mode 100644 index 0000000..f219978 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/SDWebImage/WebImage/SDWebImage.h @@ -0,0 +1,92 @@ +/* + * This file is part of the SDWebImage package. + * (c) Olivier Poitrey + * (c) Florent Vilmart + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +#import + +#if SD_UIKIT +#import +#endif + +//! Project version number for WebImage. +FOUNDATION_EXPORT double WebImageVersionNumber; + +//! Project version string for WebImage. +FOUNDATION_EXPORT const unsigned char WebImageVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import + +// Mac +#if __has_include() +#import +#endif +#if __has_include() +#import +#endif +#if __has_include() +#import +#endif + +// MapKit +#if __has_include() +#import +#endif diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.markdown b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.markdown index 11ad986..d9fc904 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.markdown +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.markdown @@ -47,4 +47,28 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of 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. + +## SDWebImage + +Copyright (c) 2009-2018 Olivier Poitrey rs@dailymotion.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + Generated by CocoaPods - https://cocoapods.org diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.plist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.plist index 35b6c8c..c7c621f 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.plist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-acknowledgements.plist @@ -77,6 +77,36 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI Type PSGroupSpecifier + + FooterText + Copyright (c) 2009-2018 Olivier Poitrey rs@dailymotion.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + + License + MIT + Title + SDWebImage + Type + PSGroupSpecifier + FooterText Generated by CocoaPods - https://cocoapods.org diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-input-files.xcfilelist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-input-files.xcfilelist index 09ad86c..92f0c66 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-input-files.xcfilelist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-input-files.xcfilelist @@ -1,4 +1,5 @@ ${PODS_ROOT}/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh ${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework ${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework -${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework \ No newline at end of file +${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework +${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework \ No newline at end of file diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-output-files.xcfilelist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-output-files.xcfilelist index 449948d..2c149ed 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-output-files.xcfilelist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Debug-output-files.xcfilelist @@ -1,3 +1,4 @@ ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ObjectMapper.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework \ No newline at end of file +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework \ No newline at end of file diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-input-files.xcfilelist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-input-files.xcfilelist index 09ad86c..92f0c66 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-input-files.xcfilelist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-input-files.xcfilelist @@ -1,4 +1,5 @@ ${PODS_ROOT}/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh ${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework ${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework -${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework \ No newline at end of file +${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework +${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework \ No newline at end of file diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-output-files.xcfilelist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-output-files.xcfilelist index 449948d..2c149ed 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-output-files.xcfilelist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks-Release-output-files.xcfilelist @@ -1,3 +1,4 @@ ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ObjectMapper.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework \ No newline at end of file +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework \ No newline at end of file diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh index 71130b3..27678e1 100755 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests-frameworks.sh @@ -164,11 +164,13 @@ if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework" install_framework "${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework" install_framework "${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig index 51c938e..7bc22f4 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig @@ -1,9 +1,9 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ObjectMapper" -framework "RxSwift" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ImageIO" -framework "ObjectMapper" -framework "RxSwift" -framework "SDWebImage" OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.release.xcconfig b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.release.xcconfig index 51c938e..7bc22f4 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.release.xcconfig +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.release.xcconfig @@ -1,9 +1,9 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ObjectMapper" -framework "RxSwift" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ImageIO" -framework "ObjectMapper" -framework "RxSwift" -framework "SDWebImage" OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.markdown b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.markdown index 11ad986..d9fc904 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.markdown +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.markdown @@ -47,4 +47,28 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of 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. + +## SDWebImage + +Copyright (c) 2009-2018 Olivier Poitrey rs@dailymotion.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + Generated by CocoaPods - https://cocoapods.org diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.plist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.plist index 35b6c8c..c7c621f 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.plist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-acknowledgements.plist @@ -77,6 +77,36 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI Type PSGroupSpecifier + + FooterText + Copyright (c) 2009-2018 Olivier Poitrey rs@dailymotion.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + + License + MIT + Title + SDWebImage + Type + PSGroupSpecifier + FooterText Generated by CocoaPods - https://cocoapods.org diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-input-files.xcfilelist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-input-files.xcfilelist index b1be39a..348d2c2 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-input-files.xcfilelist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-input-files.xcfilelist @@ -1,4 +1,5 @@ ${PODS_ROOT}/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks.sh ${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework ${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework -${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework \ No newline at end of file +${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework +${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework \ No newline at end of file diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-output-files.xcfilelist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-output-files.xcfilelist index 449948d..2c149ed 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-output-files.xcfilelist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Debug-output-files.xcfilelist @@ -1,3 +1,4 @@ ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ObjectMapper.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework \ No newline at end of file +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework \ No newline at end of file diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-input-files.xcfilelist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-input-files.xcfilelist index b1be39a..348d2c2 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-input-files.xcfilelist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-input-files.xcfilelist @@ -1,4 +1,5 @@ ${PODS_ROOT}/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks.sh ${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework ${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework -${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework \ No newline at end of file +${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework +${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework \ No newline at end of file diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-output-files.xcfilelist b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-output-files.xcfilelist index 449948d..2c149ed 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-output-files.xcfilelist +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks-Release-output-files.xcfilelist @@ -1,3 +1,4 @@ ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ObjectMapper.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework \ No newline at end of file +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework \ No newline at end of file diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks.sh b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks.sh index 71130b3..27678e1 100755 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks.sh +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius-frameworks.sh @@ -164,11 +164,13 @@ if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework" install_framework "${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework" install_framework "${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.debug.xcconfig b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.debug.xcconfig index 51c938e..7bc22f4 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.debug.xcconfig +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.debug.xcconfig @@ -1,9 +1,9 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ObjectMapper" -framework "RxSwift" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ImageIO" -framework "ObjectMapper" -framework "RxSwift" -framework "SDWebImage" OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.release.xcconfig b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.release.xcconfig index 51c938e..7bc22f4 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.release.xcconfig +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.release.xcconfig @@ -1,9 +1,9 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ObjectMapper" -framework "RxSwift" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ImageIO" -framework "ObjectMapper" -framework "RxSwift" -framework "SDWebImage" OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.debug.xcconfig b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.debug.xcconfig index d69cba4..7d74c52 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.debug.xcconfig +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.debug.xcconfig @@ -1,7 +1,7 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ObjectMapper" -framework "RxSwift" +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ImageIO" -framework "ObjectMapper" -framework "RxSwift" -framework "SDWebImage" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.release.xcconfig b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.release.xcconfig index d69cba4..7d74c52 100644 --- a/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.release.xcconfig +++ b/TesteArenaFelipePerius/Pods/Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.release.xcconfig @@ -1,7 +1,7 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ObjectMapper" -framework "RxSwift" +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/RxSwift/RxSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "CFNetwork" -framework "ImageIO" -framework "ObjectMapper" -framework "RxSwift" -framework "SDWebImage" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-Info.plist b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-Info.plist new file mode 100644 index 0000000..128157e --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.5.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m new file mode 100644 index 0000000..86d2b5f --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SDWebImage : NSObject +@end +@implementation PodsDummy_SDWebImage +@end diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-umbrella.h b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-umbrella.h new file mode 100644 index 0000000..fb94fa1 --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage-umbrella.h @@ -0,0 +1,74 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "NSButton+WebCache.h" +#import "NSData+ImageContentType.h" +#import "NSImage+Compatibility.h" +#import "SDAnimatedImage.h" +#import "SDAnimatedImagePlayer.h" +#import "SDAnimatedImageRep.h" +#import "SDAnimatedImageView+WebCache.h" +#import "SDAnimatedImageView.h" +#import "SDDiskCache.h" +#import "SDGraphicsImageRenderer.h" +#import "SDImageAPNGCoder.h" +#import "SDImageCache.h" +#import "SDImageCacheConfig.h" +#import "SDImageCacheDefine.h" +#import "SDImageCachesManager.h" +#import "SDImageCoder.h" +#import "SDImageCoderHelper.h" +#import "SDImageCodersManager.h" +#import "SDImageFrame.h" +#import "SDImageGIFCoder.h" +#import "SDImageGraphics.h" +#import "SDImageHEICCoder.h" +#import "SDImageIOAnimatedCoder.h" +#import "SDImageIOCoder.h" +#import "SDImageLoader.h" +#import "SDImageLoadersManager.h" +#import "SDImageTransformer.h" +#import "SDMemoryCache.h" +#import "SDWebImageCacheKeyFilter.h" +#import "SDWebImageCacheSerializer.h" +#import "SDWebImageCompat.h" +#import "SDWebImageDefine.h" +#import "SDWebImageDownloader.h" +#import "SDWebImageDownloaderConfig.h" +#import "SDWebImageDownloaderDecryptor.h" +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageDownloaderRequestModifier.h" +#import "SDWebImageDownloaderResponseModifier.h" +#import "SDWebImageError.h" +#import "SDWebImageIndicator.h" +#import "SDWebImageManager.h" +#import "SDWebImageOperation.h" +#import "SDWebImageOptionsProcessor.h" +#import "SDWebImagePrefetcher.h" +#import "SDWebImageTransition.h" +#import "UIButton+WebCache.h" +#import "UIImage+ExtendedCacheData.h" +#import "UIImage+ForceDecode.h" +#import "UIImage+GIF.h" +#import "UIImage+MemoryCacheCost.h" +#import "UIImage+Metadata.h" +#import "UIImage+MultiFormat.h" +#import "UIImage+Transform.h" +#import "UIImageView+HighlightedWebCache.h" +#import "UIImageView+WebCache.h" +#import "UIView+WebCache.h" +#import "UIView+WebCacheOperation.h" +#import "SDWebImage.h" + +FOUNDATION_EXPORT double SDWebImageVersionNumber; +FOUNDATION_EXPORT const unsigned char SDWebImageVersionString[]; + diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage.modulemap b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage.modulemap new file mode 100644 index 0000000..91545be --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage.modulemap @@ -0,0 +1,6 @@ +framework module SDWebImage { + umbrella header "SDWebImage-umbrella.h" + + export * + module * { export * } +} diff --git a/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage.xcconfig b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage.xcconfig new file mode 100644 index 0000000..4e955db --- /dev/null +++ b/TesteArenaFelipePerius/Pods/Target Support Files/SDWebImage/SDWebImage.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage +DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER = NO +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "ImageIO" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SDWebImage +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +SUPPORTS_MACCATALYST = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj index b466fb7..3e58dc9 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 2F317E0723FC39AC0078CFEE /* UIColor+Util.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F317E0623FC39AC0078CFEE /* UIColor+Util.swift */; }; 2F5C380A23FA179C000985E2 /* RepositoryTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F5C380823FA179C000985E2 /* RepositoryTableViewCell.swift */; }; 2F5C380B23FA179C000985E2 /* RepositoryTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2F5C380923FA179C000985E2 /* RepositoryTableViewCell.xib */; }; 2F5C380D23FAE992000985E2 /* HomeDataScource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F5C380C23FAE992000985E2 /* HomeDataScource.swift */; }; @@ -65,6 +66,7 @@ /* Begin PBXFileReference section */ 048ABF9CC21A73C4F9C32A2B /* Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2F317E0623FC39AC0078CFEE /* UIColor+Util.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIColor+Util.swift"; sourceTree = ""; }; 2F5C380823FA179C000985E2 /* RepositoryTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RepositoryTableViewCell.swift; sourceTree = ""; }; 2F5C380923FA179C000985E2 /* RepositoryTableViewCell.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = RepositoryTableViewCell.xib; sourceTree = ""; }; 2F5C380C23FAE992000985E2 /* HomeDataScource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeDataScource.swift; sourceTree = ""; }; @@ -143,9 +145,18 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 2F317E0823FC3FDC0078CFEE /* Color */ = { + isa = PBXGroup; + children = ( + 2F317E0623FC39AC0078CFEE /* UIColor+Util.swift */, + ); + path = Color; + sourceTree = ""; + }; 2F5C380F23FAF8E2000985E2 /* Helpers */ = { isa = PBXGroup; children = ( + 2F317E0823FC3FDC0078CFEE /* Color */, 2F83AD5323FC2E38006CF2E5 /* View */, 2F83AD4E23FC2983006CF2E5 /* AlertUtils */, 2F5C382123FAF9A4000985E2 /* Extension */, @@ -650,6 +661,7 @@ 2F83AD5023FC2999006CF2E5 /* AlertUtils.swift in Sources */, 2F5C382023FAF97E000985E2 /* NSObject+ClassName.swift in Sources */, 2F5C381A23FAF97E000985E2 /* NibLoadableView.swift in Sources */, + 2F317E0723FC39AC0078CFEE /* UIColor+Util.swift in Sources */, 2F5C381D23FAF97E000985E2 /* AutoheightableView.swift in Sources */, 2F5C382523FB0919000985E2 /* RepositoryList.swift in Sources */, 2F7B7C6F23FA07B2006D73D2 /* HomeViewController+ExtensionNavBar.swift in Sources */, diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/xcuserdata/feperius.xcuserdatad/xcschemes/xcschememanagement.plist b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/xcuserdata/feperius.xcuserdatad/xcschemes/xcschememanagement.plist index f1bdc8b..5e9b349 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/xcuserdata/feperius.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/xcuserdata/feperius.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ TesteArenaFelipePerius.xcscheme_^#shared#^_ orderHint - 6 + 7 diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Helpers/Color/UIColor+Util.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Helpers/Color/UIColor+Util.swift new file mode 100644 index 0000000..daf7699 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Helpers/Color/UIColor+Util.swift @@ -0,0 +1,5 @@ +import UIKit + +public extension UIColor { + static var taOrange: UIColor = #colorLiteral(red: 0.8745098039, green: 0.5764705882, blue: 0.01960784314, alpha: 1) +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist b/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist index 27cda5f..64bb8c5 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Info.plist @@ -20,6 +20,10 @@ 1 LSRequiresIPhoneOS + UIStatusBarStyle + UIStatusBarStyleLightContent + UIViewControllerBasedStatusBarAppearance + UILaunchStoryboardName LaunchScreen UIMainStoryboardFile diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.swift index a788305..e208056 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.swift +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.swift @@ -7,6 +7,7 @@ // import UIKit +import SDWebImage class RepositoryTableViewCell: UITableViewCell { @@ -18,6 +19,7 @@ class RepositoryTableViewCell: UITableViewCell { @IBOutlet weak var fullName: UILabel! @IBOutlet weak var forkImageView: UIImageView! @IBOutlet weak var starImageView: UIImageView! + @IBOutlet weak var photoUser: UIImageView! static let identifier: String = "RepositoryTableViewCell" @@ -28,16 +30,21 @@ class RepositoryTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() selectionStyle = .none + self.setupViewCell() } func setupCell(respository:Repository) { if let owner = respository.owner { usernameLabel.text = owner.name + if let avatarUrl = owner.avatarUrl{ + self.loadImageView(url:avatarUrl) + } } titleRepository.text = respository.name descriptionRepository.text = respository.description + fullName.text = respository.fullName if let countForks = respository.forksCount { numberForks.text = "\(countForks)" @@ -46,6 +53,20 @@ class RepositoryTableViewCell: UITableViewCell { if let starsCount = respository.starsCount { numberStars.text = "\(starsCount)" } + } + func setupViewCell(){ + let image = UIImage(named: "ic_fork")!.withRenderingMode(.alwaysTemplate) + forkImageView.image = image + forkImageView.tintColor = UIColor.taOrange + + photoUser.layer.cornerRadius = photoUser.frame.size.width / 2 + photoUser.clipsToBounds = true + } + + func loadImageView(url:String){ + photoUser.sd_setImage(with: URL(string:url), placeholderImage: UIImage(named: "photo_user")) + } + } diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib index a3f4336..9bf7c85 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib @@ -111,6 +111,7 @@ + From 061bd9af197da57e2f4e2b55785c7f886f2a0e20 Mon Sep 17 00:00:00 2001 From: felipe Date: Tue, 18 Feb 2020 23:48:53 -0300 Subject: [PATCH 13/25] implenation scenes clean pullRequestViewController --- .../project.pbxproj | 68 ++++++++++++++ .../arena_logo.imageset/Contents.json | 21 +++++ .../arena_logo.imageset/arena_Logo.png | Bin 0 -> 17715 bytes .../Helpers/Segues/SegueName.swift | 16 ++++ .../Models/PullRequest.swift | 31 +++++++ .../TesteArenaFelipePerius/Models/User.swift | 28 ++++++ .../Scenes/Home/HomeDataScource.swift | 21 +++++ .../Scenes/Home/HomeInteractor.swift | 25 +++--- .../Scenes/Home/HomeRouter.swift | 17 ++++ .../Scenes/Home/HomeViewController.swift | 30 +++++-- .../PullRequestDataScource.swift | 57 ++++++++++++ .../PullRequestInteractor.swift | 32 +++++++ .../PullRequestList/PullRequestModel.swift | 17 ++++ .../PullRequestPresenter.swift | 27 ++++++ .../PullRequestsViewController.swift | 73 +++++++++++++++ .../Service/Manager /Routes/Routes.swift | 2 +- .../Service/PullRequestService.swift | 41 +++++++++ .../Service/RepositoryService.swift | 2 +- .../View/Cells/HeaderTableViewCell.swift | 24 +++++ .../View/Cells/HeaderTableViewCell.xib | 47 ++++++++++ .../View/Cells/PullRequestTableViewCell.swift | 51 +++++++++++ .../View/Cells/PullRequestTableViewCell.xib | 84 ++++++++++++++++++ .../View/Cells/RepositoryTableViewCell.xib | 6 +- .../Base.lproj/LaunchScreen.storyboard | 27 ++++-- .../View/Storyboard/Home.storyboard | 47 ++++++++-- .../Workers/PullRequestWorker.swift | 20 +++++ .../Workers/RepositoryWorker.swift | 6 +- 27 files changed, 782 insertions(+), 38 deletions(-) create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/arena_logo.imageset/Contents.json create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/arena_logo.imageset/arena_Logo.png create mode 100755 TesteArenaFelipePerius/TesteArenaFelipePerius/Helpers/Segues/SegueName.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Models/PullRequest.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Models/User.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeRouter.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestDataScource.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestInteractor.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestModel.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestPresenter.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestsViewController.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Service/PullRequestService.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/HeaderTableViewCell.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/HeaderTableViewCell.xib create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/PullRequestTableViewCell.swift create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/PullRequestTableViewCell.xib create mode 100644 TesteArenaFelipePerius/TesteArenaFelipePerius/Workers/PullRequestWorker.swift diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj index 3e58dc9..8bf3566 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius.xcodeproj/project.pbxproj @@ -7,6 +7,14 @@ objects = { /* Begin PBXBuildFile section */ + 2F04A9C923FC63DA00863D28 /* PullRequestsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F04A9C823FC63DA00863D28 /* PullRequestsViewController.swift */; }; + 2F04A9CC23FC642500863D28 /* HeaderTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F04A9CA23FC642500863D28 /* HeaderTableViewCell.swift */; }; + 2F04A9CD23FC642500863D28 /* HeaderTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2F04A9CB23FC642500863D28 /* HeaderTableViewCell.xib */; }; + 2F04A9D023FC667D00863D28 /* PullRequestTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F04A9CE23FC667D00863D28 /* PullRequestTableViewCell.swift */; }; + 2F04A9D123FC667D00863D28 /* PullRequestTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2F04A9CF23FC667D00863D28 /* PullRequestTableViewCell.xib */; }; + 2F04A9D323FC6AFE00863D28 /* PullRequestDataScource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F04A9D223FC6AFE00863D28 /* PullRequestDataScource.swift */; }; + 2F04A9D523FC6BE000863D28 /* HomeRouter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F04A9D423FC6BE000863D28 /* HomeRouter.swift */; }; + 2F04A9D723FC6C1C00863D28 /* SegueName.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F04A9D623FC6C1C00863D28 /* SegueName.swift */; }; 2F317E0723FC39AC0078CFEE /* UIColor+Util.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F317E0623FC39AC0078CFEE /* UIColor+Util.swift */; }; 2F5C380A23FA179C000985E2 /* RepositoryTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F5C380823FA179C000985E2 /* RepositoryTableViewCell.swift */; }; 2F5C380B23FA179C000985E2 /* RepositoryTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2F5C380923FA179C000985E2 /* RepositoryTableViewCell.xib */; }; @@ -42,6 +50,13 @@ 2F83AD4D23FB6436006CF2E5 /* HomeModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F83AD4C23FB6436006CF2E5 /* HomeModels.swift */; }; 2F83AD5023FC2999006CF2E5 /* AlertUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F83AD4F23FC2999006CF2E5 /* AlertUtils.swift */; }; 2F83AD5223FC2E31006CF2E5 /* UIViewExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F83AD5123FC2E31006CF2E5 /* UIViewExtension.swift */; }; + 2FDB6C8423FC867000200D05 /* PullRequestService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FDB6C8323FC867000200D05 /* PullRequestService.swift */; }; + 2FDB6C8623FC8A1400200D05 /* PullRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FDB6C8523FC8A1400200D05 /* PullRequest.swift */; }; + 2FDB6C8823FC941600200D05 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FDB6C8723FC941600200D05 /* User.swift */; }; + 2FDB6C8A23FCAD1B00200D05 /* PullRequestWorker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FDB6C8923FCAD1B00200D05 /* PullRequestWorker.swift */; }; + 2FDB6C8C23FCBAAE00200D05 /* PullRequestInteractor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FDB6C8B23FCBAAE00200D05 /* PullRequestInteractor.swift */; }; + 2FDB6C8E23FCBD7100200D05 /* PullRequestPresenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FDB6C8D23FCBD7100200D05 /* PullRequestPresenter.swift */; }; + 2FDB6C9023FCBDC600200D05 /* PullRequestModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FDB6C8F23FCBDC600200D05 /* PullRequestModel.swift */; }; 5788081D7108998BDFD8FE21 /* Pods_TesteArenaFelipePeriusTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 682DE70EE38E255494C0F9ED /* Pods_TesteArenaFelipePeriusTests.framework */; }; A8252042FBBD56510D0BEE34 /* Pods_TesteArenaFelipePerius.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F5065BBB3CF4BF530C374DE0 /* Pods_TesteArenaFelipePerius.framework */; }; B9E7660544DD81AF378C2AF7 /* Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 048ABF9CC21A73C4F9C32A2B /* Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework */; }; @@ -66,6 +81,14 @@ /* Begin PBXFileReference section */ 048ABF9CC21A73C4F9C32A2B /* Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_TesteArenaFelipePerius_TesteArenaFelipePeriusUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2F04A9C823FC63DA00863D28 /* PullRequestsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PullRequestsViewController.swift; sourceTree = ""; }; + 2F04A9CA23FC642500863D28 /* HeaderTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HeaderTableViewCell.swift; sourceTree = ""; }; + 2F04A9CB23FC642500863D28 /* HeaderTableViewCell.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = HeaderTableViewCell.xib; sourceTree = ""; }; + 2F04A9CE23FC667D00863D28 /* PullRequestTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PullRequestTableViewCell.swift; sourceTree = ""; }; + 2F04A9CF23FC667D00863D28 /* PullRequestTableViewCell.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = PullRequestTableViewCell.xib; sourceTree = ""; }; + 2F04A9D223FC6AFE00863D28 /* PullRequestDataScource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PullRequestDataScource.swift; sourceTree = ""; }; + 2F04A9D423FC6BE000863D28 /* HomeRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeRouter.swift; sourceTree = ""; }; + 2F04A9D623FC6C1C00863D28 /* SegueName.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SegueName.swift; sourceTree = ""; }; 2F317E0623FC39AC0078CFEE /* UIColor+Util.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIColor+Util.swift"; sourceTree = ""; }; 2F5C380823FA179C000985E2 /* RepositoryTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RepositoryTableViewCell.swift; sourceTree = ""; }; 2F5C380923FA179C000985E2 /* RepositoryTableViewCell.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = RepositoryTableViewCell.xib; sourceTree = ""; }; @@ -107,6 +130,13 @@ 2F83AD4C23FB6436006CF2E5 /* HomeModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeModels.swift; sourceTree = ""; }; 2F83AD4F23FC2999006CF2E5 /* AlertUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AlertUtils.swift; sourceTree = ""; }; 2F83AD5123FC2E31006CF2E5 /* UIViewExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UIViewExtension.swift; sourceTree = ""; }; + 2FDB6C8323FC867000200D05 /* PullRequestService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PullRequestService.swift; sourceTree = ""; }; + 2FDB6C8523FC8A1400200D05 /* PullRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PullRequest.swift; sourceTree = ""; }; + 2FDB6C8723FC941600200D05 /* User.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 2FDB6C8923FCAD1B00200D05 /* PullRequestWorker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PullRequestWorker.swift; sourceTree = ""; }; + 2FDB6C8B23FCBAAE00200D05 /* PullRequestInteractor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PullRequestInteractor.swift; sourceTree = ""; }; + 2FDB6C8D23FCBD7100200D05 /* PullRequestPresenter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PullRequestPresenter.swift; sourceTree = ""; }; + 2FDB6C8F23FCBDC600200D05 /* PullRequestModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PullRequestModel.swift; sourceTree = ""; }; 4B9D8828C4E241ED882C63F0 /* Pods-TesteArenaFelipePerius.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-TesteArenaFelipePerius.debug.xcconfig"; path = "Target Support Files/Pods-TesteArenaFelipePerius/Pods-TesteArenaFelipePerius.debug.xcconfig"; sourceTree = ""; }; 5BFC72AAAF6B1B0E9E4804F1 /* Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig"; path = "Target Support Files/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests/Pods-TesteArenaFelipePerius-TesteArenaFelipePeriusUITests.debug.xcconfig"; sourceTree = ""; }; 676BFE73DC18D74400BA3C6A /* Pods-TesteArenaFelipePeriusTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-TesteArenaFelipePeriusTests.debug.xcconfig"; path = "Target Support Files/Pods-TesteArenaFelipePeriusTests/Pods-TesteArenaFelipePeriusTests.debug.xcconfig"; sourceTree = ""; }; @@ -145,6 +175,14 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 2F04A9D823FC6C2000863D28 /* Segues */ = { + isa = PBXGroup; + children = ( + 2F04A9D623FC6C1C00863D28 /* SegueName.swift */, + ); + path = Segues; + sourceTree = ""; + }; 2F317E0823FC3FDC0078CFEE /* Color */ = { isa = PBXGroup; children = ( @@ -156,6 +194,7 @@ 2F5C380F23FAF8E2000985E2 /* Helpers */ = { isa = PBXGroup; children = ( + 2F04A9D823FC6C2000863D28 /* Segues */, 2F317E0823FC3FDC0078CFEE /* Color */, 2F83AD5323FC2E38006CF2E5 /* View */, 2F83AD4E23FC2983006CF2E5 /* AlertUtils */, @@ -193,6 +232,7 @@ children = ( 2F5C382C23FB184E000985E2 /* Manager */, 2F5C382A23FB171A000985E2 /* RepositoryService.swift */, + 2FDB6C8323FC867000200D05 /* PullRequestService.swift */, ); path = Service; sourceTree = ""; @@ -201,8 +241,10 @@ isa = PBXGroup; children = ( 2F5C382423FB0919000985E2 /* RepositoryList.swift */, + 2FDB6C8523FC8A1400200D05 /* PullRequest.swift */, 2F5C382623FB09DB000985E2 /* Repository.swift */, 2F5C382823FB12C6000985E2 /* Owner.swift */, + 2FDB6C8723FC941600200D05 /* User.swift */, ); path = Models; sourceTree = ""; @@ -237,6 +279,7 @@ isa = PBXGroup; children = ( 2F5C383623FB314A000985E2 /* RepositoryWorker.swift */, + 2FDB6C8923FCAD1B00200D05 /* PullRequestWorker.swift */, ); path = Workers; sourceTree = ""; @@ -341,6 +384,7 @@ 2F83AD4823FB4119006CF2E5 /* HomeInteractor.swift */, 2F83AD4A23FB6171006CF2E5 /* HomePresenter.swift */, 2F83AD4C23FB6436006CF2E5 /* HomeModels.swift */, + 2F04A9D423FC6BE000863D28 /* HomeRouter.swift */, ); path = Home; sourceTree = ""; @@ -348,6 +392,11 @@ 2F7B7C6623FA01CD006D73D2 /* PullRequestList */ = { isa = PBXGroup; children = ( + 2F04A9C823FC63DA00863D28 /* PullRequestsViewController.swift */, + 2FDB6C8F23FCBDC600200D05 /* PullRequestModel.swift */, + 2F04A9D223FC6AFE00863D28 /* PullRequestDataScource.swift */, + 2FDB6C8B23FCBAAE00200D05 /* PullRequestInteractor.swift */, + 2FDB6C8D23FCBD7100200D05 /* PullRequestPresenter.swift */, ); path = PullRequestList; sourceTree = ""; @@ -366,6 +415,10 @@ children = ( 2F5C380823FA179C000985E2 /* RepositoryTableViewCell.swift */, 2F5C380923FA179C000985E2 /* RepositoryTableViewCell.xib */, + 2F04A9CA23FC642500863D28 /* HeaderTableViewCell.swift */, + 2F04A9CB23FC642500863D28 /* HeaderTableViewCell.xib */, + 2F04A9CE23FC667D00863D28 /* PullRequestTableViewCell.swift */, + 2F04A9CF23FC667D00863D28 /* PullRequestTableViewCell.xib */, ); path = Cells; sourceTree = ""; @@ -522,6 +575,8 @@ 2F7B7C4023F711C9006D73D2 /* LaunchScreen.storyboard in Resources */, 2F7B7C6D23FA0275006D73D2 /* Home.storyboard in Resources */, 2F7B7C3D23F711C9006D73D2 /* Preview Assets.xcassets in Resources */, + 2F04A9CD23FC642500863D28 /* HeaderTableViewCell.xib in Resources */, + 2F04A9D123FC667D00863D28 /* PullRequestTableViewCell.xib in Resources */, 2F7B7C3A23F711C9006D73D2 /* Assets.xcassets in Resources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -650,21 +705,34 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 2FDB6C8A23FCAD1B00200D05 /* PullRequestWorker.swift in Sources */, + 2F04A9C923FC63DA00863D28 /* PullRequestsViewController.swift in Sources */, 2F7B7C3423F711C7006D73D2 /* AppDelegate.swift in Sources */, + 2F04A9D023FC667D00863D28 /* PullRequestTableViewCell.swift in Sources */, 2F5C382923FB12C6000985E2 /* Owner.swift in Sources */, 2F5C381923FAF97E000985E2 /* UITableView+NibUtils.swift in Sources */, + 2FDB6C9023FCBDC600200D05 /* PullRequestModel.swift in Sources */, 2F5C382723FB09DB000985E2 /* Repository.swift in Sources */, + 2FDB6C8623FC8A1400200D05 /* PullRequest.swift in Sources */, 2F5C381C23FAF97E000985E2 /* UITableViewCell+Defaults.swift in Sources */, 2F5C383723FB314A000985E2 /* RepositoryWorker.swift in Sources */, + 2F04A9D723FC6C1C00863D28 /* SegueName.swift in Sources */, 2F5C382E23FB1877000985E2 /* ServiceManager.swift in Sources */, 2F5C381F23FAF97E000985E2 /* ReusableView.swift in Sources */, + 2F04A9D523FC6BE000863D28 /* HomeRouter.swift in Sources */, 2F83AD5023FC2999006CF2E5 /* AlertUtils.swift in Sources */, + 2F04A9D323FC6AFE00863D28 /* PullRequestDataScource.swift in Sources */, 2F5C382023FAF97E000985E2 /* NSObject+ClassName.swift in Sources */, + 2FDB6C8423FC867000200D05 /* PullRequestService.swift in Sources */, 2F5C381A23FAF97E000985E2 /* NibLoadableView.swift in Sources */, + 2FDB6C8E23FCBD7100200D05 /* PullRequestPresenter.swift in Sources */, + 2FDB6C8C23FCBAAE00200D05 /* PullRequestInteractor.swift in Sources */, 2F317E0723FC39AC0078CFEE /* UIColor+Util.swift in Sources */, 2F5C381D23FAF97E000985E2 /* AutoheightableView.swift in Sources */, 2F5C382523FB0919000985E2 /* RepositoryList.swift in Sources */, 2F7B7C6F23FA07B2006D73D2 /* HomeViewController+ExtensionNavBar.swift in Sources */, + 2F04A9CC23FC642500863D28 /* HeaderTableViewCell.swift in Sources */, + 2FDB6C8823FC941600200D05 /* User.swift in Sources */, 2F7B7C6923FA0220006D73D2 /* HomeViewController.swift in Sources */, 2F83AD5223FC2E31006CF2E5 /* UIViewExtension.swift in Sources */, 2F5C382B23FB171A000985E2 /* RepositoryService.swift in Sources */, diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/arena_logo.imageset/Contents.json b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/arena_logo.imageset/Contents.json new file mode 100644 index 0000000..0a2eb8f --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/arena_logo.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "arena_Logo.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/arena_logo.imageset/arena_Logo.png b/TesteArenaFelipePerius/TesteArenaFelipePerius/Assets.xcassets/arena_logo.imageset/arena_Logo.png new file mode 100644 index 0000000000000000000000000000000000000000..62fc6de9c6fcec8b1601de973852d23ab36691ae GIT binary patch literal 17715 zcmd?Og;N~uvN#L@g1b9e+#$HTy9I(va9P}f1()FNwzxwGL6_jc-C@zd;_mX}J@?#m zPu2G)d{Z^^NZWMx(_Pa&QR=F4=qMy8FfcIa3i8sLFfg#wZ*vEv_ixYj1+EAf7&Jv& zDJgXYDJd#-SD=-xgCz`%d{n9~qPEr_k~{-V1)Fb3^2nW0njj_QLK&p?|9c)4`4}>o@<@OfXN42|V5|)-mEQ{(s$?w{H*T3#P?~Sgqzdl_) z({kO8!xU(ZBrCdU7{Of7AT-`ZV$G+_auYyd#bMr;2O+F_`?aQ!6B42qpozUQ*40Yd zGo%})7@EYt>Q3Pz?fSta@JDjNy9QA7fnkEuFG?EU!99N%kNguu7@TO0^%%Yw|*2DY`W2>@x%DcL@ftrcQ zee-7~gvhPEPwX)=QH%!}oOXr$0`JWoBQq~@LK<t+ZIS`p{N}@Xm+t9I0+_6#fNi@;tT#I!(c{_eu=cJRTSZdjU?4O z+iH<3sgOixQf;7*g;SULXqZJ>)-YJnvx-!*j$*FmV-{@1Mxh5o2+E?2PbBE0t=#V8 zYV^U~o;}}?p(1e>XIOPXS^U_|l7QYv?my;#mhMYKb{2&81@?pUlufubs9ct&UJa&y zgFP}-T=XNmG!GMenEI=kbk&KGc&XhFbslO&;ZS}|>2HR228CI)#OG;f6ymXW%%^@t z_G}Kr4Rsz4<_xXv<8$E>XP1P>RPv!HQ!*MWRRY7MtVmLQb zbTU)XlWx?z5L2x8bisNFNSeRV^enLrCq8nJj>5%A5SPPLb^EHL{|s_8CA`Bvf*aew z;>QSp+moRG_0FkhZU!zdDBuhQ4S*ymxsL?LDa(Ro&`0bd=a(Q(gBB&bm8eZa{zsA~ z@?B;Giv&{wk33H!euZ3sECygOu}PlL6|Obr3NVrA#SlKN4mXR|EHzjt%0L<`i8}?g zA;^j+C@$GY`GHa+bz7ja?{X#Vi*PKPUjRqc{ey$fDyr2~ln61Vf4W{-Ih?h7xIwWR z!@f^{^VJXeaNwc7g&*5`gJl(=c0*nmd2jpv?wy~2aqMYN_F3{B?GxL2d?3vvaw)uZ zFy%L;49OwDC|wFR6S5EzB2w9g)4_)h08W&0k;oM3$$+*wuM3-tfD5h*`#DiVjCVf2 zI3V%6!Z-*CL z-!j^9!?K~{w;Rc0l4H8#m}NB&2Em_#4!OjF{er22j~;CMS5Qs&V|Rfz;WdOdo;E~} zIw;0I=hfM-#O`wh-FJD;^B8 zF$H$>4Dpt8+)Wkq7C_V?&K+irW{GC8n`XUEbOS#uTr*ooQ%C(rt46(wM`au2kmXoO z=lBn{$`@pdV}oNuWp`!2#?}&ba#;~a5bqJy@jCH#IRLF-V0t*|Lr6|ixEd{ z=ogGBCJ1aq`|R+Ett#3hX%1*>M{HYBziPK+CSYR;O#Px`-n?+|lV@&uP;kaK*CX2l z92+)9lkLNc&Kvj^s{Rf#KS>?bR=R#RwJ0?_&etxTG;}74EOae){eDSxv2Lay!g`(pp#=O4iaUQ(uLMgh z_Hwp;<9d&JDsQYvm?*_{#3+C{jmtLVx;N`EcNep6*p8iVt|6S@vYNnv*1qFrG=xu zzVvMDXlLm$<|>*-=GZOgFH81iIe*7pMC+a5%j!>`v`d1CcA;16j^l%y9f+!g(&8Ku2CN+YZXRF;cpwB=+mo38#TXL$=&t~3q}5;ddTla#6rY^A^OKXYj3Mo34-b#Y10(yZdAzz- zu;=u0sYkWP?xAsQe(Q_F?%gmeX*nq#XuDEZV4%N!-+ZZHd)u&MpJUhxg_GKPzyo4F<$+hmQTgJzS=krs z+uA!L`oqq{L$B-;81`^*}<&~Lxi~V@kShiS$+mE-Op5OyCpRV>MpkgL#gw1u1 z;E9(36NkVGk#2tV^-%6H+XEm0k5>!mr#pF$cYVzq_`18!B5=)T=t6zWthbjrUOhgA zf>==B&wV4~N)K{gy?wi4^>a;_bGL6dIa$p!CtA?sZ_61(HODGn)R%5!w6H0_8Z+-w zV8L(w&`+z~`tch?Bv5Q}b8gE0_oJjz8PM8(A+(m7FocZ)jOPn&8Cf0KtLrm_wq?0r zKQ!AewAG>3ighJ^-Cm*$3q)HtbdPbadir^CJSbHUjEYXxGmMW*_j)t`rNb^b@j*8WXZ%ga8A_2`(Xs~JFw+e z4SMQB_m%g`?;drVP{<@MaETX-&v{R0z3TVEF7P|#$oKH_=Bho#EB?JTn7*^_VdJjw z+G2LlK*~o-N;B_!nIMX3ePL!Mj4%WlMg%{PToATERR?mZ9bA4|$^`#{`w4=evxU$- zZVHn`0E>k_!H{j%6qfNmf4JD!oI_khST;*`CzImDj*X<_9BUm7y^{kjXcna#acOdL zqqMLPbH%Kl4~9RjuFHfe4C(Yegp^U^k>}WF1NELyEFfSx!ctG~t++sTmjCPq14BUj z&kd`fNptpAd*s?`>$&TxC<|Hu9ofvj0L?Agyd9n2uwh_?y#?QkfZ#l;46wPxoO5D;MJ_{je8BkLOmtDBFLyO}qulNJUfB2f213lbD0Dyl4{pb3h_q6o3{Xa=gZvR&6O+og5AncrM9PIz${YEPM z&#s`lt+%Cvp0ur_rIXv63{h@gUg3Y?|9>F=C-J{1KmQ*kCkOw3Q~np^-;~1a|0wWZ z3jL3@{RR=_WzjvZDHTK`Q{BWTWK}zxAEOSu6et7-)@F~k8g7#5wwe#>bDVD zL0UrF8}`TuF#})br)Vhg`)~LPRfJ{<||Jk#zov=|o+JbZWm z2Y6isxbmuCSoj&76e<)noHPawIK^?|_jor?JTpzlCG9|6kK1cwVG)R*|Ks{etyW-e zr562c1y000l>j`fgg6!!{M*ot^bH3fAM2bP@t?i0AS6vQ`2R(qf_Vp!hYO;QM|l?< zL`8*!^tKE`{9oj6Fi4S9=rDQ0OmBdH!6T{gDgMRz9|7;EsDim+yf4cCMfeXqSlj#G zlEtx*f`X8yVK)90|C@2}o8Zm=yxIRR1b0(vCe#|WX5O5Nbk_uCd>l?KB%%MrxfSY2 z>NWLqtbO)tq+*|lZe@~8YNaJ{s^!Dvi$9_b=mflA6*zEGsw&OFzC!x1Z}BN0SnA<+z_NZxdQ_Kn9aeMS}CXJf79fOL#!iT6ws}l&A3X zRm*o*=z#x9q`1#MW=yvRt32WOa9J4FrOnDfuA;L!4EyiEhJxL!yi*e+e3J(qu?KFjYD75) z26WW9dERBZ47&qeU;2Z2xUGjZhfO-tcUp*%yeMP0X1XdgbH09 zI2F9mpDqb%O7Kw^)G1zpyY^z&KMqVP>kL+}ELcoZ_k@1p9L-b5tO z$1oOH(am^56`jfg$_c?^eS zBAMAnIpF-ZR}8B}?JY{p+z} zJ4&hr9c&eAjpG|z;Vxiya#FG!E`4PiYqei7e(>pkzuanxdAu0?x+atFRb|g@+HcXc z$dvNuHEb{1;X`n0dBBXmcBA&6NvNpbJ_l>|YZFr-{Y;b8)PVc9F4p!6Q;0;RI`LHs zyC`MI;qb1Ht5H(jYPCX^KdhT!Ddv0u^sRb(L1ZyoLSXM36 zJo;i;a(X1t_q@sDS-dkVgk&>4vucn) zvpQ6+2DB_}7j8OT?hCBeDrYYfl`5V%Eqj4P5q!0;wlSJ)1iQ7M{Ir^QrF`7i&(Dp} z&(|p{yC5x9^{k&#E?r&0&W0Rr2&{La@dOjb3K1COA4^d`^;zw4tEW{Rc*I@n1mN+N z{GgJFc)7W}=k{1#mCUzJJcV-PD=qqIm>KF?q2s^vU_o`5xkZ?h$E-JT8$HxQp+|!~ zO#dDHBT!r-Yb1+kbagnCIDumACb**7qfG1jv!jF{?tyT?Y_<7VZwe)gNyYdjd7V=U z3#r6DpFi)^GdjVCjp`6gZj-~8P#cg#s_#o)U?o2c_!!x%Uj@_1d>PFp-(aKxDaLAd zDoH?$kuN?h!sOv;6#~)`5sYe{)tV5E8n(QTu?*UE_;aMgB76xI|IJ=_n=k0lJZx*6 zP4cr^iRU1zzq1cvVK+PlA2j*iR8yO&^=vI}q9p zSJyC!+Ufjrs(z@=xVq;lv1iNfz20-n=q}#1b+YfmGg|deqHLy{t0K?Q<6l22b5Fw| zAlkm07^aWU#I^HR@dsUk4OC4!E_0_Piw8zdAJsNY<7)i{)tj?YSMP++Zu^7br`BcC zFu_+cE`dvC5(V?yrv2sdDLA0WXtMJoLU6n6 z29MNbmH^ZagjK|TP2O)+T(it&%q}Pnj*7>#x>6G;==t%YA)5Z@Z^_|Ft2%;A=$fr; zBZ1)KA+5q^AiRl3=krs2RrPxM!85B}toz6VId}PlkgT6ZR=S_a^?J>>m71XR774gq zVc$4x^78@YT!>OCn?f#-KVrPCp3$sF#CQM8a+BNZsjBYENH+5~63YbLVI<9rIpgEo zsEe?NhRwr=RU8*^oNTmU*UOF`{uF_XzlT3)2K>YqOU(OujHS4Mp5>{otC+gkCL7l~ zsL>cks}{vvsUA}g5mWj)oK-nK{Dq)dHmk)3Jzk;sGc0$^AMY>wu_-zYIsJCa)<_p# zFE5sb=84iz$g2%#qtoA2&XF&D;C-HV$Kw)Ni6p-}|4pPdEhIX$z7--}2qG z_6^+OD3Zti%z2`@3W$W`7eY}H{phW+_i^Uz%W&Em#L9{7HjogFQ%^dJ4(toK9@AeXV`V@hRWDRmhN@fht>Rg8v#Qdci$68SS1 z_f=ZaVjgEvf7cKFOfm4Ei+xNM} z#YCq=5CaO$p2bR@XzjHmahtbO(>`Ur@9>H_G~Ky|3;h#w>yO3wqVX0|eytHM+^19X zkfM3{-%=T0{<^$pU%L^0?vQn#bKLW3C_DsG>qWBVWacM5Rm5oF-O3ea(lt|ssp0*+ z`BL9-cvro;e_hPU@_K9Mdwf163@i1Q=F@M-!>yit@bZ<`MCZ|WQB{54I>^^)h8_nxs}J{F>lgDryXtY{B|m7r(r5cD~Kd-^wK+!h)Q z=@08)s=Gc@xD#^G4l<`;Zc$f3cj$a4c%_rDQn*ZY^z@4SDTE^%nwG45d+Yn;np(F| z5#R(NkNqbDF`oIo_MbB~rRxSZT_Qf+o^2me7{7FQ8y zP$H7kM9~ag6YD)}TJ*%O#Dvi&N(we;?<`-V;XT&22ebg!$$fnqt_El1)5kyeR}2i` z+ZQ!VMED%m|vhR32u& zDM8-+ZMT#=8cFKrgX2#?kjdL^LfL7`&bvR;SG{C` zNrl3C@J^&>)=ZyqLJaGv84)Tza=J|4b6CmGJF(3#p|hbC=`lyjFFCRp7H3TL&&Wgk zUzoGR{Cya%J&P!#P#c+2x8;8~YBwnQEacjB`JR3?mKPCv3()*Ll`(!>FZA(1x**3- z3VDL*m*}(sQY@BjBg=46&cBhj18LL?d!GZ zE}ATG9=zGst@l)jZFWoGFtX<%USM8xWnFv9!@MRx3 zU#n=gm0!MQa>UQROKw`=LjC#O#pL{GEdf9M5C4UV`ZHK?+NMzf2XD8cZZHoQO{)pm z4%LiuTQ5L$mS-S9dcpjuyt}=t+N3!Xx;!k@Q$NSicTRL&q1g#od)4IodP(fB`eu&n zXl8<14DL(2CAJ7b$RgdDDls*p+QxV%H+SrBCF->{*uO{E-wqsY&*T@sV*xp$PQHQe zAOW0W9OU$F<|oWwTXeJP*wBAba#J-gb{QcQZUkBl(kZJ6scAl36OkyM{EgNbnJF0! z4EXU;NMdmi5Bc21Gh5>EnIfCzj`Q^WG0@V7>cnqbpwIyru{x&b`2z^#Z-+|PBNC{8Qt%SpgIF z^5_OR`&q00MqylaCFI}W_r+2ARuy89 z?Y%=%tn1V!A;(t(&5!Td4s>&f;emg&ZgmO9t2Yto>s}mH>Q49Db|8NXbqztQ40qx*#tf0jkPx# z`f8CbxON0|2gG3&ApLT!%*PO0%vals9X%zRO|6`F&NF0K-&V+hKC*Ubr+uKzDjV7{b+g3T;{6Ix z$lz9{Cehr`8=djpJ*GRL9HsPWplm_M1%`mK+dbCOFM|ruJ=GSt5%B^KwNV|rUrR@g z&Tqs#wvIbG2_7Ah(yw7RJ<d$ygh#AqLLDOc$A+UWC^SM8Mzz)=Qbw4G4d(2i4z=y_jlD>~<T8w&8W=0g`NkTFxip((r9)*4Ut#N{m7#^Dy}6rR&qR9lwB4a|wMBiZ zY2}+Xt(-}jqHc+=I+n9-^cJpaE*!t(Sik;Qw`Q-4H!HP1z!;4ybi?m#<0_~pDf(aEqW_9bAU zUG`e;UPa$h>-JFy`f2R)rSN$W>tlU?RsPB;zBl@PZ{6C)=kSyG#k%{;mNL?K`n7i` zHy~^f(NM~tAi0mZndE*rcWSfe58Y}EUc-{Z!y5(oDr2+ubgwoox;p0Gd@93-j~{oZ z`QO#2AB>dp!$+-Gf2zV+d+cd;i3tz1c}Tys{aDw0SsAbTIQSJ)kQIJ^sRNc*+0aQ2 z!Y1|OZrs=@B}+|R#b+|YpRCGZ8G;o{c5Sug8H~O2(RB!(Iv}diNZjJBFrrF>yDDZF zkh_9R$SL!ku$SdSBHLD%*VjkCiLvK(CawGV=3wW;lvN4*{Oy=@9PtZ;1#%uBwED<2 zd*tp1g9$G`eT-PJ_%%SkEARd4Ia5ihYMCo^x7n}MiG&ev8L^<(&CZ)cVQ(gUSOx->gSt8f`av9hVUAr;q?0V|v2V z{jaG4FLvF3#akHS%q518$?CdP!I1o1=`;p7}jKzTYi3j=!4hzXA5%-Bs0Ydi<8d~Gs_GjLL1%sR)X7SiY5?o}o@l-m8 za>M|1%GB)ez4z{V5b)|LoPI*P@;#DbDw~Ss%t!xw<+Xho-;OdT;@b5xt-!xTVY(Rf zV!xn;O5dwm;>t;Y;&ItfW|r%JRks+!WCoEu60ahT5#t6e5?^t3BS zEfb6ZZxpulLQq?}_xcb%_JHb1A1#?MAbWanl^$ngfQ?5!L(K>e{o#^xwNYbh2o#C! z|B{ZXRd6(+@?`Vg|7yVdL`)eNl~kRX_Js?WMiSb|&Bhn2jXb^H+k6PzOr0tEsUL4y zrm@$gm?mbLqj5hrVJp6{`dqfPrA~-6S&`#)CH`B2g73<2o$i*J(?5HBECnleY|}tl zF9$P_CYF2dA-m$Q7q`t@fq%ybB_yI;_1kf23)!1cOjw?u(BDpgxM`DA;DEvfmO~zr zUg2P1USCH}Ab((BC@TK>DR69r7=$M?AJ863n}LOo0jD61rJexFz<`a4M(*`_iHIQ5 z!}{*UR32338k{s5U5;3U6d9ej3MJnUEO;r^;xv~;3qn!UH@%1GuGN)!wOF^c`TFXG zSDIB+oE%i%cA=PbqKF`@EKOl}qUL+YzMStIN@JB21a%%C;fIE^w>60I2spgvD82qR z7_l85%2ezM4wj?^&b@VoWt;W2)%Qa~c1}I55D!EPED(GaYVT8DT+gr6{bx33Ivl0i zHkP~ar{_A)=C|UZ=L)E?7h)$nKWF!z*c5-1phAji*}K%3!FnY+0nn={)<9v%J!szD z0ZeU^|M2yol9cE)i>r(T8vn5T%Mz~bu2c(dCid(3I_ckO>(fAs?|Y6-G0c(mP0cN- zCe@`;x?|CXqAI@(*%ZqSVGdl`(!T<82Iti4z)U6(;8$1qutvr}Sj#YQ!3)UGS7Ni^ zf<0euwtk;Hg>qSnh(h6d#fEuAOpiD#Fu_mcm&pmiB;TRAR(I4V41oWZ$MSgoyO;fk z5a5BDiWf{Gn*|`(?^&7F`U9uSMOgweK1jc*{AZ7-e7qCfM=Yq!O!GBcyxOHFB4^^w z4C^Jzxv|k1+gPAYgT{+BzE^QpJO0#k*y&8;>mxw(K6Qaw@ov&HcAuYaGQ@yVU4k+h zbs>jyPChWD2{1i{jB6X}xjE=!Ci zVxmg;ndwh?FSNvfS{BVA)OR`v^l7$cI+ezq;cn#AI{8n;teWZaOEh~I3L<5=qTFRO#?;x{QNuL=krzpB_Sca~3&xbOb2L{ac#6Pa;|vU0 z$zef*2aOA@t=Tj$1hm);orFu65s;Xh%OlHt1j1b_zu~KUDIe$I3pWeh6h(-5%yEfc z_x42mw3iR;V9S$v;5Go|!PIu7G8$?(3F7W=Uah>yX*L&Cq9i%Ic<~s3N*{P_Tg8lW z5@dWQ81ib(N8~)vJ{*6Lf1v^x{Yq};(+jw5M8E^(SHjsIFqe8JGZF6Cvrf+jK}b!b zHxquh5L8q)FTI}1I4#=6&XPBlCpOA~x&&@rZxPX;ipPQ3MkCU4?bZ~ZrP+ngndEd> z^<3o&H*tvn}RyBtuNVTMjkVpy(|+*#OdGHVh`$iNQ4D<=u!J`?^<%( zABd6vO>k0QRtP^cBPW@mtc6l@y8fN`dS~hDaub-+F)oirz{n){Sc_M$?owB-kKWaz zdv9{fB~(f~%}J%nW&`{}PcC5MQX030f{pb)5udzIqR)D#!^xB%-=? zIbC+wxb4^Iin>N(Qp+pOp_1%Yt(MR=9iJLsU~}4&_^@P z1F0!7h@s>e6Fr(mr_h9RgN2g}Qu@UzZIDYj*aMqc$Csu9$Gf0_!RDDn_< zR6hWDb_yKqGJXF&bpE_tDf3!HGBJ-TeqxHuf$@37Zh%>;HEdN0TeI=tG(Vb}WApNMYjtPIE% zb%K5Ng1XYTqj^^$A+L&UWmwG~f4|XwEodup)epQ8VZT(}yq$aYMV!@06U~d?_M`|mi{|?- z#Rhvq9J7UefN{HvY@TqBS&X>Xm~-D5 z#}VPLLG#5gsoR`q?YUFm9-d!*p%i_S2fj=6)skd_0z^ zcM=@f6VNMl!2Hf}smleyFqo~Iq%#C_@9TAMYMsYkX-9Dj`3DhPuYOxS>QoBBEJ(_N zd~&1wDT#pGXVHqnRJ4k#r*pUP_dVEUokm|L?n9xsAo6MrEK$F@j*GP9_#yfIuw0_2HiLxG>_<=7p6VV5Jdrj>sX9}ormM? z>Aa2%F30Z%rzMIKUT5{c;RDm{0YUEPYxis|z4Dena)%<7lK*bsI0=~lvm;l|6p%Ng%_-MZ77>BCV};ul_0IH zP=aF`o1VHlp&sLpfPJ4*?6lmCpig8*n`k87?zVu6Kdq?eFM1hJ!Wb#GQaH)Q^+qSN zj}%Dkr9N)pA}g}2<)GW|mrZEWEIwlAJ5Bg z5Z(p%>x+ww?+;1)DkEeD7(X+|YD-sA$TPBthu*RJ*xe>+lxfTJ9fYxqy~NSIKoxY^ z14x2VzYU(<0)Mar8xQ1b1bL&FlA^&^`IMk>V$vZOZexdu&@AY$(cQ8}8M|^emgy}} z3w}n!&%1Z+7vAli=;Uf17bBJ+eml9pM2fnb&O8Hjan=wA2*jkBTd8}TjJOSD zKz?y4#7)W>*6y9oURY2cXwHr0I*?Xo*5u3Ww;J>j`Uocpa#e{`qW?bSVJo(x;$eGr>0FBxbw&1 zUXMEWa&lz#w~z={sq55vxr~#xd+3r`G#($;$!{R3NPeEh6@c=K3#z#(wd}dAD>m51y=p zd=rpA4npW#CWF7T>!(|>>*a}^mq1wkgSBg04P|9Yg7epm_44;*ws<~IzN-R2y@4l* zA}u-5ewVG(+x5p|1qS@f~g$rUfdr;Bh=1q^2@`ucYJ*&OX_yat|UWLr<| zb}9xnZ0L5z@@|1u+lzN*>CN-K^gYF!>+e}j5$R16D=o2jnn#wU`%njQ8jijkFy+di z$XJ~LExN|-`CQh*$H3}y2MDvJ7F>2-%BX@#uk~Mlb}+NDmc*~$CkY)>LghSuItiV^ z)G8qI)W~@p9xFWZEVe&U|9EK6x1FUT!}B_9k;_rlcK18s+x_re;I0ddN;iF&AzuQE z^z9%Va|Dnmxk%hmftYK+yT;kMtX?d2sI@H>n0&L}rgl_A4d`Y!L|TpR;7dC9w%2l4aqWZrva@43hCQIX)uw?&GKtcvv8|8z8@2Bkg2Bg7Xh74R4kfYF-X#a zI|E00palFhSXnRoE^E}^j=#;ZEvXH?z-tv4;~$C!+E481CdWvX8uLt2D|Pmx&#g5= z!ZZ2!(NE)fGzao`HP92m(C{fU%uWH~823g!5cbabh!|%d0O4uL0jMd~rwb+=d54S* zv!V9N479sgOF;U3g{kUX3iHdX)bv0;hnmN}MUVy&$0HI?Np|WIIXf|kLL-+e<~JM? zoX=#uDZK}dbo3Ib1MkN~ROx6jEnP-dO@@%fgOC>CY`brqB#Q$o;K})E*66cE8l5gK z{1N;a!cPbrsBTf^kLw?TcGAZu2Nr(3}Wmxu$dPtNhmY+s!-&N046u17vzUoO% z`pX@zJBJG+V7H8VAJqp7%r61x9}rHy*!S_YZss-%M$D`DA&s*6_sr$H%*5GWIHX}p zBh(KJFMpHJwHxt)@@6>#A|8feO7npjv!s9ER}s&*0=)e|6Jn(U!~z#RUKhP&e)(=8 zQCAaz-a!_v;~L_Uaoy$hTf=L>xh`z{%lI7Ym9e%%+8+Iqg5EU6efg;^|>$0J2qVy5Ax>G_Z>lhRm z0YY2%kobKGJ<2&3Dow4YWV&g!#S6{~!bxjQ__uHHx8o_)_T(l3+V3EzrzYpyzahm* z^4!K$o2@4ZlMl)BVo=sZ8y92zrxRm1PLx8+#vj;vm>y^oERB-nmD430nSU!CeVwf! z%ruC4tRf`%>PBm@^l?qID6VQlkVP)<8!PUog*6M7kCq|ZtT-kmdtt4D_jz)D{HFpK z#cdxbmAOi(r^TKzaTx>gHl2eHe8xB;-S<_NTI34{VX^^VHBAD>gRU8Y{gG{VXVs^2>8#_MpVWscDX`;%9j)kJ z;XEN#1kD>II8Q^;8IPet$A1=DrBQxqsPx%}(%V*>^pf}olmZu=La#ok&0eJMaNR2c z(Wn3i%;yp7ek43f-2ji}=t~O#$#%xa3yXWiFLnn^*R!<@VFR%!?eF$@TZ0FVC;3tx zK$^x}I#BP>eH_{d{03LqU#D!Df?CaFH{-Fsx4GU2g89_fNQ6+=#h8iBJUBs(Q#a-= zmUjeD9%WEz^f&nkT4@jiTnCofz)oPJHt3{VRpK z?!yDr)04Bo)cZTwPhTFYT&~BF6H5uj&c@j!K$C{D!;8G^Y1vffIO{z^J}pk$=<-z3 zFQ%0QA}Q9$X{aOqSM?I-bJ}&M_u78$f2hb_h&tOC6o*olQYkBhHm6PN@EEv=U zNX`t10GZ6k^MoQy47{{&djWfVcmx$@@qrw5iN-hSUp$Y^Q=S#R8`UQ7nGg`83MU-j zgl7`C&>he1+}Fd79{>YOh3ax-XtP`D-BralZeRHuDal>$BmkZWl)E1lK3i38%GHV` z^OUZc#j<6zN?&WyUC;b@VrDpOhXLfmE3MXdqA5)R`U_^HYuBH6g>zM+M2Uv|))-kd z!F}=P;gKcYm)IsLi7gf2%s)SVxL3)2e{t_nk;zHE>;Z6d|K!&Ru`t2rU?IG1BTak6 z_>dlpsZ`(bNSlhl{Wv9Y=S&KlJS;F$$Mk2v)nP= z3h;>r+=v5}Rz5y~0U&r&&6H8-r8M8rUDN0W5G9Uxo|+tZIa($cx_9FYOy#0-b@*yU zYH!J1dqlc_Qv!`^CbsVsTLu4uOr4bxVSqmJP<+tLeG1u8jh5Fj_${D`Za6%G06;&; z=GxoMt;)eRogI601XntG+Z3#@;XZsseKh!UN_`LeCiAw2uX1evSp^*or*|b^%MZez?xcgA3YLI z1^R<^8F=(%Y1+&>>I>Z;d1c_K)P+x#$6TkJZ_bQ3qBLn>?Ndq(VUsNQl`)G3$=rB35?;D0b#(lMmPN2 zG>edbb9m~wgdB#6?#Z8;na{<_y=2QP#a?XM?33x9I!n(S0CK(~PW?{T8oSe7Ry^cw zKB;q&p;TJUQRTwUN~gYsfSHK0QA&aohfI4$Ky04qjzXNg%MpE67tULv?Mz0@UCh{X zXP-J-wv5uYBW1cgLVOvM`*MdaWmwNhPhMd7hitvECiLg|6p<~LE1E1DH*hWCJ=%#P zA7=Im-H>#2^p5C8e0&Z^#UVI8uKrd4$}(-TAAKnfvRb2^mzVqgCsqb!tnatx=k9it z^Y=7RZ|M+F?>>#%4us5+ycY#uWP>nYcq)UCYUIoysX=~9pdhZw1ztCy{AJd9bYA{> z@eT}b-{GR@e#wR)-7uT*0)d)pnzreV`HOSNsIUb2+r#UaUny?0&y^)gn-2%e&Z;|K$?)l-r#TkHH5xYN_}nEy%qU%@5Kll;@|zuJ^?( z>XaJnDm$>ly*^?RI0Vq#g>kE;vuJUVr{{}pZkhZbOTPW8ZO`F~HL8B~UlZrtNb7Bz z+|IT{4=)6HfBV0Bk-u|~tY-s%e;h?^zo>%ECHJ$4E)&|*=RDnJ=P+4(?Z9Hn(h~$c zyEIFI@{BcmTtCpPS|MUH_Jx#OY#s5<3NEMNczyAkIhjEJKz$HUxY4s zG_jz&7H+`AhwHn%g{-vtu;^G*`#?j=CD)`2g}ntaXW&7f7$6qIGhVRy>9h6jV?uyK zqO0OK2i0;U0r^d2D9g0a%V@DfUTuZ~Rl+w6k>)^ubwant zp5JeJBBV6}3wwzPbp)@vu=mY7HNiN@_GlO;jp3FzbC8uR3{lrT zYsh@-jh=hmErR;geu>btL}#_n6~KAVp!~nNc_m)vTfINt+y6t~e$mtQ3+B&YnaJn1 z;na7ItDL_-zm#=ava(HwH|qR)9v7`2k8?fbKRqnlbAs`o)Ui`3XPGMA1=sUu-B`1) z>YypdmZ+~d3l-dsl!4m_g}mDekxxhFf}wL9IgL*Q!DD{RjFGaPOC-z zKkdf!Fl=?))Pf&-ujRSsq+VNATfbTT|6AAJW;eRoO@C*VrcL!r)SlpaKxxBi#R=EN zUh0L<3QO#6016}sp0H$^=26VI^Xvs6X9GtB%O_4o? CGFloat { return RepositoryTableViewCell.cellHeight } + + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + self.currentRepository = repositories[indexPath.row] + self.viewController?.router.goToPullRequestList() + } + + func scrollViewDidScroll(_ scrollView: UIScrollView) { + let currentOffset = scrollView.contentOffset.y + let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height + + if (maximumOffset - currentOffset) <= 40 && isLoading == false && offset <= maximumPage { + offset = offset+1 + isLoading = true + viewController?.getRepositories(page:offset) + } + } } diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeInteractor.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeInteractor.swift index 6214f9b..3dbb5cd 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeInteractor.swift +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeInteractor.swift @@ -14,18 +14,23 @@ protocol RepositoryListBusinessLogic { class HomeInteractor: RepositoryListBusinessLogic { var presenter: RepositoryListPresentationLogic? + var isLoading = false func fetchListRepository(page:Int) { - self.presenter?.loadingView(isLoading:true) - RepositoryWorker.getRepositories(page: page) { (repository, msgError) in - self.presenter?.loadingView(isLoading:false) - if let messsage = msgError { - let response = HomeModel.Response.init(repositoryList:nil, isError:true, messageError: messsage) - self.presenter?.presentRepositories(response:response) - } else { - let response = HomeModel.Response.init(repositoryList:repository, isError:false, messageError:nil) - self.presenter?.presentRepositories(response:response) - } + if !isLoading { + isLoading = true + self.presenter?.loadingView(isLoading:isLoading) + RepositoryWorker.getRepositories(page: page) { (repository, msgError) in + self.isLoading = false + self.presenter?.loadingView(isLoading:self.isLoading) + if let messsage = msgError { + let response = HomeModel.Response.init(repositoryList:nil, isError:true, messageError: messsage) + self.presenter?.presentRepositories(response:response) + } else { + let response = HomeModel.Response.init(repositoryList:repository, isError:false, messageError:nil) + self.presenter?.presentRepositories(response:response) + } + } } } } diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeRouter.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeRouter.swift new file mode 100644 index 0000000..6b41217 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeRouter.swift @@ -0,0 +1,17 @@ +// +// HomeRouter.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 18/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +class HomeRouter: NSObject { + weak var homeViewController: HomeViewController! + + func goToPullRequestList() { + homeViewController.performSegue(withIdentifier:SegueName.goToPullRequestList.rawValue.self, sender:nil) + } +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController.swift index 224951a..7215376 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController.swift +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/Home/HomeViewController.swift @@ -17,6 +17,8 @@ class HomeViewController: UIViewController { @IBOutlet weak var tableView: UITableView! private let dataSource = HomeDataScource() var interactor: RepositoryListBusinessLogic? + var startPage = 1 + var router = HomeRouter() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent @@ -27,10 +29,7 @@ class HomeViewController: UIViewController { setup() setupNavigationBarItems() configTableView() - } - - override func viewDidAppear(_ animated: Bool) { - self.getRepositories() + self.getRepositories(page:startPage) } // MARK: Setup @@ -39,7 +38,10 @@ class HomeViewController: UIViewController { let interactor = HomeInteractor() let presenter = HomePresenter() presenter.viewController = viewController + router.homeViewController = viewController interactor.presenter = presenter + dataSource.offset = startPage + dataSource.viewController = viewController viewController.interactor = interactor as RepositoryListBusinessLogic } @@ -50,14 +52,15 @@ class HomeViewController: UIViewController { dataSource.registerNibs(in: tableView) } - func getRepositories() { - interactor?.fetchListRepository(page:1) + func getRepositories(page:Int) { + interactor?.fetchListRepository(page:page) } - + } extension HomeViewController:HomeOutput{ func loadingView(isLoading:Bool) { + dataSource.isLoading = isLoading if isLoading { self.view.loadAnimation() } else { @@ -70,8 +73,19 @@ extension HomeViewController:HomeOutput{ AlertUtils.showAlertErrorWithMessage(title:"Erro", message:viewModel.messageError ?? "erro a carregar repositorios!", viewController:self) } else { if let repositories = viewModel.repositoryList?.repositoryList { - dataSource.repositories = repositories + dataSource.repositories += repositories } } } } + +extension HomeViewController { + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + super.prepare(for: segue, sender: sender) + if segue.identifier == SegueName.goToPullRequestList.rawValue { + guard let destinationVC = segue.destination as? PullRequestsViewController else { return } + destinationVC.currentRepository = dataSource.currentRepository + destinationVC.title = dataSource.currentRepository?.name + } + } +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestDataScource.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestDataScource.swift new file mode 100644 index 0000000..f3122e1 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestDataScource.swift @@ -0,0 +1,57 @@ +// +// PullRequestDataScource.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 18/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +class PullRequestDataScource: NSObject { + weak var tableView: UITableView? + var pullRequests: [PullRequest] = [] { + didSet { + tableView?.reloadData() + } + } + + func registerNibs(in tableView: UITableView) { + tableView.registerNib(PullRequestTableViewCell.self) + } + + private func generatePullRequestTableViewCell(forTableView tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { + + guard let cell = tableView.dequeueReusableCellWithDefaultIdentifier(PullRequestTableViewCell.self) else { + return UITableViewCell() + } + cell.setupCell(pullRequest:pullRequests[indexPath.row]) + return cell + } + +} + + +// MARK: Delegate TableView +extension PullRequestDataScource:UITableViewDataSource { + + func numberOfSections(in tableView: UITableView) -> Int { + return 1 + } + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return pullRequests.count + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + return generatePullRequestTableViewCell(forTableView: tableView, at: indexPath) + } +} + + +extension PullRequestDataScource: UITableViewDelegate { + + func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { + return PullRequestTableViewCell.cellHeight + } +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestInteractor.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestInteractor.swift new file mode 100644 index 0000000..4b17031 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestInteractor.swift @@ -0,0 +1,32 @@ +// +// PullRequestInteractor.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 18/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +protocol PullRequestListBusinessLogic { + func fetchListPullRequest(owner:String, repository: String) +} + +class PullRequestInteractor: PullRequestListBusinessLogic { + var presenter: PullRequestPresentationLogic? + + func fetchListPullRequest(owner: String, repository: String) { + self.presenter?.loadingView(isLoading:true) + PullRequestWorker.getPullrequests(owner: owner, repository: repository) { (pullRequests, msgError) in + self.presenter?.loadingView(isLoading:false) + if let messsage = msgError { + let response = PullRequestModel.Response.init(pullRequests:nil, isError: true, messageError:messsage) + self.presenter?.presentPullRequests(response:response) + } else { + let response = PullRequestModel.Response.init(pullRequests:pullRequests, isError:false, messageError:nil) + self.presenter?.presentPullRequests(response:response) + } + } + } + +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestModel.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestModel.swift new file mode 100644 index 0000000..587f3d8 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestModel.swift @@ -0,0 +1,17 @@ +// +// PullRequestModel.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 18/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +enum PullRequestModel { + struct Response { + var pullRequests: [PullRequest]? + var isError: Bool + var messageError: String? + } +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestPresenter.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestPresenter.swift new file mode 100644 index 0000000..45bd10c --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestPresenter.swift @@ -0,0 +1,27 @@ +// +// PullRequestPresenter.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 18/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +protocol PullRequestPresentationLogic { + func presentPullRequests(response:PullRequestModel.Response) + func loadingView(isLoading:Bool) +} + +class PullRequestPresenter: PullRequestPresentationLogic { + weak var viewController: PullRequestOutput? + + func presentPullRequests(response: PullRequestModel.Response) { + viewController?.displayPullRequests(viewModel:response) + } + + func loadingView(isLoading: Bool) { + viewController?.loadingView(isLoading:isLoading) + } + +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestsViewController.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestsViewController.swift new file mode 100644 index 0000000..edf1837 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Scenes/PullRequestList/PullRequestsViewController.swift @@ -0,0 +1,73 @@ +// +// PullRequestsViewController.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 18/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +protocol PullRequestOutput: class { + func displayPullRequests(viewModel:PullRequestModel.Response) + func loadingView(isLoading:Bool) +} +class PullRequestsViewController: UIViewController { + @IBOutlet weak var tableView: UITableView! + private let dataSource = PullRequestDataScource() + var interactor: PullRequestListBusinessLogic? + var currentRepository:Repository? + + override func viewDidLoad() { + super.viewDidLoad() + self.setupTableView() + self.setup() + self.getPullRequests() + } + + private func setup() { + let viewController = self + let interactor = PullRequestInteractor() + let presenter = PullRequestPresenter() + presenter.viewController = viewController + interactor.presenter = presenter + viewController.interactor = interactor as PullRequestListBusinessLogic + } + + + private func setupTableView() { + tableView.dataSource = dataSource as UITableViewDataSource + tableView.delegate = dataSource + dataSource.tableView = tableView + dataSource.registerNibs(in: tableView) + } + + func getPullRequests() { + if let owner = currentRepository?.owner,let nameRepo = currentRepository?.name { + interactor?.fetchListPullRequest(owner:owner.name ?? "", repository: nameRepo) + } + } + +} + +extension PullRequestsViewController:PullRequestOutput{ + func displayPullRequests(viewModel: PullRequestModel.Response) { + if viewModel.isError { + AlertUtils.showAlertErrorWithMessage(title:"Erro", message:viewModel.messageError ?? "erro a carregar conteúdo!", viewController:self) + } else { + if let pullRequests = viewModel.pullRequests { + dataSource.pullRequests = pullRequests + } + } + } + + func loadingView(isLoading: Bool) { + if isLoading { + self.view.loadAnimation() + } else { + self.view.unload() + } + } + + +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/Manager /Routes/Routes.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/Manager /Routes/Routes.swift index f04c72a..d6752ba 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/Manager /Routes/Routes.swift +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/Manager /Routes/Routes.swift @@ -16,7 +16,7 @@ class Routes: NSObject { } // MARK: - PullRequests - static func getStatements(owner: String, repository: String) -> URL { + static func getPullRequests(owner: String, repository: String) -> URL { return URLBaseManager.baseURL.appendingPathComponent("repos/\(owner)/\(repository)/pulls") } } diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/PullRequestService.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/PullRequestService.swift new file mode 100644 index 0000000..4cde32d --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/PullRequestService.swift @@ -0,0 +1,41 @@ +// +// PullRequestService.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 18/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit +import RxSwift +import Alamofire +import ObjectMapper + +class PullRequestService: NSObject { + class func getPullrequests(owner:String, repository: String) -> RxSwift.Observable<[PullRequest]> { + + return RxSwift.Observable<[PullRequest]>.create({ (observer) -> Disposable in + let url = Routes.getPullRequests(owner:owner, repository: repository) + ServiceManager.defaultClient.request(url,method: .get, + parameters:nil, + encoding:JSONEncoding(), + headers:nil) + .validate(statusCode: 200...399) + .responseJSON(completionHandler: { (response) in + if let dic = response.value as? [[String: Any]] { + let pullRequests = dic.compactMap { + return Mapper().map(JSON: $0) + } + observer.onNext(pullRequests) + observer.onCompleted() + } else { + observer.onError(NSError(domain: "br.com.testeiOS", code:403, userInfo: ["message": "Erro de parse"])) + observer.onCompleted() + } + return observer.onCompleted() + }) + + return Disposables.create() + }) + } +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/RepositoryService.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/RepositoryService.swift index 826eaf1..abeb338 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/RepositoryService.swift +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/Service/RepositoryService.swift @@ -27,7 +27,7 @@ class RepositoryService: NSObject { headers:nil) .validate(statusCode: 200...399) .responseJSON(completionHandler: { (response) in - if let dic = response.value as? [String: Any] { + if let dic = response.value as? [String: Any] { if let respositoryList = Mapper().map(JSON: dic) { observer.onNext(respositoryList) } else { diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/HeaderTableViewCell.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/HeaderTableViewCell.swift new file mode 100644 index 0000000..96b8e27 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/HeaderTableViewCell.swift @@ -0,0 +1,24 @@ +// +// HeaderTableViewCell.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 18/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit + +class HeaderTableViewCell: UITableViewCell { + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } + +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/HeaderTableViewCell.xib b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/HeaderTableViewCell.xib new file mode 100644 index 0000000..7c77bc9 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/HeaderTableViewCell.xib @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/PullRequestTableViewCell.swift b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/PullRequestTableViewCell.swift new file mode 100644 index 0000000..8118b71 --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/PullRequestTableViewCell.swift @@ -0,0 +1,51 @@ +// +// PullRequestTableViewCell.swift +// TesteArenaFelipePerius +// +// Created by Felipe perius on 18/02/20. +// Copyright © 2020 Felipe Perius. All rights reserved. +// + +import UIKit +import SDWebImage + +class PullRequestTableViewCell: UITableViewCell { + @IBOutlet weak var titlePullRequest: UILabel! + @IBOutlet weak var descriptionLabel: UILabel! + @IBOutlet weak var usernameLabel: UILabel! + @IBOutlet weak var fullNameLabel: UILabel! + @IBOutlet weak var photoImageView: UIImageView! + + static let identifier: String = "PullRequestTableViewCell" + + static var cellHeight: CGFloat { + return 140 + } + + override func awakeFromNib() { + super.awakeFromNib() + self.setupViewCell() + } + + func setupCell(pullRequest:PullRequest) { + if let user = pullRequest.user { + usernameLabel.text = user.name + if let avatarUrl = user.avatarUrl { + self.loadImageView(url:avatarUrl) + } + } + fullNameLabel.text = pullRequest.fullName + titlePullRequest.text = pullRequest.title + descriptionLabel.text = pullRequest.body + } + + func setupViewCell(){ + photoImageView.layer.cornerRadius = photoImageView.frame.size.width / 2 + photoImageView.clipsToBounds = true + } + + func loadImageView(url:String){ + photoImageView.sd_setImage(with: URL(string:url), placeholderImage: UIImage(named: "photo_user")) + } + +} diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/PullRequestTableViewCell.xib b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/PullRequestTableViewCell.xib new file mode 100644 index 0000000..a67431b --- /dev/null +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/PullRequestTableViewCell.xib @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib index 9bf7c85..0ca5d02 100644 --- a/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib +++ b/TesteArenaFelipePerius/TesteArenaFelipePerius/View/Cells/RepositoryTableViewCell.xib @@ -23,7 +23,7 @@